Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this C++ function in Go with identical behavior. | #include <iostream>
auto Zero = [](auto){ return [](auto x){ return x; }; };
auto True = [](auto a){ return [=](auto){ return a; }; };
auto False = [](auto){ return [](auto b){ return b; }; };
auto Successor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(f)(f(x));
};
};
}
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())
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2;
dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2;
dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0;
dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << 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 + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
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 ) c |= ( 1 << xx );
}
return c;
}
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 );
}
void findStart( int& x, int& y, int& z )
{
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val == 0 )
{
x = a; y = b; z = 1;
arr[a + wid * b].val = z;
return;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7;
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( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2;
dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2;
dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0;
dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << 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 + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
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 ) c |= ( 1 << xx );
}
return c;
}
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 );
}
void findStart( int& x, int& y, int& z )
{
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val == 0 )
{
x = a; y = b; z = 1;
arr[a + wid * b].val = z;
return;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7;
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( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2;
dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2;
dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0;
dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << 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 + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
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 ) c |= ( 1 << xx );
}
return c;
}
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 );
}
void findStart( int& x, int& y, int& z )
{
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val == 0 )
{
x = a; y = b; z = 1;
arr[a + wid * b].val = z;
return;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7;
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( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| package main
import (
"fmt"
"sort"
)
var board = []string{
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0...",
}
var moves = [][2]int{
{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2},
}
var grid [][]int
var totalToFill = 0
func solve(r, c, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Change the following C++ code into Go without altering its purpose. |
template<uint _N, uint _G> class Nonogram {
enum class ng_val : char {X='#',B='.',V='?'};
template<uint _NG> struct N {
N() {}
N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}
std::bitset<_NG> X, B, T, Tx, Tb;
std::vector<int> ng;
int En, gNG;
void fn (const int n,const int i,const int g,const int e,const int l){
if (fe(g,l,false) and fe(g+l,e,true)){
if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}
else {
if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}
}}
if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);
}
void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}
ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}
inline bool fe (const int n,const int i, const bool g){
for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;
return true;
}
int fl (){
if (En == 1) return 1;
Tx.set(); Tb.set(); En=0;
fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);
return En;
}};
std::vector<N<_G>> ng;
std::vector<N<_N>> gn;
int En, zN, zG;
void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}
public:
Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {
for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));
for (int i=0; i<zN; i++) {
ng.push_back(N<_G>(n[i],zG));
if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);
}}
bool solve(){
int i{}, g{};
for (int l = 0; l<zN; l++) {
if ((g = ng[l].fl()) == 0) return false; else i+=g;
for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);
}
for (int l = 0; l<zG; l++) {
if ((g = gn[l].fl()) == 0) return false; else i+=g;
for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);
}
if (i == En) return false; else En = i;
if (i == zN+zG) return true; else return solve();
}
const std::string toStr() const {
std::ostringstream n;
for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}
return n.str();
}};
| package main
import (
"fmt"
"strings"
)
type BitSet []bool
func (bs BitSet) and(other BitSet) {
for i := range bs {
if bs[i] && other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func (bs BitSet) or(other BitSet) {
for i := range bs {
if bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. |
template<uint _N, uint _G> class Nonogram {
enum class ng_val : char {X='#',B='.',V='?'};
template<uint _NG> struct N {
N() {}
N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}
std::bitset<_NG> X, B, T, Tx, Tb;
std::vector<int> ng;
int En, gNG;
void fn (const int n,const int i,const int g,const int e,const int l){
if (fe(g,l,false) and fe(g+l,e,true)){
if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}
else {
if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}
}}
if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);
}
void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}
ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}
inline bool fe (const int n,const int i, const bool g){
for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;
return true;
}
int fl (){
if (En == 1) return 1;
Tx.set(); Tb.set(); En=0;
fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);
return En;
}};
std::vector<N<_G>> ng;
std::vector<N<_N>> gn;
int En, zN, zG;
void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}
public:
Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {
for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));
for (int i=0; i<zN; i++) {
ng.push_back(N<_G>(n[i],zG));
if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);
}}
bool solve(){
int i{}, g{};
for (int l = 0; l<zN; l++) {
if ((g = ng[l].fl()) == 0) return false; else i+=g;
for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);
}
for (int l = 0; l<zG; l++) {
if ((g = gn[l].fl()) == 0) return false; else i+=g;
for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);
}
if (i == En) return false; else En = i;
if (i == zN+zG) return true; else return solve();
}
const std::string toStr() const {
std::ostringstream n;
for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}
return n.str();
}};
| package main
import (
"fmt"
"strings"
)
type BitSet []bool
func (bs BitSet) and(other BitSet) {
for i := range bs {
if bs[i] && other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func (bs BitSet) or(other BitSet) {
for i := range bs {
if bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <iomanip>
#include <ctime>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;
class Cell {
public:
Cell() : val( 0 ), cntOverlap( 0 ) {}
char val; int cntOverlap;
};
class Word {
public:
Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) :
word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {}
bool operator ==( const std::string& s ) { return 0 == word.compare( s ); }
std::string word;
int cols, rows, cole, rowe, dx, dy;
};
class words {
public:
void create( std::string& file ) {
std::ifstream f( file.c_str(), std::ios_base::in );
std::string word;
while( f >> word ) {
if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue;
if( word.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) != word.npos ) continue;
dictionary.push_back( word );
}
f.close();
std::random_shuffle( dictionary.begin(), dictionary.end() );
buildPuzzle();
}
void printOut() {
std::cout << "\t";
for( int x = 0; x < WID; x++ ) std::cout << x << " ";
std::cout << "\n\n";
for( int y = 0; y < HEI; y++ ) {
std::cout << y << "\t";
for( int x = 0; x < WID; x++ )
std::cout << puzzle[x][y].val << " ";
std::cout << "\n";
}
size_t wid1 = 0, wid2 = 0;
for( size_t x = 0; x < used.size(); x++ ) {
if( x & 1 ) {
if( used[x].word.length() > wid1 ) wid1 = used[x].word.length();
} else {
if( used[x].word.length() > wid2 ) wid2 = used[x].word.length();
}
}
std::cout << "\n";
std::vector<Word>::iterator w = used.begin();
while( w != used.end() ) {
std::cout << std::right << std::setw( wid1 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") ("
<< ( *w ).cole << ", " << ( *w ).rowe << ")\t";
w++;
if( w == used.end() ) break;
std::cout << std::setw( wid2 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") ("
<< ( *w ).cole << ", " << ( *w ).rowe << ")\n";
w++;
}
std::cout << "\n\n";
}
private:
void addMsg() {
std::string msg = "ROSETTACODE";
int stp = 9, p = rand() % stp;
for( size_t x = 0; x < msg.length(); x++ ) {
puzzle[p % WID][p / HEI].val = msg.at( x );
p += rand() % stp + 4;
}
}
int getEmptySpaces() {
int es = 0;
for( int y = 0; y < HEI; y++ ) {
for( int x = 0; x < WID; x++ ) {
if( !puzzle[x][y].val ) es++;
}
}
return es;
}
bool check( std::string word, int c, int r, int dc, int dr ) {
for( size_t a = 0; a < word.length(); a++ ) {
if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false;
if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false;
c += dc; r += dr;
}
return true;
}
bool setWord( std::string word, int c, int r, int dc, int dr ) {
if( !check( word, c, r, dc, dr ) ) return false;
int sx = c, sy = r;
for( size_t a = 0; a < word.length(); a++ ) {
if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a );
else puzzle[c][r].cntOverlap++;
c += dc; r += dr;
}
used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) );
return true;
}
bool add2Puzzle( std::string word ) {
int x = rand() % WID, y = rand() % HEI,
z = rand() % 8;
for( int d = z; d < z + 8; d++ ) {
switch( d % 8 ) {
case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break;
case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break;
case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break;
case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break;
case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break;
case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break;
case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break;
case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break;
}
}
return false;
}
void clearWord() {
if( used.size() ) {
Word lastW = used.back();
used.pop_back();
for( size_t a = 0; a < lastW.word.length(); a++ ) {
if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) {
puzzle[lastW.cols][lastW.rows].val = 0;
}
if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) {
puzzle[lastW.cols][lastW.rows].cntOverlap--;
}
lastW.cols += lastW.dx; lastW.rows += lastW.dy;
}
}
}
void buildPuzzle() {
addMsg();
int es = 0, cnt = 0;
size_t idx = 0;
do {
for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) {
if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue;
if( add2Puzzle( *w ) ) {
es = getEmptySpaces();
if( !es && used.size() >= MIN_WORD_CNT )
return;
}
}
clearWord();
std::random_shuffle( dictionary.begin(), dictionary.end() );
} while( ++cnt < 100 );
}
std::vector<Word> used;
std::vector<std::string> dictionary;
Cell puzzle[WID][HEI];
};
int main( int argc, char* argv[] ) {
unsigned s = unsigned( time( 0 ) );
srand( s );
words w; w.create( std::string( "unixdict.txt" ) );
w.printOut();
return 0;
}
| package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"regexp"
"strings"
"time"
)
var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}
const (
nRows = 10
nCols = nRows
gridSize = nRows * nCols
minWords = 25
)
var (
re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows))
re2 = regexp.MustCompile("[^A-Z]")
)
type grid struct {
numAttempts int
cells [nRows][nCols]byte
solutions []string
}
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 re1.MatchString(word) {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func createWordSearch(words []string) *grid {
var gr *grid
outer:
for i := 1; i < 100; i++ {
gr = new(grid)
messageLen := gr.placeMessage("Rosetta Code")
target := gridSize - messageLen
cellsFilled := 0
rand.Shuffle(len(words), func(i, j int) {
words[i], words[j] = words[j], words[i]
})
for _, word := range words {
cellsFilled += gr.tryPlaceWord(word)
if cellsFilled == target {
if len(gr.solutions) >= minWords {
gr.numAttempts = i
break outer
} else {
break
}
}
}
}
return gr
}
func (gr *grid) placeMessage(msg string) int {
msg = strings.ToUpper(msg)
msg = re2.ReplaceAllLiteralString(msg, "")
messageLen := len(msg)
if messageLen > 0 && messageLen < gridSize {
gapSize := gridSize / messageLen
for i := 0; i < messageLen; i++ {
pos := i*gapSize + rand.Intn(gapSize)
gr.cells[pos/nCols][pos%nCols] = msg[i]
}
return messageLen
}
return 0
}
func (gr *grid) tryPlaceWord(word string) int {
randDir := rand.Intn(len(dirs))
randPos := rand.Intn(gridSize)
for dir := 0; dir < len(dirs); dir++ {
dir = (dir + randDir) % len(dirs)
for pos := 0; pos < gridSize; pos++ {
pos = (pos + randPos) % gridSize
lettersPlaced := gr.tryLocation(word, dir, pos)
if lettersPlaced > 0 {
return lettersPlaced
}
}
}
return 0
}
func (gr *grid) tryLocation(word string, dir, pos int) int {
r := pos / nCols
c := pos % nCols
le := len(word)
if (dirs[dir][0] == 1 && (le+c) > nCols) ||
(dirs[dir][0] == -1 && (le-1) > c) ||
(dirs[dir][1] == 1 && (le+r) > nRows) ||
(dirs[dir][1] == -1 && (le-1) > r) {
return 0
}
overlaps := 0
rr := r
cc := c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {
return 0
}
cc += dirs[dir][0]
rr += dirs[dir][1]
}
rr = r
cc = c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] == word[i] {
overlaps++
} else {
gr.cells[rr][cc] = word[i]
}
if i < le-1 {
cc += dirs[dir][0]
rr += dirs[dir][1]
}
}
lettersPlaced := le - overlaps
if lettersPlaced > 0 {
sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)
gr.solutions = append(gr.solutions, sol)
}
return lettersPlaced
}
func printResult(gr *grid) {
if gr.numAttempts == 0 {
fmt.Println("No grid to display")
return
}
size := len(gr.solutions)
fmt.Println("Attempts:", gr.numAttempts)
fmt.Println("Number of words:", size)
fmt.Println("\n 0 1 2 3 4 5 6 7 8 9")
for r := 0; r < nRows; r++ {
fmt.Printf("\n%d ", r)
for c := 0; c < nCols; c++ {
fmt.Printf(" %c ", gr.cells[r][c])
}
}
fmt.Println("\n")
for i := 0; i < size-1; i += 2 {
fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1])
}
if size%2 == 1 {
fmt.Println(gr.solutions[size-1])
}
}
func main() {
rand.Seed(time.Now().UnixNano())
unixDictPath := "/usr/share/dict/words"
printResult(createWordSearch(readWords(unixDictPath)))
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <iostream>
class CWidget;
class CFactory
{
friend class CWidget;
private:
unsigned int m_uiCount;
public:
CFactory();
~CFactory();
CWidget* GetWidget();
};
class CWidget
{
private:
CFactory& m_parent;
private:
CWidget();
CWidget(const CWidget&);
CWidget& operator=(const CWidget&);
public:
CWidget(CFactory& parent);
~CWidget();
};
CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}
CWidget* CFactory::GetWidget()
{
return new CWidget(*this);
}
CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
++m_parent.m_uiCount;
std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
CWidget::~CWidget()
{
--m_parent.m_uiCount;
std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
int main()
{
CFactory factory;
CWidget* pWidget1 = factory.GetWidget();
CWidget* pWidget2 = factory.GetWidget();
delete pWidget1;
CWidget* pWidget3 = factory.GetWidget();
delete pWidget3;
delete pWidget2;
}
| package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iostream>
class CWidget;
class CFactory
{
friend class CWidget;
private:
unsigned int m_uiCount;
public:
CFactory();
~CFactory();
CWidget* GetWidget();
};
class CWidget
{
private:
CFactory& m_parent;
private:
CWidget();
CWidget(const CWidget&);
CWidget& operator=(const CWidget&);
public:
CWidget(CFactory& parent);
~CWidget();
};
CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}
CWidget* CFactory::GetWidget()
{
return new CWidget(*this);
}
CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
++m_parent.m_uiCount;
std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
CWidget::~CWidget()
{
--m_parent.m_uiCount;
std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
int main()
{
CFactory factory;
CWidget* pWidget1 = factory.GetWidget();
CWidget* pWidget2 = factory.GetWidget();
delete pWidget1;
CWidget* pWidget3 = factory.GetWidget();
delete pWidget3;
delete pWidget2;
}
| package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
class CWidget;
class CFactory
{
friend class CWidget;
private:
unsigned int m_uiCount;
public:
CFactory();
~CFactory();
CWidget* GetWidget();
};
class CWidget
{
private:
CFactory& m_parent;
private:
CWidget();
CWidget(const CWidget&);
CWidget& operator=(const CWidget&);
public:
CWidget(CFactory& parent);
~CWidget();
};
CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}
CWidget* CFactory::GetWidget()
{
return new CWidget(*this);
}
CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
++m_parent.m_uiCount;
std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
CWidget::~CWidget()
{
--m_parent.m_uiCount;
std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
int main()
{
CFactory factory;
CWidget* pWidget1 = factory.GetWidget();
CWidget* pWidget2 = factory.GetWidget();
delete pWidget1;
CWidget* pWidget3 = factory.GetWidget();
delete pWidget3;
delete pWidget2;
}
| package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <string>
#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <iostream>
class Employee {
public :
Employee( ) { }
Employee ( const std::string &dep , const std::string &namen )
: department( dep ) , name( namen ) {
my_id = count++ ;
}
std::string getName( ) const {
return name ;
}
std::string getDepartment( ) const {
return department ;
}
int getId( ) const {
return my_id ;
}
void setDepartment( const std::string &dep ) {
department.assign( dep ) ;
}
virtual void print( ) {
std::cout << "Name: " << name << '\n' ;
std::cout << "Id: " << my_id << '\n' ;
std::cout << "Department: " << department << '\n' ;
}
virtual ~Employee( ) { }
static int count ;
private :
std::string name ;
std::string department ;
int my_id ;
friend class boost::serialization::access ;
template <class Archive>
void serialize( Archive &ar, const unsigned int version ) {
ar & my_id ;
ar & name ;
ar & department ;
}
} ;
class Worker : public Employee {
public :
Worker( const std::string & dep, const std::string &namen ,
double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }
Worker( ) { }
double getSalary( ) {
return salary ;
}
void setSalary( double pay ) {
if ( pay > 0 )
salary = pay ;
}
virtual void print( ) {
Employee::print( ) ;
std::cout << "wage per hour: " << salary << '\n' ;
}
private :
double salary ;
friend class boost::serialization::access ;
template <class Archive>
void serialize ( Archive & ar, const unsigned int version ) {
ar & boost::serialization::base_object<Employee>( *this ) ;
ar & salary ;
}
} ;
int Employee::count = 0 ;
int main( ) {
std::ofstream storefile( "/home/ulrich/objects.dat" ) ;
const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ;
const Employee emp2( "maintenance" , "John Berry" ) ;
const Employee emp3( "repair" , "Pawel Lichatschow" ) ;
const Employee emp4( "IT" , "Marian Niculescu" ) ;
const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ;
const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ;
boost::archive::text_oarchive oar ( storefile ) ;
oar << emp1 ;
oar << emp2 ;
oar << emp3 ;
oar << emp4 ;
oar << worker1 ;
oar << worker2 ;
storefile.close( ) ;
std::cout << "Reading out the data again\n" ;
Employee e1 , e2 , e3 , e4 ;
Worker w1, w2 ;
std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ;
boost::archive::text_iarchive iar( sourcefile ) ;
iar >> e1 >> e2 >> e3 >> e4 ;
iar >> w1 >> w2 ;
sourcefile.close( ) ;
std::cout << "And here are the data after deserialization!( abridged):\n" ;
e1.print( ) ;
e3.print( ) ;
w2.print( ) ;
return 0 ;
}
| package main
import (
"encoding/gob"
"fmt"
"os"
)
type printable interface {
print()
}
func main() {
animals := []printable{
&Animal{Alive: true},
&Cat{},
&Lab{
Dog: Dog{Animal: Animal{Alive: true}},
Color: "yellow",
},
&Collie{Dog: Dog{
Animal: Animal{Alive: true},
ObedienceTrained: true,
}},
}
fmt.Println("created:")
for _, a := range animals {
a.print()
}
f, err := os.Create("objects.dat")
if err != nil {
fmt.Println(err)
return
}
for _, a := range animals {
gob.Register(a)
}
err = gob.NewEncoder(f).Encode(animals)
if err != nil {
fmt.Println(err)
return
}
f.Close()
f, err = os.Open("objects.dat")
if err != nil {
fmt.Println(err)
return
}
var clones []printable
gob.NewDecoder(f).Decode(&clones)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("\nloaded from objects.dat:")
for _, c := range clones {
c.print()
}
}
type Animal struct {
Alive bool
}
func (a *Animal) print() {
if a.Alive {
fmt.Println(" live animal, unspecified type")
} else {
fmt.Println(" dead animal, unspecified type")
}
}
type Dog struct {
Animal
ObedienceTrained bool
}
func (d *Dog) print() {
switch {
case !d.Alive:
fmt.Println(" dead dog")
case d.ObedienceTrained:
fmt.Println(" trained dog")
default:
fmt.Println(" dog, not trained")
}
}
type Cat struct {
Animal
LitterBoxTrained bool
}
func (c *Cat) print() {
switch {
case !c.Alive:
fmt.Println(" dead cat")
case c.LitterBoxTrained:
fmt.Println(" litter box trained cat")
default:
fmt.Println(" cat, not litter box trained")
}
}
type Lab struct {
Dog
Color string
}
func (l *Lab) print() {
var r string
if l.Color == "" {
r = "lab, color unspecified"
} else {
r = l.Color + " lab"
}
switch {
case !l.Alive:
fmt.Println(" dead", r)
case l.ObedienceTrained:
fmt.Println(" trained", r)
default:
fmt.Printf(" %s, not trained\n", r)
}
}
type Collie struct {
Dog
CatchesFrisbee bool
}
func (c *Collie) print() {
switch {
case !c.Alive:
fmt.Println(" dead collie")
case c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" trained collie, catches frisbee")
case c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" trained collie, but doesn't catch frisbee")
case !c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" collie, not trained, but catches frisbee")
case !c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" collie, not trained, doesn't catch frisbee")
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <string>
#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <iostream>
class Employee {
public :
Employee( ) { }
Employee ( const std::string &dep , const std::string &namen )
: department( dep ) , name( namen ) {
my_id = count++ ;
}
std::string getName( ) const {
return name ;
}
std::string getDepartment( ) const {
return department ;
}
int getId( ) const {
return my_id ;
}
void setDepartment( const std::string &dep ) {
department.assign( dep ) ;
}
virtual void print( ) {
std::cout << "Name: " << name << '\n' ;
std::cout << "Id: " << my_id << '\n' ;
std::cout << "Department: " << department << '\n' ;
}
virtual ~Employee( ) { }
static int count ;
private :
std::string name ;
std::string department ;
int my_id ;
friend class boost::serialization::access ;
template <class Archive>
void serialize( Archive &ar, const unsigned int version ) {
ar & my_id ;
ar & name ;
ar & department ;
}
} ;
class Worker : public Employee {
public :
Worker( const std::string & dep, const std::string &namen ,
double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }
Worker( ) { }
double getSalary( ) {
return salary ;
}
void setSalary( double pay ) {
if ( pay > 0 )
salary = pay ;
}
virtual void print( ) {
Employee::print( ) ;
std::cout << "wage per hour: " << salary << '\n' ;
}
private :
double salary ;
friend class boost::serialization::access ;
template <class Archive>
void serialize ( Archive & ar, const unsigned int version ) {
ar & boost::serialization::base_object<Employee>( *this ) ;
ar & salary ;
}
} ;
int Employee::count = 0 ;
int main( ) {
std::ofstream storefile( "/home/ulrich/objects.dat" ) ;
const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ;
const Employee emp2( "maintenance" , "John Berry" ) ;
const Employee emp3( "repair" , "Pawel Lichatschow" ) ;
const Employee emp4( "IT" , "Marian Niculescu" ) ;
const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ;
const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ;
boost::archive::text_oarchive oar ( storefile ) ;
oar << emp1 ;
oar << emp2 ;
oar << emp3 ;
oar << emp4 ;
oar << worker1 ;
oar << worker2 ;
storefile.close( ) ;
std::cout << "Reading out the data again\n" ;
Employee e1 , e2 , e3 , e4 ;
Worker w1, w2 ;
std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ;
boost::archive::text_iarchive iar( sourcefile ) ;
iar >> e1 >> e2 >> e3 >> e4 ;
iar >> w1 >> w2 ;
sourcefile.close( ) ;
std::cout << "And here are the data after deserialization!( abridged):\n" ;
e1.print( ) ;
e3.print( ) ;
w2.print( ) ;
return 0 ;
}
| package main
import (
"encoding/gob"
"fmt"
"os"
)
type printable interface {
print()
}
func main() {
animals := []printable{
&Animal{Alive: true},
&Cat{},
&Lab{
Dog: Dog{Animal: Animal{Alive: true}},
Color: "yellow",
},
&Collie{Dog: Dog{
Animal: Animal{Alive: true},
ObedienceTrained: true,
}},
}
fmt.Println("created:")
for _, a := range animals {
a.print()
}
f, err := os.Create("objects.dat")
if err != nil {
fmt.Println(err)
return
}
for _, a := range animals {
gob.Register(a)
}
err = gob.NewEncoder(f).Encode(animals)
if err != nil {
fmt.Println(err)
return
}
f.Close()
f, err = os.Open("objects.dat")
if err != nil {
fmt.Println(err)
return
}
var clones []printable
gob.NewDecoder(f).Decode(&clones)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("\nloaded from objects.dat:")
for _, c := range clones {
c.print()
}
}
type Animal struct {
Alive bool
}
func (a *Animal) print() {
if a.Alive {
fmt.Println(" live animal, unspecified type")
} else {
fmt.Println(" dead animal, unspecified type")
}
}
type Dog struct {
Animal
ObedienceTrained bool
}
func (d *Dog) print() {
switch {
case !d.Alive:
fmt.Println(" dead dog")
case d.ObedienceTrained:
fmt.Println(" trained dog")
default:
fmt.Println(" dog, not trained")
}
}
type Cat struct {
Animal
LitterBoxTrained bool
}
func (c *Cat) print() {
switch {
case !c.Alive:
fmt.Println(" dead cat")
case c.LitterBoxTrained:
fmt.Println(" litter box trained cat")
default:
fmt.Println(" cat, not litter box trained")
}
}
type Lab struct {
Dog
Color string
}
func (l *Lab) print() {
var r string
if l.Color == "" {
r = "lab, color unspecified"
} else {
r = l.Color + " lab"
}
switch {
case !l.Alive:
fmt.Println(" dead", r)
case l.ObedienceTrained:
fmt.Println(" trained", r)
default:
fmt.Printf(" %s, not trained\n", r)
}
}
type Collie struct {
Dog
CatchesFrisbee bool
}
func (c *Collie) print() {
switch {
case !c.Alive:
fmt.Println(" dead collie")
case c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" trained collie, catches frisbee")
case c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" trained collie, but doesn't catch frisbee")
case !c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" collie, not trained, but catches frisbee")
case !c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" collie, not trained, doesn't catch frisbee")
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <iostream>
#include <functional>
#include <map>
#include <vector>
struct Node {
int length;
std::map<char, int> edges;
int suffix;
Node(int l) : length(l), suffix(0) {
}
Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {
}
};
constexpr int evenRoot = 0;
constexpr int oddRoot = 1;
std::vector<Node> eertree(const std::string& s) {
std::vector<Node> tree = {
Node(0, {}, oddRoot),
Node(-1, {}, oddRoot)
};
int suffix = oddRoot;
int n, k;
for (size_t i = 0; i < s.length(); ++i) {
char c = s[i];
for (n = suffix; ; n = tree[n].suffix) {
k = tree[n].length;
int b = i - k - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
auto it = tree[n].edges.find(c);
auto end = tree[n].edges.end();
if (it != end) {
suffix = it->second;
continue;
}
suffix = tree.size();
tree.push_back(Node(k + 2));
tree[n].edges[c] = suffix;
if (tree[suffix].length == 1) {
tree[suffix].suffix = 0;
continue;
}
while (true) {
n = tree[n].suffix;
int b = i - tree[n].length - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
tree[suffix].suffix = tree[n].edges[c];
}
return tree;
}
std::vector<std::string> subPalindromes(const std::vector<Node>& tree) {
std::vector<std::string> s;
std::function<void(int, std::string)> children;
children = [&children, &tree, &s](int n, std::string p) {
auto it = tree[n].edges.cbegin();
auto end = tree[n].edges.cend();
for (; it != end; it = std::next(it)) {
auto c = it->first;
auto m = it->second;
std::string pl = c + p + c;
s.push_back(pl);
children(m, pl);
}
};
children(0, "");
auto it = tree[1].edges.cbegin();
auto end = tree[1].edges.cend();
for (; it != end; it = std::next(it)) {
auto c = it->first;
auto n = it->second;
std::string ct(1, c);
s.push_back(ct);
children(n, ct);
}
return s;
}
int main() {
using namespace std;
auto tree = eertree("eertree");
auto pal = subPalindromes(tree);
auto it = pal.cbegin();
auto end = pal.cend();
cout << "[";
if (it != end) {
cout << it->c_str();
it++;
}
while (it != end) {
cout << ", " << it->c_str();
it++;
}
cout << "]" << endl;
return 0;
}
| package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iostream>
#include <functional>
#include <map>
#include <vector>
struct Node {
int length;
std::map<char, int> edges;
int suffix;
Node(int l) : length(l), suffix(0) {
}
Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {
}
};
constexpr int evenRoot = 0;
constexpr int oddRoot = 1;
std::vector<Node> eertree(const std::string& s) {
std::vector<Node> tree = {
Node(0, {}, oddRoot),
Node(-1, {}, oddRoot)
};
int suffix = oddRoot;
int n, k;
for (size_t i = 0; i < s.length(); ++i) {
char c = s[i];
for (n = suffix; ; n = tree[n].suffix) {
k = tree[n].length;
int b = i - k - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
auto it = tree[n].edges.find(c);
auto end = tree[n].edges.end();
if (it != end) {
suffix = it->second;
continue;
}
suffix = tree.size();
tree.push_back(Node(k + 2));
tree[n].edges[c] = suffix;
if (tree[suffix].length == 1) {
tree[suffix].suffix = 0;
continue;
}
while (true) {
n = tree[n].suffix;
int b = i - tree[n].length - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
tree[suffix].suffix = tree[n].edges[c];
}
return tree;
}
std::vector<std::string> subPalindromes(const std::vector<Node>& tree) {
std::vector<std::string> s;
std::function<void(int, std::string)> children;
children = [&children, &tree, &s](int n, std::string p) {
auto it = tree[n].edges.cbegin();
auto end = tree[n].edges.cend();
for (; it != end; it = std::next(it)) {
auto c = it->first;
auto m = it->second;
std::string pl = c + p + c;
s.push_back(pl);
children(m, pl);
}
};
children(0, "");
auto it = tree[1].edges.cbegin();
auto end = tree[1].edges.cend();
for (; it != end; it = std::next(it)) {
auto c = it->first;
auto n = it->second;
std::string ct(1, c);
s.push_back(ct);
children(n, ct);
}
return s;
}
int main() {
using namespace std;
auto tree = eertree("eertree");
auto pal = subPalindromes(tree);
auto it = pal.cbegin();
auto end = pal.cend();
cout << "[";
if (it != end) {
cout << it->c_str();
it++;
}
while (it != end) {
cout << ", " << it->c_str();
it++;
}
cout << "]" << endl;
return 0;
}
| package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <stdio.h>
#include <math.h>
int p(int year) {
return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}
int is_long_year(int year) {
return p(year) == 4 || p(year - 1) == 3;
}
void print_long_years(int from, int to) {
for (int year = from; year <= to; ++year) {
if (is_long_year(year)) {
printf("%d ", year);
}
}
}
int main() {
printf("Long (53 week) years between 1800 and 2100\n\n");
print_long_years(1800, 2100);
printf("\n");
return 0;
}
| package main
import (
"fmt"
"time"
)
func main() {
centuries := []string{"20th", "21st", "22nd"}
starts := []int{1900, 2000, 2100}
for i := 0; i < len(centuries); i++ {
var longYears []int
fmt.Printf("\nLong years in the %s century:\n", centuries[i])
for j := starts[i]; j < starts[i] + 100; j++ {
t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
if _, week := t.ISOWeek(); week == 53 {
longYears = append(longYears, j)
}
}
fmt.Println(longYears)
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <iostream">
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <numeric>
using namespace std;
const uint* binary(uint n, uint length);
uint sum_subset_unrank_bin(const vector<uint>& d, uint r);
vector<uint> factors(uint x);
bool isPrime(uint number);
bool isZum(uint n);
ostream& operator<<(ostream& os, const vector<uint>& zumz) {
for (uint i = 0; i < zumz.size(); i++) {
if (i % 10 == 0)
os << endl;
os << setw(10) << zumz[i] << ' ';
}
return os;
}
int main() {
cout << "First 220 Zumkeller numbers:" << endl;
vector<uint> zumz;
for (uint n = 2; zumz.size() < 220; n++)
if (isZum(n))
zumz.push_back(n);
cout << zumz << endl << endl;
cout << "First 40 odd Zumkeller numbers:" << endl;
vector<uint> zumz2;
for (uint n = 2; zumz2.size() < 40; n++)
if (n % 2 && isZum(n))
zumz2.push_back(n);
cout << zumz2 << endl << endl;
cout << "First 40 odd Zumkeller numbers not ending in 5:" << endl;
vector<uint> zumz3;
for (uint n = 2; zumz3.size() < 40; n++)
if (n % 2 && (n % 10) != 5 && isZum(n))
zumz3.push_back(n);
cout << zumz3 << endl << endl;
return 0;
}
const uint* binary(uint n, uint length) {
uint* bin = new uint[length];
fill(bin, bin + length, 0);
for (uint i = 0; n > 0; i++) {
uint rem = n % 2;
n /= 2;
if (rem)
bin[length - 1 - i] = 1;
}
return bin;
}
uint sum_subset_unrank_bin(const vector<uint>& d, uint r) {
vector<uint> subset;
const uint* bits = binary(r, d.size() - 1);
for (uint i = 0; i < d.size() - 1; i++)
if (bits[i])
subset.push_back(d[i]);
delete[] bits;
return accumulate(subset.begin(), subset.end(), 0u);
}
vector<uint> factors(uint x) {
vector<uint> result;
for (uint i = 1; i * i <= x; i++) {
if (x % i == 0) {
result.push_back(i);
if (x / i != i)
result.push_back(x / i);
}
}
sort(result.begin(), result.end());
return result;
}
bool isPrime(uint number) {
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (uint i = 3; i * i <= number; i += 2)
if (number % i == 0) return false;
return true;
}
bool isZum(uint n) {
if (isPrime(n))
return false;
const auto d = factors(n);
uint s = accumulate(d.begin(), d.end(), 0u);
if (s % 2 || s < 2 * n)
return false;
if (n % 2 || d.size() >= 24)
return true;
if (!(s % 2) && d[d.size() - 1] <= s / 2)
for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++)
if (sum_subset_unrank_bin(d, x) == s / 2)
return true;
return false;
}
| package main
import "fmt"
func getDivisors(n int) []int {
divs := []int{1, n}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs = append(divs, j)
}
}
}
return divs
}
func sum(divs []int) int {
sum := 0
for _, div := range divs {
sum += div
}
return sum
}
func isPartSum(divs []int, sum int) bool {
if sum == 0 {
return true
}
le := len(divs)
if le == 0 {
return false
}
last := divs[le-1]
divs = divs[0 : le-1]
if last > sum {
return isPartSum(divs, sum)
}
return isPartSum(divs, sum) || isPartSum(divs, sum-last)
}
func isZumkeller(n int) bool {
divs := getDivisors(n)
sum := sum(divs)
if sum%2 == 1 {
return false
}
if n%2 == 1 {
abundance := sum - 2*n
return abundance > 0 && abundance%2 == 0
}
return isPartSum(divs, sum/2)
}
func main() {
fmt.Println("The first 220 Zumkeller numbers are:")
for i, count := 2, 0; count < 220; i++ {
if isZumkeller(i) {
fmt.Printf("%3d ", i)
count++
if count%20 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers are:")
for i, count := 3, 0; count < 40; i += 2 {
if isZumkeller(i) {
fmt.Printf("%5d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
for i, count := 3, 0; count < 40; i += 2 {
if (i % 10 != 5) && isZumkeller(i) {
fmt.Printf("%7d ", i)
count++
if count%8 == 0 {
fmt.Println()
}
}
}
fmt.Println()
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Generate an equivalent Go version of this C++ code. | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: ";
auto x0 = 1L, x1 = 1L;
std::cout << x0 << ", " << x1;
for (auto i = 1u; i <= N - 1 - 1; i++) {
auto x2 = b * x1 + x0;
std::cout << ", " << x2;
x0 = x1;
x1 = x2;
}
std::cout << std::endl;
}
template<const ushort P>
void metallic(ulong b) {
using namespace boost::multiprecision;
using bfloat = number<cpp_dec_float<P+1>>;
bfloat x0(1), x1(1);
auto prev = bfloat(1).str(P+1);
for (auto i = 0u;;) {
i++;
bfloat x2(b * x1 + x0);
auto thiz = bfloat(x2 / x1).str(P+1);
if (prev == thiz) {
std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl;
break;
}
prev = thiz;
x0 = x1;
x1 = x2;
}
}
int main() {
for (auto b = 0L; b < 10L; b++) {
lucas<15>(b);
metallic<32>(b);
}
std::cout << "Golden ratio, where b = 1:" << std::endl;
metallic<256>(1);
return 0;
}
| package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: ";
auto x0 = 1L, x1 = 1L;
std::cout << x0 << ", " << x1;
for (auto i = 1u; i <= N - 1 - 1; i++) {
auto x2 = b * x1 + x0;
std::cout << ", " << x2;
x0 = x1;
x1 = x2;
}
std::cout << std::endl;
}
template<const ushort P>
void metallic(ulong b) {
using namespace boost::multiprecision;
using bfloat = number<cpp_dec_float<P+1>>;
bfloat x0(1), x1(1);
auto prev = bfloat(1).str(P+1);
for (auto i = 0u;;) {
i++;
bfloat x2(b * x1 + x0);
auto thiz = bfloat(x2 / x1).str(P+1);
if (prev == thiz) {
std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl;
break;
}
prev = thiz;
x0 = x1;
x1 = x2;
}
}
int main() {
for (auto b = 0L; b < 10L; b++) {
lucas<15>(b);
metallic<32>(b);
}
std::cout << "Golden ratio, where b = 1:" << std::endl;
metallic<256>(1);
return 0;
}
| package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <stdexcept>
int main()
{
throw std::runtime_error("boom");
}
| package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
|
Please provide an equivalent version of this C++ code in Go. | #include <stdexcept>
int main()
{
throw std::runtime_error("boom");
}
| package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
|
Translate this program into Go but keep the logic exactly as in C++. | template<typename T>
struct can_eat
{
private:
template<typename U, void (U::*)()> struct SFINAE {};
template<typename U> static char Test(SFINAE<U, &U::eat>*);
template<typename U> static int Test(...);
public:
static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);
};
struct potato
{ void eat(); };
struct brick
{};
template<typename T>
class FoodBox
{
static_assert(can_eat<T>::value, "Only edible items are allowed in foodbox");
};
int main()
{
FoodBox<potato> lunch;
}
| type eatable interface {
eat()
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | template<typename T>
struct can_eat
{
private:
template<typename U, void (U::*)()> struct SFINAE {};
template<typename U> static char Test(SFINAE<U, &U::eat>*);
template<typename U> static int Test(...);
public:
static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char);
};
struct potato
{ void eat(); };
struct brick
{};
template<typename T>
class FoodBox
{
static_assert(can_eat<T>::value, "Only edible items are allowed in foodbox");
};
int main()
{
FoodBox<potato> lunch;
}
| type eatable interface {
eat()
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <ctime>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
class markov {
public:
void create( std::string& file, unsigned int keyLen, unsigned int words ) {
std::ifstream f( file.c_str(), std::ios_base::in );
fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
f.close();
if( fileBuffer.length() < 1 ) return;
createDictionary( keyLen );
createText( words - keyLen );
}
private:
void createText( int w ) {
std::string key, first, second;
size_t next;
std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();
std::advance( it, rand() % dictionary.size() );
key = ( *it ).first;
std::cout << key;
while( true ) {
std::vector<std::string> d = dictionary[key];
if( d.size() < 1 ) break;
second = d[rand() % d.size()];
if( second.length() < 1 ) break;
std::cout << " " << second;
if( --w < 0 ) break;
next = key.find_first_of( 32, 0 );
first = key.substr( next + 1 );
key = first + " " + second;
}
std::cout << "\n";
}
void createDictionary( unsigned int kl ) {
std::string w1, key;
size_t wc = 0, pos, next;
next = fileBuffer.find_first_not_of( 32, 0 );
if( next == std::string::npos ) return;
while( wc < kl ) {
pos = fileBuffer.find_first_of( ' ', next );
w1 = fileBuffer.substr( next, pos - next );
key += w1 + " ";
next = fileBuffer.find_first_not_of( 32, pos + 1 );
if( next == std::string::npos ) return;
wc++;
}
key = key.substr( 0, key.size() - 1 );
while( true ) {
next = fileBuffer.find_first_not_of( 32, pos + 1 );
if( next == std::string::npos ) return;
pos = fileBuffer.find_first_of( 32, next );
w1 = fileBuffer.substr( next, pos - next );
if( w1.size() < 1 ) break;
if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() )
dictionary[key].push_back( w1 );
key = key.substr( key.find_first_of( 32 ) + 1 ) + " " + w1;
}
}
std::string fileBuffer;
std::map<std::string, std::vector<std::string> > dictionary;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
markov m;
m.create( std::string( "alice_oz.txt" ), 3, 200 );
return 0;
}
| package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"math/rand"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
)
func main() {
log.SetFlags(0)
log.SetPrefix("markov: ")
input := flag.String("in", "alice_oz.txt", "input file")
n := flag.Int("n", 2, "number of words to use as prefix")
runs := flag.Int("runs", 1, "number of runs to generate")
wordsPerRun := flag.Int("words", 300, "number of words per run")
startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix")
stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)")
flag.Parse()
rand.Seed(time.Now().UnixNano())
m, err := NewMarkovFromFile(*input, *n)
if err != nil {
log.Fatal(err)
}
for i := 0; i < *runs; i++ {
err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}
}
type Markov struct {
n int
capitalized int
suffix map[string][]string
}
func NewMarkovFromFile(filename string, n int) (*Markov, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return NewMarkov(f, n)
}
func NewMarkov(r io.Reader, n int) (*Markov, error) {
m := &Markov{
n: n,
suffix: make(map[string][]string),
}
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
window := make([]string, 0, n)
for sc.Scan() {
word := sc.Text()
if len(window) > 0 {
prefix := strings.Join(window, " ")
m.suffix[prefix] = append(m.suffix[prefix], word)
if isCapitalized(prefix) {
m.capitalized++
}
}
window = appendMax(n, window, word)
}
if err := sc.Err(); err != nil {
return nil, err
}
return m, nil
}
func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {
bw := bufio.NewWriter(w)
var i int
if startCapital {
i = rand.Intn(m.capitalized)
} else {
i = rand.Intn(len(m.suffix))
}
var prefix string
for prefix = range m.suffix {
if startCapital && !isCapitalized(prefix) {
continue
}
if i == 0 {
break
}
i--
}
bw.WriteString(prefix)
prefixWords := strings.Fields(prefix)
n -= len(prefixWords)
for {
suffixChoices := m.suffix[prefix]
if len(suffixChoices) == 0 {
break
}
i = rand.Intn(len(suffixChoices))
suffix := suffixChoices[i]
bw.WriteByte(' ')
if _, err := bw.WriteString(suffix); err != nil {
break
}
n--
if n < 0 && (!stopSentence || isSentenceEnd(suffix)) {
break
}
prefixWords = appendMax(m.n, prefixWords, suffix)
prefix = strings.Join(prefixWords, " ")
}
return bw.Flush()
}
func isCapitalized(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return unicode.IsUpper(r)
}
func isSentenceEnd(s string) bool {
r, _ := utf8.DecodeLastRuneInString(s)
return r == '.' || r == '?' || r == '!'
}
func appendMax(max int, slice []string, value string) []string {
if len(slice)+1 > max {
n := copy(slice, slice[1:])
slice = slice[:n]
}
return append(slice, value)
}
|
Write the same code in Go as shown below in C++. | #include <iostream>
#include <vector>
#include <string>
#include <list>
#include <limits>
#include <set>
#include <utility>
#include <algorithm>
#include <iterator>
typedef int vertex_t;
typedef double weight_t;
const weight_t max_weight = std::numeric_limits<double>::infinity();
struct neighbor {
vertex_t target;
weight_t weight;
neighbor(vertex_t arg_target, weight_t arg_weight)
: target(arg_target), weight(arg_weight) { }
};
typedef std::vector<std::vector<neighbor> > adjacency_list_t;
void DijkstraComputePaths(vertex_t source,
const adjacency_list_t &adjacency_list,
std::vector<weight_t> &min_distance,
std::vector<vertex_t> &previous)
{
int n = adjacency_list.size();
min_distance.clear();
min_distance.resize(n, max_weight);
min_distance[source] = 0;
previous.clear();
previous.resize(n, -1);
std::set<std::pair<weight_t, vertex_t> > vertex_queue;
vertex_queue.insert(std::make_pair(min_distance[source], source));
while (!vertex_queue.empty())
{
weight_t dist = vertex_queue.begin()->first;
vertex_t u = vertex_queue.begin()->second;
vertex_queue.erase(vertex_queue.begin());
const std::vector<neighbor> &neighbors = adjacency_list[u];
for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();
neighbor_iter != neighbors.end();
neighbor_iter++)
{
vertex_t v = neighbor_iter->target;
weight_t weight = neighbor_iter->weight;
weight_t distance_through_u = dist + weight;
if (distance_through_u < min_distance[v]) {
vertex_queue.erase(std::make_pair(min_distance[v], v));
min_distance[v] = distance_through_u;
previous[v] = u;
vertex_queue.insert(std::make_pair(min_distance[v], v));
}
}
}
}
std::list<vertex_t> DijkstraGetShortestPathTo(
vertex_t vertex, const std::vector<vertex_t> &previous)
{
std::list<vertex_t> path;
for ( ; vertex != -1; vertex = previous[vertex])
path.push_front(vertex);
return path;
}
int main()
{
adjacency_list_t adjacency_list(6);
adjacency_list[0].push_back(neighbor(1, 7));
adjacency_list[0].push_back(neighbor(2, 9));
adjacency_list[0].push_back(neighbor(5, 14));
adjacency_list[1].push_back(neighbor(0, 7));
adjacency_list[1].push_back(neighbor(2, 10));
adjacency_list[1].push_back(neighbor(3, 15));
adjacency_list[2].push_back(neighbor(0, 9));
adjacency_list[2].push_back(neighbor(1, 10));
adjacency_list[2].push_back(neighbor(3, 11));
adjacency_list[2].push_back(neighbor(5, 2));
adjacency_list[3].push_back(neighbor(1, 15));
adjacency_list[3].push_back(neighbor(2, 11));
adjacency_list[3].push_back(neighbor(4, 6));
adjacency_list[4].push_back(neighbor(3, 6));
adjacency_list[4].push_back(neighbor(5, 9));
adjacency_list[5].push_back(neighbor(0, 14));
adjacency_list[5].push_back(neighbor(2, 2));
adjacency_list[5].push_back(neighbor(4, 9));
std::vector<weight_t> min_distance;
std::vector<vertex_t> previous;
DijkstraComputePaths(0, adjacency_list, min_distance, previous);
std::cout << "Distance from 0 to 4: " << min_distance[4] << std::endl;
std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);
std::cout << "Path : ";
std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, " "));
std::cout << std::endl;
return 0;
}
| package main
import (
"container/heap"
"fmt"
)
type PriorityQueue struct {
items []Vertex
m map[Vertex]int
pr map[Vertex]int
}
func (pq *PriorityQueue) Len() int { return len(pq.items) }
func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }
func (pq *PriorityQueue) Swap(i, j int) {
pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
pq.m[pq.items[i]] = i
pq.m[pq.items[j]] = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(pq.items)
item := x.(Vertex)
pq.m[item] = n
pq.items = append(pq.items, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := pq.items
n := len(old)
item := old[n-1]
pq.m[item] = -1
pq.items = old[0 : n-1]
return item
}
func (pq *PriorityQueue) update(item Vertex, priority int) {
pq.pr[item] = priority
heap.Fix(pq, pq.m[item])
}
func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {
heap.Push(pq, item)
pq.update(item, priority)
}
const (
Infinity = int(^uint(0) >> 1)
Uninitialized = -1
)
func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {
vs := g.Vertices()
dist = make(map[Vertex]int, len(vs))
prev = make(map[Vertex]Vertex, len(vs))
sid := source
dist[sid] = 0
q := &PriorityQueue{
items: make([]Vertex, 0, len(vs)),
m: make(map[Vertex]int, len(vs)),
pr: make(map[Vertex]int, len(vs)),
}
for _, v := range vs {
if v != sid {
dist[v] = Infinity
}
prev[v] = Uninitialized
q.addWithPriority(v, dist[v])
}
for len(q.items) != 0 {
u := heap.Pop(q).(Vertex)
for _, v := range g.Neighbors(u) {
alt := dist[u] + g.Weight(u, v)
if alt < dist[v] {
dist[v] = alt
prev[v] = u
q.update(v, alt)
}
}
}
return dist, prev
}
type Graph interface {
Vertices() []Vertex
Neighbors(v Vertex) []Vertex
Weight(u, v Vertex) int
}
type Vertex int
type sg struct {
ids map[string]Vertex
names map[Vertex]string
edges map[Vertex]map[Vertex]int
}
func newsg(ids map[string]Vertex) sg {
g := sg{ids: ids}
g.names = make(map[Vertex]string, len(ids))
for k, v := range ids {
g.names[v] = k
}
g.edges = make(map[Vertex]map[Vertex]int)
return g
}
func (g sg) edge(u, v string, w int) {
if _, ok := g.edges[g.ids[u]]; !ok {
g.edges[g.ids[u]] = make(map[Vertex]int)
}
g.edges[g.ids[u]][g.ids[v]] = w
}
func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {
s = g.names[v]
for prev[v] >= 0 {
v = prev[v]
s = g.names[v] + s
}
return s
}
func (g sg) Vertices() []Vertex {
vs := make([]Vertex, 0, len(g.ids))
for _, v := range g.ids {
vs = append(vs, v)
}
return vs
}
func (g sg) Neighbors(u Vertex) []Vertex {
vs := make([]Vertex, 0, len(g.edges[u]))
for v := range g.edges[u] {
vs = append(vs, v)
}
return vs
}
func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }
func main() {
g := newsg(map[string]Vertex{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
})
g.edge("a", "b", 7)
g.edge("a", "c", 9)
g.edge("a", "f", 14)
g.edge("b", "c", 10)
g.edge("b", "d", 15)
g.edge("c", "d", 11)
g.edge("c", "f", 2)
g.edge("d", "e", 6)
g.edge("e", "f", 9)
dist, prev := Dijkstra(g, g.ids["a"])
fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev))
fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev))
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <algorithm>
#include <iostream>
#include <random>
#include <vector>
double uniform01() {
static std::default_random_engine generator;
static std::uniform_real_distribution<double> distribution(0.0, 1.0);
return distribution(generator);
}
int bitCount(int i) {
i -= ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i + (i >> 4)) & 0x0F0F0F0F;
i += (i >> 8);
i += (i >> 16);
return i & 0x0000003F;
}
double reorderingSign(int i, int j) {
int k = i >> 1;
int sum = 0;
while (k != 0) {
sum += bitCount(k & j);
k = k >> 1;
}
return ((sum & 1) == 0) ? 1.0 : -1.0;
}
struct MyVector {
public:
MyVector(const std::vector<double> &da) : dims(da) {
}
double &operator[](size_t i) {
return dims[i];
}
const double &operator[](size_t i) const {
return dims[i];
}
MyVector operator+(const MyVector &rhs) const {
std::vector<double> temp(dims);
for (size_t i = 0; i < rhs.dims.size(); ++i) {
temp[i] += rhs[i];
}
return MyVector(temp);
}
MyVector operator*(const MyVector &rhs) const {
std::vector<double> temp(dims.size(), 0.0);
for (size_t i = 0; i < dims.size(); i++) {
if (dims[i] != 0.0) {
for (size_t j = 0; j < dims.size(); j++) {
if (rhs[j] != 0.0) {
auto s = reorderingSign(i, j) * dims[i] * rhs[j];
auto k = i ^ j;
temp[k] += s;
}
}
}
}
return MyVector(temp);
}
MyVector operator*(double scale) const {
std::vector<double> temp(dims);
std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; });
return MyVector(temp);
}
MyVector operator-() const {
return *this * -1.0;
}
MyVector dot(const MyVector &rhs) const {
return (*this * rhs + rhs * *this) * 0.5;
}
friend std::ostream &operator<<(std::ostream &, const MyVector &);
private:
std::vector<double> dims;
};
std::ostream &operator<<(std::ostream &os, const MyVector &v) {
auto it = v.dims.cbegin();
auto end = v.dims.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
MyVector e(int n) {
if (n > 4) {
throw new std::runtime_error("n must be less than 5");
}
auto result = MyVector(std::vector<double>(32, 0.0));
result[1 << n] = 1.0;
return result;
}
MyVector randomVector() {
auto result = MyVector(std::vector<double>(32, 0.0));
for (int i = 0; i < 5; i++) {
result = result + MyVector(std::vector<double>(1, uniform01())) * e(i);
}
return result;
}
MyVector randomMultiVector() {
auto result = MyVector(std::vector<double>(32, 0.0));
for (int i = 0; i < 32; i++) {
result[i] = uniform01();
}
return result;
}
int main() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i < j) {
if (e(i).dot(e(j))[0] != 0.0) {
std::cout << "Unexpected non-null scalar product.";
return 1;
} else if (i == j) {
if (e(i).dot(e(j))[0] == 0.0) {
std::cout << "Unexpected null scalar product.";
}
}
}
}
}
auto a = randomMultiVector();
auto b = randomMultiVector();
auto c = randomMultiVector();
auto x = randomVector();
std::cout << ((a * b) * c) << '\n';
std::cout << (a * (b * c)) << "\n\n";
std::cout << (a * (b + c)) << '\n';
std::cout << (a * b + a * c) << "\n\n";
std::cout << ((a + b) * c) << '\n';
std::cout << (a * c + b * c) << "\n\n";
std::cout << (x * x) << '\n';
return 0;
}
| package main
import (
"fmt"
"math/rand"
"time"
)
type vector []float64
func e(n uint) vector {
if n > 4 {
panic("n must be less than 5")
}
result := make(vector, 32)
result[1<<n] = 1.0
return result
}
func cdot(a, b vector) vector {
return mul(vector{0.5}, add(mul(a, b), mul(b, a)))
}
func neg(x vector) vector {
return mul(vector{-1}, x)
}
func bitCount(i int) int {
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
i = (i + (i >> 4)) & 0x0F0F0F0F
i = i + (i >> 8)
i = i + (i >> 16)
return i & 0x0000003F
}
func reorderingSign(i, j int) float64 {
i >>= 1
sum := 0
for i != 0 {
sum += bitCount(i & j)
i >>= 1
}
cond := (sum & 1) == 0
if cond {
return 1.0
}
return -1.0
}
func add(a, b vector) vector {
result := make(vector, 32)
copy(result, a)
for i, _ := range b {
result[i] += b[i]
}
return result
}
func mul(a, b vector) vector {
result := make(vector, 32)
for i, _ := range a {
if a[i] != 0 {
for j, _ := range b {
if b[j] != 0 {
s := reorderingSign(i, j) * a[i] * b[j]
k := i ^ j
result[k] += s
}
}
}
}
return result
}
func randomVector() vector {
result := make(vector, 32)
for i := uint(0); i < 5; i++ {
result = add(result, mul(vector{rand.Float64()}, e(i)))
}
return result
}
func randomMultiVector() vector {
result := make(vector, 32)
for i := 0; i < 32; i++ {
result[i] = rand.Float64()
}
return result
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 5; i++ {
for j := uint(0); j < 5; j++ {
if i < j {
if cdot(e(i), e(j))[0] != 0 {
fmt.Println("Unexpected non-null scalar product.")
return
}
} else if i == j {
if cdot(e(i), e(j))[0] == 0 {
fmt.Println("Unexpected null scalar product.")
}
}
}
}
a := randomMultiVector()
b := randomMultiVector()
c := randomMultiVector()
x := randomVector()
fmt.Println(mul(mul(a, b), c))
fmt.Println(mul(a, mul(b, c)))
fmt.Println(mul(a, add(b, c)))
fmt.Println(add(mul(a, b), mul(a, c)))
fmt.Println(mul(add(a, b), c))
fmt.Println(add(mul(a, c), mul(b, c)))
fmt.Println(mul(x, x))
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <functional>
#include <iostream>
#include <vector>
struct Node {
std::string sub = "";
std::vector<int> ch;
Node() {
}
Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {
ch.insert(ch.end(), children);
}
};
struct SuffixTree {
std::vector<Node> nodes;
SuffixTree(const std::string& str) {
nodes.push_back(Node{});
for (size_t i = 0; i < str.length(); i++) {
addSuffix(str.substr(i));
}
}
void visualize() {
if (nodes.size() == 0) {
std::cout << "<empty>\n";
return;
}
std::function<void(int, const std::string&)> f;
f = [&](int n, const std::string & pre) {
auto children = nodes[n].ch;
if (children.size() == 0) {
std::cout << "- " << nodes[n].sub << '\n';
return;
}
std::cout << "+ " << nodes[n].sub << '\n';
auto it = std::begin(children);
if (it != std::end(children)) do {
if (std::next(it) == std::end(children)) break;
std::cout << pre << "+-";
f(*it, pre + "| ");
it = std::next(it);
} while (true);
std::cout << pre << "+-";
f(children[children.size() - 1], pre + " ");
};
f(0, "");
}
private:
void addSuffix(const std::string & suf) {
int n = 0;
size_t i = 0;
while (i < suf.length()) {
char b = suf[i];
int x2 = 0;
int n2;
while (true) {
auto children = nodes[n].ch;
if (x2 == children.size()) {
n2 = nodes.size();
nodes.push_back(Node(suf.substr(i), {}));
nodes[n].ch.push_back(n2);
return;
}
n2 = children[x2];
if (nodes[n2].sub[0] == b) {
break;
}
x2++;
}
auto sub2 = nodes[n2].sub;
size_t j = 0;
while (j < sub2.size()) {
if (suf[i + j] != sub2[j]) {
auto n3 = n2;
n2 = nodes.size();
nodes.push_back(Node(sub2.substr(0, j), { n3 }));
nodes[n3].sub = sub2.substr(j);
nodes[n].ch[x2] = n2;
break;
}
j++;
}
i += j;
n = n2;
}
}
};
int main() {
SuffixTree("banana$").visualize();
}
| package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <functional>
#include <iostream>
#include <vector>
struct Node {
std::string sub = "";
std::vector<int> ch;
Node() {
}
Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {
ch.insert(ch.end(), children);
}
};
struct SuffixTree {
std::vector<Node> nodes;
SuffixTree(const std::string& str) {
nodes.push_back(Node{});
for (size_t i = 0; i < str.length(); i++) {
addSuffix(str.substr(i));
}
}
void visualize() {
if (nodes.size() == 0) {
std::cout << "<empty>\n";
return;
}
std::function<void(int, const std::string&)> f;
f = [&](int n, const std::string & pre) {
auto children = nodes[n].ch;
if (children.size() == 0) {
std::cout << "- " << nodes[n].sub << '\n';
return;
}
std::cout << "+ " << nodes[n].sub << '\n';
auto it = std::begin(children);
if (it != std::end(children)) do {
if (std::next(it) == std::end(children)) break;
std::cout << pre << "+-";
f(*it, pre + "| ");
it = std::next(it);
} while (true);
std::cout << pre << "+-";
f(children[children.size() - 1], pre + " ");
};
f(0, "");
}
private:
void addSuffix(const std::string & suf) {
int n = 0;
size_t i = 0;
while (i < suf.length()) {
char b = suf[i];
int x2 = 0;
int n2;
while (true) {
auto children = nodes[n].ch;
if (x2 == children.size()) {
n2 = nodes.size();
nodes.push_back(Node(suf.substr(i), {}));
nodes[n].ch.push_back(n2);
return;
}
n2 = children[x2];
if (nodes[n2].sub[0] == b) {
break;
}
x2++;
}
auto sub2 = nodes[n2].sub;
size_t j = 0;
while (j < sub2.size()) {
if (suf[i + j] != sub2[j]) {
auto n3 = n2;
n2 = nodes.size();
nodes.push_back(Node(sub2.substr(0, j), { n3 }));
nodes[n3].sub = sub2.substr(j);
nodes[n].ch[x2] = n2;
break;
}
j++;
}
i += j;
n = n2;
}
}
};
int main() {
SuffixTree("banana$").visualize();
}
| package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> dict {
{"One", 1},
{"Two", 2},
{"Three", 7}
};
dict["Three"] = 3;
std::cout << "One: " << dict["One"] << std::endl;
std::cout << "Key/Value pairs: " << std::endl;
for(auto& kv: dict) {
std::cout << " " << kv.first << ": " << kv.second << std::endl;
}
return 0;
}
| myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <stdexcept>
class tiny_int
{
public:
tiny_int(int i):
value(i)
{
if (value < 1)
throw std::out_of_range("tiny_int: value smaller than 1");
if (value > 10)
throw std::out_of_range("tiny_int: value larger than 10");
}
operator int() const
{
return value;
}
tiny_int& operator+=(int i)
{
*this = value + i;
return *this;
}
tiny_int& operator-=(int i)
{
*this = value - i;
return *this;
}
tiny_int& operator*=(int i)
{
*this = value * i;
return *this;
}
tiny_int& operator/=(int i)
{
*this = value / i;
return *this;
}
tiny_int& operator<<=(int i)
{
*this = value << i;
return *this;
}
tiny_int& operator>>=(int i)
{
*this = value >> i;
return *this;
}
tiny_int& operator&=(int i)
{
*this = value & i;
return *this;
}
tiny_int& operator|=(int i)
{
*this = value | i;
return *this;
}
private:
unsigned char value;
};
| package main
import "fmt"
type TinyInt int
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1 % t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <algorithm>
#include <iostream>
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left;
delete right;
}
};
template <class T>
class AVLtree {
public:
AVLtree(void);
~AVLtree(void);
bool insert(T key);
void deleteKey(const T key);
void printBalance();
private:
AVLnode<T> *root;
AVLnode<T>* rotateLeft ( AVLnode<T> *a );
AVLnode<T>* rotateRight ( AVLnode<T> *a );
AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );
AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );
void rebalance ( AVLnode<T> *n );
int height ( AVLnode<T> *n );
void setBalance ( AVLnode<T> *n );
void printBalance ( AVLnode<T> *n );
};
template <class T>
void AVLtree<T>::rebalance(AVLnode<T> *n) {
setBalance(n);
if (n->balance == -2) {
if (height(n->left->left) >= height(n->left->right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
}
else if (n->balance == 2) {
if (height(n->right->right) >= height(n->right->left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n->parent != NULL) {
rebalance(n->parent);
}
else {
root = n;
}
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {
AVLnode<T> *b = a->right;
b->parent = a->parent;
a->right = b->left;
if (a->right != NULL)
a->right->parent = a;
b->left = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {
AVLnode<T> *b = a->left;
b->parent = a->parent;
a->left = b->right;
if (a->left != NULL)
a->left->parent = a;
b->right = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {
n->left = rotateLeft(n->left);
return rotateRight(n);
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {
n->right = rotateRight(n->right);
return rotateLeft(n);
}
template <class T>
int AVLtree<T>::height(AVLnode<T> *n) {
if (n == NULL)
return -1;
return 1 + std::max(height(n->left), height(n->right));
}
template <class T>
void AVLtree<T>::setBalance(AVLnode<T> *n) {
n->balance = height(n->right) - height(n->left);
}
template <class T>
void AVLtree<T>::printBalance(AVLnode<T> *n) {
if (n != NULL) {
printBalance(n->left);
std::cout << n->balance << " ";
printBalance(n->right);
}
}
template <class T>
AVLtree<T>::AVLtree(void) : root(NULL) {}
template <class T>
AVLtree<T>::~AVLtree(void) {
delete root;
}
template <class T>
bool AVLtree<T>::insert(T key) {
if (root == NULL) {
root = new AVLnode<T>(key, NULL);
}
else {
AVLnode<T>
*n = root,
*parent;
while (true) {
if (n->key == key)
return false;
parent = n;
bool goLeft = n->key > key;
n = goLeft ? n->left : n->right;
if (n == NULL) {
if (goLeft) {
parent->left = new AVLnode<T>(key, parent);
}
else {
parent->right = new AVLnode<T>(key, parent);
}
rebalance(parent);
break;
}
}
}
return true;
}
template <class T>
void AVLtree<T>::deleteKey(const T delKey) {
if (root == NULL)
return;
AVLnode<T>
*n = root,
*parent = root,
*delNode = NULL,
*child = root;
while (child != NULL) {
parent = n;
n = child;
child = delKey >= n->key ? n->right : n->left;
if (delKey == n->key)
delNode = n;
}
if (delNode != NULL) {
delNode->key = n->key;
child = n->left != NULL ? n->left : n->right;
if (root->key == delKey) {
root = child;
}
else {
if (parent->left == n) {
parent->left = child;
}
else {
parent->right = child;
}
rebalance(parent);
}
}
}
template <class T>
void AVLtree<T>::printBalance() {
printBalance(root);
std::cout << std::endl;
}
int main(void)
{
AVLtree<int> t;
std::cout << "Inserting integer values 1 to 10" << std::endl;
for (int i = 1; i <= 10; ++i)
t.insert(i);
std::cout << "Printing balance: ";
t.printBalance();
}
| package avl
type Key interface {
Less(Key) bool
Eq(Key) bool
}
type Node struct {
Data Key
Balance int
Link [2]*Node
}
func opp(dir int) int {
return 1 - dir
}
func single(root *Node, dir int) *Node {
save := root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func double(root *Node, dir int) *Node {
save := root.Link[opp(dir)].Link[dir]
root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]
save.Link[opp(dir)] = root.Link[opp(dir)]
root.Link[opp(dir)] = save
save = root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func adjustBalance(root *Node, dir, bal int) {
n := root.Link[dir]
nn := n.Link[opp(dir)]
switch nn.Balance {
case 0:
root.Balance = 0
n.Balance = 0
case bal:
root.Balance = -bal
n.Balance = 0
default:
root.Balance = 0
n.Balance = bal
}
nn.Balance = 0
}
func insertBalance(root *Node, dir int) *Node {
n := root.Link[dir]
bal := 2*dir - 1
if n.Balance == bal {
root.Balance = 0
n.Balance = 0
return single(root, opp(dir))
}
adjustBalance(root, dir, bal)
return double(root, opp(dir))
}
func insertR(root *Node, data Key) (*Node, bool) {
if root == nil {
return &Node{Data: data}, false
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = insertR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 2*dir - 1
switch root.Balance {
case 0:
return root, true
case 1, -1:
return root, false
}
return insertBalance(root, dir), true
}
func Insert(tree **Node, data Key) {
*tree, _ = insertR(*tree, data)
}
func removeBalance(root *Node, dir int) (*Node, bool) {
n := root.Link[opp(dir)]
bal := 2*dir - 1
switch n.Balance {
case -bal:
root.Balance = 0
n.Balance = 0
return single(root, dir), false
case bal:
adjustBalance(root, opp(dir), -bal)
return double(root, dir), false
}
root.Balance = -bal
n.Balance = bal
return single(root, dir), true
}
func removeR(root *Node, data Key) (*Node, bool) {
if root == nil {
return nil, false
}
if root.Data.Eq(data) {
switch {
case root.Link[0] == nil:
return root.Link[1], false
case root.Link[1] == nil:
return root.Link[0], false
}
heir := root.Link[0]
for heir.Link[1] != nil {
heir = heir.Link[1]
}
root.Data = heir.Data
data = heir.Data
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = removeR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 1 - 2*dir
switch root.Balance {
case 1, -1:
return root, true
case 0:
return root, false
}
return removeBalance(root, dir)
}
func Remove(tree **Node, data Key) {
*tree, _ = removeR(*tree, data)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <algorithm>
#include <iostream>
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left;
delete right;
}
};
template <class T>
class AVLtree {
public:
AVLtree(void);
~AVLtree(void);
bool insert(T key);
void deleteKey(const T key);
void printBalance();
private:
AVLnode<T> *root;
AVLnode<T>* rotateLeft ( AVLnode<T> *a );
AVLnode<T>* rotateRight ( AVLnode<T> *a );
AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );
AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );
void rebalance ( AVLnode<T> *n );
int height ( AVLnode<T> *n );
void setBalance ( AVLnode<T> *n );
void printBalance ( AVLnode<T> *n );
};
template <class T>
void AVLtree<T>::rebalance(AVLnode<T> *n) {
setBalance(n);
if (n->balance == -2) {
if (height(n->left->left) >= height(n->left->right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
}
else if (n->balance == 2) {
if (height(n->right->right) >= height(n->right->left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n->parent != NULL) {
rebalance(n->parent);
}
else {
root = n;
}
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateLeft(AVLnode<T> *a) {
AVLnode<T> *b = a->right;
b->parent = a->parent;
a->right = b->left;
if (a->right != NULL)
a->right->parent = a;
b->left = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateRight(AVLnode<T> *a) {
AVLnode<T> *b = a->left;
b->parent = a->parent;
a->left = b->right;
if (a->left != NULL)
a->left->parent = a;
b->right = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateLeftThenRight(AVLnode<T> *n) {
n->left = rotateLeft(n->left);
return rotateRight(n);
}
template <class T>
AVLnode<T>* AVLtree<T>::rotateRightThenLeft(AVLnode<T> *n) {
n->right = rotateRight(n->right);
return rotateLeft(n);
}
template <class T>
int AVLtree<T>::height(AVLnode<T> *n) {
if (n == NULL)
return -1;
return 1 + std::max(height(n->left), height(n->right));
}
template <class T>
void AVLtree<T>::setBalance(AVLnode<T> *n) {
n->balance = height(n->right) - height(n->left);
}
template <class T>
void AVLtree<T>::printBalance(AVLnode<T> *n) {
if (n != NULL) {
printBalance(n->left);
std::cout << n->balance << " ";
printBalance(n->right);
}
}
template <class T>
AVLtree<T>::AVLtree(void) : root(NULL) {}
template <class T>
AVLtree<T>::~AVLtree(void) {
delete root;
}
template <class T>
bool AVLtree<T>::insert(T key) {
if (root == NULL) {
root = new AVLnode<T>(key, NULL);
}
else {
AVLnode<T>
*n = root,
*parent;
while (true) {
if (n->key == key)
return false;
parent = n;
bool goLeft = n->key > key;
n = goLeft ? n->left : n->right;
if (n == NULL) {
if (goLeft) {
parent->left = new AVLnode<T>(key, parent);
}
else {
parent->right = new AVLnode<T>(key, parent);
}
rebalance(parent);
break;
}
}
}
return true;
}
template <class T>
void AVLtree<T>::deleteKey(const T delKey) {
if (root == NULL)
return;
AVLnode<T>
*n = root,
*parent = root,
*delNode = NULL,
*child = root;
while (child != NULL) {
parent = n;
n = child;
child = delKey >= n->key ? n->right : n->left;
if (delKey == n->key)
delNode = n;
}
if (delNode != NULL) {
delNode->key = n->key;
child = n->left != NULL ? n->left : n->right;
if (root->key == delKey) {
root = child;
}
else {
if (parent->left == n) {
parent->left = child;
}
else {
parent->right = child;
}
rebalance(parent);
}
}
}
template <class T>
void AVLtree<T>::printBalance() {
printBalance(root);
std::cout << std::endl;
}
int main(void)
{
AVLtree<int> t;
std::cout << "Inserting integer values 1 to 10" << std::endl;
for (int i = 1; i <= 10; ++i)
t.insert(i);
std::cout << "Printing balance: ";
t.printBalance();
}
| package avl
type Key interface {
Less(Key) bool
Eq(Key) bool
}
type Node struct {
Data Key
Balance int
Link [2]*Node
}
func opp(dir int) int {
return 1 - dir
}
func single(root *Node, dir int) *Node {
save := root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func double(root *Node, dir int) *Node {
save := root.Link[opp(dir)].Link[dir]
root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]
save.Link[opp(dir)] = root.Link[opp(dir)]
root.Link[opp(dir)] = save
save = root.Link[opp(dir)]
root.Link[opp(dir)] = save.Link[dir]
save.Link[dir] = root
return save
}
func adjustBalance(root *Node, dir, bal int) {
n := root.Link[dir]
nn := n.Link[opp(dir)]
switch nn.Balance {
case 0:
root.Balance = 0
n.Balance = 0
case bal:
root.Balance = -bal
n.Balance = 0
default:
root.Balance = 0
n.Balance = bal
}
nn.Balance = 0
}
func insertBalance(root *Node, dir int) *Node {
n := root.Link[dir]
bal := 2*dir - 1
if n.Balance == bal {
root.Balance = 0
n.Balance = 0
return single(root, opp(dir))
}
adjustBalance(root, dir, bal)
return double(root, opp(dir))
}
func insertR(root *Node, data Key) (*Node, bool) {
if root == nil {
return &Node{Data: data}, false
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = insertR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 2*dir - 1
switch root.Balance {
case 0:
return root, true
case 1, -1:
return root, false
}
return insertBalance(root, dir), true
}
func Insert(tree **Node, data Key) {
*tree, _ = insertR(*tree, data)
}
func removeBalance(root *Node, dir int) (*Node, bool) {
n := root.Link[opp(dir)]
bal := 2*dir - 1
switch n.Balance {
case -bal:
root.Balance = 0
n.Balance = 0
return single(root, dir), false
case bal:
adjustBalance(root, opp(dir), -bal)
return double(root, dir), false
}
root.Balance = -bal
n.Balance = bal
return single(root, dir), true
}
func removeR(root *Node, data Key) (*Node, bool) {
if root == nil {
return nil, false
}
if root.Data.Eq(data) {
switch {
case root.Link[0] == nil:
return root.Link[1], false
case root.Link[1] == nil:
return root.Link[0], false
}
heir := root.Link[0]
for heir.Link[1] != nil {
heir = heir.Link[1]
}
root.Data = heir.Data
data = heir.Data
}
dir := 0
if root.Data.Less(data) {
dir = 1
}
var done bool
root.Link[dir], done = removeR(root.Link[dir], data)
if done {
return root, true
}
root.Balance += 1 - 2*dir
switch root.Balance {
case 1, -1:
return root, true
case 0:
return root, false
}
return removeBalance(root, dir)
}
func Remove(tree **Node, data Key) {
*tree, _ = removeR(*tree, data)
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <iomanip>
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
template <typename IntegerType>
IntegerType arithmetic_derivative(IntegerType n) {
bool negative = n < 0;
if (negative)
n = -n;
if (n < 2)
return 0;
IntegerType sum = 0, count = 0, m = n;
while ((m & 1) == 0) {
m >>= 1;
count += n;
}
if (count > 0)
sum += count / 2;
for (IntegerType p = 3, sq = 9; sq <= m; p += 2) {
count = 0;
while (m % p == 0) {
m /= p;
count += n;
}
if (count > 0)
sum += count / p;
sq += (p + 1) << 2;
}
if (m > 1)
sum += n / m;
if (negative)
sum = -sum;
return sum;
}
int main() {
using boost::multiprecision::int128_t;
for (int n = -99, i = 0; n <= 100; ++n, ++i) {
std::cout << std::setw(4) << arithmetic_derivative(n)
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
int128_t p = 10;
std::cout << '\n';
for (int i = 0; i < 20; ++i, p *= 10) {
std::cout << "D(10^" << std::setw(2) << i + 1
<< ") / 7 = " << arithmetic_derivative(p) / 7 << '\n';
}
}
| package main
import (
"fmt"
"rcu"
)
func D(n float64) float64 {
if n < 0 {
return -D(-n)
}
if n < 2 {
return 0
}
var f []int
if n < 1e19 {
f = rcu.PrimeFactors(int(n))
} else {
g := int(n / 100)
f = rcu.PrimeFactors(g)
f = append(f, []int{2, 2, 5, 5}...)
}
c := len(f)
if c == 1 {
return 1
}
if c == 2 {
return float64(f[0] + f[1])
}
d := n / float64(f[0])
return D(d)*float64(f[0]) + d
}
func main() {
ad := make([]int, 200)
for n := -99; n < 101; n++ {
ad[n+99] = int(D(float64(n)))
}
rcu.PrintTable(ad, 10, 4, false)
fmt.Println()
pow := 1.0
for m := 1; m < 21; m++ {
pow *= 10
fmt.Printf("D(10^%-2d) / 7 = %.0f\n", m, D(pow)/7)
}
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <iostream>
int main() {
std::string str("AABBBC");
int count = 0;
do {
std::cout << str << (++count % 10 == 0 ? '\n' : ' ');
} while (std::next_permutation(str.begin(), str.end()));
}
| package main
import "fmt"
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
return
}
for i := index; i < n; i++ {
check := shouldSwap(s, index, i)
if check {
s[index], s[i] = s[i], s[index]
findPerms(s, index+1, n, res)
s[index], s[i] = s[i], s[index]
}
}
}
func createSlice(nums []int, charSet string) []byte {
var chars []byte
for i := 0; i < len(nums); i++ {
for j := 0; j < nums[i]; j++ {
chars = append(chars, charSet[i])
}
}
return chars
}
func main() {
var res, res2, res3 []string
nums := []int{2, 1}
s := createSlice(nums, "12")
findPerms(s, 0, len(s), &res)
fmt.Println(res)
fmt.Println()
nums = []int{2, 3, 1}
s = createSlice(nums, "123")
findPerms(s, 0, len(s), &res2)
fmt.Println(res2)
fmt.Println()
s = createSlice(nums, "ABC")
findPerms(s, 0, len(s), &res3)
fmt.Println(res3)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
int main() {
std::ofstream out("penrose_tiling.svg");
if (!out) {
std::cerr << "Cannot open output file.\n";
return EXIT_FAILURE;
}
std::string penrose("[N]++[N]++[N]++[N]++[N]");
for (int i = 1; i <= 4; ++i) {
std::string next;
for (char ch : penrose) {
switch (ch) {
case 'A':
break;
case 'M':
next += "OA++PA----NA[-OA----MA]++";
break;
case 'N':
next += "+OA--PA[---MA--NA]+";
break;
case 'O':
next += "-MA++NA[+++OA++PA]-";
break;
case 'P':
next += "--OA++++MA[+PA++++NA]--NA";
break;
default:
next += ch;
break;
}
}
penrose = std::move(next);
}
const double r = 30;
const double pi5 = 0.628318530717959;
double x = r * 8, y = r * 8, theta = pi5;
std::set<std::string> svg;
std::stack<std::tuple<double, double, double>> stack;
for (char ch : penrose) {
switch (ch) {
case 'A': {
double nx = x + r * std::cos(theta);
double ny = y + r * std::sin(theta);
std::ostringstream line;
line << std::fixed << std::setprecision(3) << "<line x1='" << x
<< "' y1='" << y << "' x2='" << nx << "' y2='" << ny << "'/>";
svg.insert(line.str());
x = nx;
y = ny;
} break;
case '+':
theta += pi5;
break;
case '-':
theta -= pi5;
break;
case '[':
stack.push({x, y, theta});
break;
case ']':
std::tie(x, y, theta) = stack.top();
stack.pop();
break;
}
}
out << "<svg xmlns='http:
<< "' width='" << r * 16 << "'>\n"
<< "<rect height='100%' width='100%' fill='black'/>\n"
<< "<g stroke='rgb(255,165,0)'>\n";
for (const auto& line : svg)
out << line << '\n';
out << "</g>\n</svg>\n";
return EXIT_SUCCESS;
}
| package main
import (
"github.com/fogleman/gg"
"math"
)
type tiletype int
const (
kite tiletype = iota
dart
)
type tile struct {
tt tiletype
x, y float64
angle, size float64
}
var gr = (1 + math.Sqrt(5)) / 2
const theta = math.Pi / 5
func setupPrototiles(w, h int) []tile {
var proto []tile
for a := math.Pi/2 + theta; a < 3*math.Pi; a += 2 * theta {
ww := float64(w / 2)
hh := float64(h / 2)
proto = append(proto, tile{kite, ww, hh, a, float64(w) / 2.5})
}
return proto
}
func distinctTiles(tls []tile) []tile {
tileset := make(map[tile]bool)
for _, tl := range tls {
tileset[tl] = true
}
distinct := make([]tile, len(tileset))
for tl, _ := range tileset {
distinct = append(distinct, tl)
}
return distinct
}
func deflateTiles(tls []tile, gen int) []tile {
if gen <= 0 {
return tls
}
var next []tile
for _, tl := range tls {
x, y, a, size := tl.x, tl.y, tl.angle, tl.size/gr
var nx, ny float64
if tl.tt == dart {
next = append(next, tile{kite, x, y, a + 5*theta, size})
for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {
nx = x + math.Cos(a-4*theta*sign)*gr*tl.size
ny = y - math.Sin(a-4*theta*sign)*gr*tl.size
next = append(next, tile{dart, nx, ny, a - 4*theta*sign, size})
}
} else {
for i, sign := 0, 1.0; i < 2; i, sign = i+1, -sign {
next = append(next, tile{dart, x, y, a - 4*theta*sign, size})
nx = x + math.Cos(a-theta*sign)*gr*tl.size
ny = y - math.Sin(a-theta*sign)*gr*tl.size
next = append(next, tile{kite, nx, ny, a + 3*theta*sign, size})
}
}
}
tls = distinctTiles(next)
return deflateTiles(tls, gen-1)
}
func drawTiles(dc *gg.Context, tls []tile) {
dist := [2][3]float64{{gr, gr, gr}, {-gr, -1, -gr}}
for _, tl := range tls {
angle := tl.angle - theta
dc.MoveTo(tl.x, tl.y)
ord := tl.tt
for i := 0; i < 3; i++ {
x := tl.x + dist[ord][i]*tl.size*math.Cos(angle)
y := tl.y - dist[ord][i]*tl.size*math.Sin(angle)
dc.LineTo(x, y)
angle += theta
}
dc.ClosePath()
if ord == kite {
dc.SetHexColor("FFA500")
} else {
dc.SetHexColor("FFFF00")
}
dc.FillPreserve()
dc.SetHexColor("A9A9A9")
dc.SetLineWidth(1)
dc.Stroke()
}
}
func main() {
w, h := 700, 450
dc := gg.NewContext(w, h)
dc.SetRGB(1, 1, 1)
dc.Clear()
tiles := deflateTiles(setupPrototiles(w, h), 5)
drawTiles(dc, tiles)
dc.SavePNG("penrose_tiling.png")
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <windows.h>
#include <iostream>
#include <ctime>
const int WID = 79, HEI = 22;
const float NCOUNT = ( float )( WID * HEI );
class coord : public COORD {
public:
coord( short x = 0, short y = 0 ) { set( x, y ); }
void set( short x, short y ) { X = x; Y = y; }
};
class winConsole {
public:
static winConsole* getInstamnce() { if( 0 == inst ) { inst = new winConsole(); } return inst; }
void showCursor( bool s ) { CONSOLE_CURSOR_INFO ci = { 1, s }; SetConsoleCursorInfo( conOut, &ci ); }
void setColor( WORD clr ) { SetConsoleTextAttribute( conOut, clr ); }
void setCursor( coord p ) { SetConsoleCursorPosition( conOut, p ); }
void flush() { FlushConsoleInputBuffer( conIn ); }
void kill() { delete inst; }
private:
winConsole() { conOut = GetStdHandle( STD_OUTPUT_HANDLE );
conIn = GetStdHandle( STD_INPUT_HANDLE ); showCursor( false ); }
static winConsole* inst;
HANDLE conOut, conIn;
};
class greed {
public:
greed() { console = winConsole::getInstamnce(); }
~greed() { console->kill(); }
void play() {
char g; do {
console->showCursor( false ); createBoard();
do { displayBoard(); getInput(); } while( existsMoves() );
displayBoard(); console->setCursor( coord( 0, 24 ) ); console->setColor( 0x07 );
console->setCursor( coord( 19, 8 ) ); std::cout << "+----------------------------------------+";
console->setCursor( coord( 19, 9 ) ); std::cout << "| GAME OVER |";
console->setCursor( coord( 19, 10 ) ); std::cout << "| PLAY AGAIN(Y/N)? |";
console->setCursor( coord( 19, 11 ) ); std::cout << "+----------------------------------------+";
console->setCursor( coord( 48, 10 ) ); console->showCursor( true ); console->flush(); std::cin >> g;
} while( g == 'Y' || g == 'y' );
}
private:
void createBoard() {
for( int y = 0; y < HEI; y++ ) {
for( int x = 0; x < WID; x++ ) {
brd[x + WID * y] = rand() % 9 + 1;
}
}
cursor.set( rand() % WID, rand() % HEI );
brd[cursor.X + WID * cursor.Y] = 0; score = 0;
printScore();
}
void displayBoard() {
console->setCursor( coord() ); int i;
for( int y = 0; y < HEI; y++ ) {
for( int x = 0; x < WID; x++ ) {
i = brd[x + WID * y]; console->setColor( 6 + i );
if( !i ) std::cout << " "; else std::cout << i;
}
std::cout << "\n";
}
console->setColor( 15 ); console->setCursor( cursor ); std::cout << "@";
}
void getInput() {
while( 1 ) {
if( ( GetAsyncKeyState( 'Q' ) & 0x8000 ) && cursor.X > 0 && cursor.Y > 0 ) { execute( -1, -1 ); break; }
if( ( GetAsyncKeyState( 'W' ) & 0x8000 ) && cursor.Y > 0 ) { execute( 0, -1 ); break; }
if( ( GetAsyncKeyState( 'E' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y > 0 ) { execute( 1, -1 ); break; }
if( ( GetAsyncKeyState( 'A' ) & 0x8000 ) && cursor.X > 0 ) { execute( -1, 0 ); break; }
if( ( GetAsyncKeyState( 'D' ) & 0x8000 ) && cursor.X < WID - 1 ) { execute( 1, 0 ); break; }
if( ( GetAsyncKeyState( 'Y' ) & 0x8000 ) && cursor.X > 0 && cursor.Y < HEI - 1 ) { execute( -1, 1 ); break; }
if( ( GetAsyncKeyState( 'X' ) & 0x8000 ) && cursor.Y < HEI - 1 ) { execute( 0, 1 ); break; }
if( ( GetAsyncKeyState( 'C' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y < HEI - 1 ) { execute( 1, 1 ); break; }
}
console->flush(); printScore();
}
void printScore() {
console->setCursor( coord( 0, 24 ) ); console->setColor( 0x2a );
std::cout << " SCORE: " << score << " : " << score * 100.f / NCOUNT << "% ";
}
void execute( int x, int y ) {
int i = brd[cursor.X + x + WID * ( cursor.Y + y )];
if( countSteps( i, x, y ) ) {
score += i;
while( i ) {
--i; cursor.X += x; cursor.Y += y;
brd[cursor.X + WID * cursor.Y] = 0;
}
}
}
bool countSteps( int i, int x, int y ) {
coord t( cursor.X, cursor.Y );
while( i ) {
--i; t.X += x; t.Y += y;
if( t.X < 0 || t.Y < 0 || t.X >= WID || t.Y >= HEI || !brd[t.X + WID * t.Y] ) return false;
}
return true;
}
bool existsMoves() {
int i;
for( int y = -1; y < 2; y++ ) {
for( int x = -1; x < 2; x++ ) {
if( !x && !y ) continue;
i = brd[cursor.X + x + WID * ( cursor.Y + y )];
if( i > 0 && countSteps( i, x, y ) ) return true;
}
}
return false;
}
winConsole* console;
int brd[WID * HEI];
float score; coord cursor;
};
winConsole* winConsole::inst = 0;
int main( int argc, char* argv[] ) {
srand( ( unsigned )time( 0 ) );
SetConsoleTitle( "Greed" );
greed g; g.play(); return 0;
}
| package main
import (
"fmt"
"github.com/nsf/termbox-go"
"log"
"math/rand"
"strconv"
"time"
)
type coord struct{ x, y int }
const (
width = 79
height = 22
nCount = float64(width * height)
)
var (
board [width * height]int
score = 0
bold = termbox.AttrBold
cursor coord
)
var colors = [10]termbox.Attribute{
termbox.ColorDefault,
termbox.ColorWhite,
termbox.ColorBlack | bold,
termbox.ColorBlue | bold,
termbox.ColorGreen | bold,
termbox.ColorCyan | bold,
termbox.ColorRed | bold,
termbox.ColorMagenta | bold,
termbox.ColorYellow | bold,
termbox.ColorWhite | bold,
}
func printAt(x, y int, s string, fg, bg termbox.Attribute) {
for _, r := range s {
termbox.SetCell(x, y, r, fg, bg)
x++
}
}
func createBoard() {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
board[x+width*y] = rand.Intn(9) + 1
}
}
cursor = coord{rand.Intn(width), rand.Intn(height)}
board[cursor.x+width*cursor.y] = 0
score = 0
printScore()
}
func displayBoard() {
termbox.SetCursor(0, 0)
bg := colors[0]
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
i := board[x+width*y]
fg := colors[i]
s := " "
if i > 0 {
s = strconv.Itoa(i)
}
printAt(x, y, s, fg, bg)
}
}
fg := colors[9]
termbox.SetCursor(cursor.x, cursor.y)
printAt(cursor.x, cursor.y, "@", fg, bg)
termbox.Flush()
}
func printScore() {
termbox.SetCursor(0, 24)
fg := colors[4]
bg := termbox.ColorGreen
s := fmt.Sprintf(" SCORE: %d : %.3f%% ", score, float64(score)*100.0/nCount)
printAt(0, 24, s, fg, bg)
termbox.Flush()
}
func execute(x, y int) {
i := board[cursor.x+x+width*(cursor.y+y)]
if countSteps(i, x, y) {
score += i
for i != 0 {
i--
cursor.x += x
cursor.y += y
board[cursor.x+width*cursor.y] = 0
}
}
}
func countSteps(i, x, y int) bool {
t := cursor
for i != 0 {
i--
t.x += x
t.y += y
if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {
return false
}
}
return true
}
func existsMoves() bool {
for y := -1; y < 2; y++ {
for x := -1; x < 2; x++ {
if x == 0 && y == 0 {
continue
}
ix := cursor.x + x + width*(cursor.y+y)
i := 0
if ix >= 0 && ix < len(board) {
i = board[ix]
}
if i > 0 && countSteps(i, x, y) {
return true
}
}
}
return false
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
err := termbox.Init()
check(err)
defer termbox.Close()
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
for {
termbox.HideCursor()
createBoard()
for {
displayBoard()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
switch ev.Ch {
case 'q', 'Q':
if cursor.x > 0 && cursor.y > 0 {
execute(-1, -1)
}
case 'w', 'W':
if cursor.y > 0 {
execute(0, -1)
}
case 'e', 'E':
if cursor.x < width-1 && cursor.y > 0 {
execute(1, -1)
}
case 'a', 'A':
if cursor.x > 0 {
execute(-1, 0)
}
case 'd', 'D':
if cursor.x < width-1 {
execute(1, 0)
}
case 'z', 'Z':
if cursor.x > 0 && cursor.y < height-1 {
execute(-1, 1)
}
case 'x', 'X':
if cursor.y < height-1 {
execute(0, 1)
}
case 'c', 'C':
if cursor.x < width-1 && cursor.y < height-1 {
execute(1, 1)
}
case 'l', 'L':
return
}
} else if ev.Type == termbox.EventResize {
termbox.Flush()
}
}
printScore()
if !existsMoves() {
break
}
}
displayBoard()
fg := colors[7]
bg := colors[0]
printAt(19, 8, "+----------------------------------------+", fg, bg)
printAt(19, 9, "| GAME OVER |", fg, bg)
printAt(19, 10, "| PLAY AGAIN(Y/N)? |", fg, bg)
printAt(19, 11, "+----------------------------------------+", fg, bg)
termbox.SetCursor(48, 10)
termbox.Flush()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Ch == 'y' || ev.Ch == 'Y' {
break
} else {
return
}
}
}
}
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <windows.h>
#include <iostream>
#include <ctime>
const int WID = 79, HEI = 22;
const float NCOUNT = ( float )( WID * HEI );
class coord : public COORD {
public:
coord( short x = 0, short y = 0 ) { set( x, y ); }
void set( short x, short y ) { X = x; Y = y; }
};
class winConsole {
public:
static winConsole* getInstamnce() { if( 0 == inst ) { inst = new winConsole(); } return inst; }
void showCursor( bool s ) { CONSOLE_CURSOR_INFO ci = { 1, s }; SetConsoleCursorInfo( conOut, &ci ); }
void setColor( WORD clr ) { SetConsoleTextAttribute( conOut, clr ); }
void setCursor( coord p ) { SetConsoleCursorPosition( conOut, p ); }
void flush() { FlushConsoleInputBuffer( conIn ); }
void kill() { delete inst; }
private:
winConsole() { conOut = GetStdHandle( STD_OUTPUT_HANDLE );
conIn = GetStdHandle( STD_INPUT_HANDLE ); showCursor( false ); }
static winConsole* inst;
HANDLE conOut, conIn;
};
class greed {
public:
greed() { console = winConsole::getInstamnce(); }
~greed() { console->kill(); }
void play() {
char g; do {
console->showCursor( false ); createBoard();
do { displayBoard(); getInput(); } while( existsMoves() );
displayBoard(); console->setCursor( coord( 0, 24 ) ); console->setColor( 0x07 );
console->setCursor( coord( 19, 8 ) ); std::cout << "+----------------------------------------+";
console->setCursor( coord( 19, 9 ) ); std::cout << "| GAME OVER |";
console->setCursor( coord( 19, 10 ) ); std::cout << "| PLAY AGAIN(Y/N)? |";
console->setCursor( coord( 19, 11 ) ); std::cout << "+----------------------------------------+";
console->setCursor( coord( 48, 10 ) ); console->showCursor( true ); console->flush(); std::cin >> g;
} while( g == 'Y' || g == 'y' );
}
private:
void createBoard() {
for( int y = 0; y < HEI; y++ ) {
for( int x = 0; x < WID; x++ ) {
brd[x + WID * y] = rand() % 9 + 1;
}
}
cursor.set( rand() % WID, rand() % HEI );
brd[cursor.X + WID * cursor.Y] = 0; score = 0;
printScore();
}
void displayBoard() {
console->setCursor( coord() ); int i;
for( int y = 0; y < HEI; y++ ) {
for( int x = 0; x < WID; x++ ) {
i = brd[x + WID * y]; console->setColor( 6 + i );
if( !i ) std::cout << " "; else std::cout << i;
}
std::cout << "\n";
}
console->setColor( 15 ); console->setCursor( cursor ); std::cout << "@";
}
void getInput() {
while( 1 ) {
if( ( GetAsyncKeyState( 'Q' ) & 0x8000 ) && cursor.X > 0 && cursor.Y > 0 ) { execute( -1, -1 ); break; }
if( ( GetAsyncKeyState( 'W' ) & 0x8000 ) && cursor.Y > 0 ) { execute( 0, -1 ); break; }
if( ( GetAsyncKeyState( 'E' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y > 0 ) { execute( 1, -1 ); break; }
if( ( GetAsyncKeyState( 'A' ) & 0x8000 ) && cursor.X > 0 ) { execute( -1, 0 ); break; }
if( ( GetAsyncKeyState( 'D' ) & 0x8000 ) && cursor.X < WID - 1 ) { execute( 1, 0 ); break; }
if( ( GetAsyncKeyState( 'Y' ) & 0x8000 ) && cursor.X > 0 && cursor.Y < HEI - 1 ) { execute( -1, 1 ); break; }
if( ( GetAsyncKeyState( 'X' ) & 0x8000 ) && cursor.Y < HEI - 1 ) { execute( 0, 1 ); break; }
if( ( GetAsyncKeyState( 'C' ) & 0x8000 ) && cursor.X < WID - 1 && cursor.Y < HEI - 1 ) { execute( 1, 1 ); break; }
}
console->flush(); printScore();
}
void printScore() {
console->setCursor( coord( 0, 24 ) ); console->setColor( 0x2a );
std::cout << " SCORE: " << score << " : " << score * 100.f / NCOUNT << "% ";
}
void execute( int x, int y ) {
int i = brd[cursor.X + x + WID * ( cursor.Y + y )];
if( countSteps( i, x, y ) ) {
score += i;
while( i ) {
--i; cursor.X += x; cursor.Y += y;
brd[cursor.X + WID * cursor.Y] = 0;
}
}
}
bool countSteps( int i, int x, int y ) {
coord t( cursor.X, cursor.Y );
while( i ) {
--i; t.X += x; t.Y += y;
if( t.X < 0 || t.Y < 0 || t.X >= WID || t.Y >= HEI || !brd[t.X + WID * t.Y] ) return false;
}
return true;
}
bool existsMoves() {
int i;
for( int y = -1; y < 2; y++ ) {
for( int x = -1; x < 2; x++ ) {
if( !x && !y ) continue;
i = brd[cursor.X + x + WID * ( cursor.Y + y )];
if( i > 0 && countSteps( i, x, y ) ) return true;
}
}
return false;
}
winConsole* console;
int brd[WID * HEI];
float score; coord cursor;
};
winConsole* winConsole::inst = 0;
int main( int argc, char* argv[] ) {
srand( ( unsigned )time( 0 ) );
SetConsoleTitle( "Greed" );
greed g; g.play(); return 0;
}
| package main
import (
"fmt"
"github.com/nsf/termbox-go"
"log"
"math/rand"
"strconv"
"time"
)
type coord struct{ x, y int }
const (
width = 79
height = 22
nCount = float64(width * height)
)
var (
board [width * height]int
score = 0
bold = termbox.AttrBold
cursor coord
)
var colors = [10]termbox.Attribute{
termbox.ColorDefault,
termbox.ColorWhite,
termbox.ColorBlack | bold,
termbox.ColorBlue | bold,
termbox.ColorGreen | bold,
termbox.ColorCyan | bold,
termbox.ColorRed | bold,
termbox.ColorMagenta | bold,
termbox.ColorYellow | bold,
termbox.ColorWhite | bold,
}
func printAt(x, y int, s string, fg, bg termbox.Attribute) {
for _, r := range s {
termbox.SetCell(x, y, r, fg, bg)
x++
}
}
func createBoard() {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
board[x+width*y] = rand.Intn(9) + 1
}
}
cursor = coord{rand.Intn(width), rand.Intn(height)}
board[cursor.x+width*cursor.y] = 0
score = 0
printScore()
}
func displayBoard() {
termbox.SetCursor(0, 0)
bg := colors[0]
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
i := board[x+width*y]
fg := colors[i]
s := " "
if i > 0 {
s = strconv.Itoa(i)
}
printAt(x, y, s, fg, bg)
}
}
fg := colors[9]
termbox.SetCursor(cursor.x, cursor.y)
printAt(cursor.x, cursor.y, "@", fg, bg)
termbox.Flush()
}
func printScore() {
termbox.SetCursor(0, 24)
fg := colors[4]
bg := termbox.ColorGreen
s := fmt.Sprintf(" SCORE: %d : %.3f%% ", score, float64(score)*100.0/nCount)
printAt(0, 24, s, fg, bg)
termbox.Flush()
}
func execute(x, y int) {
i := board[cursor.x+x+width*(cursor.y+y)]
if countSteps(i, x, y) {
score += i
for i != 0 {
i--
cursor.x += x
cursor.y += y
board[cursor.x+width*cursor.y] = 0
}
}
}
func countSteps(i, x, y int) bool {
t := cursor
for i != 0 {
i--
t.x += x
t.y += y
if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {
return false
}
}
return true
}
func existsMoves() bool {
for y := -1; y < 2; y++ {
for x := -1; x < 2; x++ {
if x == 0 && y == 0 {
continue
}
ix := cursor.x + x + width*(cursor.y+y)
i := 0
if ix >= 0 && ix < len(board) {
i = board[ix]
}
if i > 0 && countSteps(i, x, y) {
return true
}
}
}
return false
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
err := termbox.Init()
check(err)
defer termbox.Close()
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
for {
termbox.HideCursor()
createBoard()
for {
displayBoard()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
switch ev.Ch {
case 'q', 'Q':
if cursor.x > 0 && cursor.y > 0 {
execute(-1, -1)
}
case 'w', 'W':
if cursor.y > 0 {
execute(0, -1)
}
case 'e', 'E':
if cursor.x < width-1 && cursor.y > 0 {
execute(1, -1)
}
case 'a', 'A':
if cursor.x > 0 {
execute(-1, 0)
}
case 'd', 'D':
if cursor.x < width-1 {
execute(1, 0)
}
case 'z', 'Z':
if cursor.x > 0 && cursor.y < height-1 {
execute(-1, 1)
}
case 'x', 'X':
if cursor.y < height-1 {
execute(0, 1)
}
case 'c', 'C':
if cursor.x < width-1 && cursor.y < height-1 {
execute(1, 1)
}
case 'l', 'L':
return
}
} else if ev.Type == termbox.EventResize {
termbox.Flush()
}
}
printScore()
if !existsMoves() {
break
}
}
displayBoard()
fg := colors[7]
bg := colors[0]
printAt(19, 8, "+----------------------------------------+", fg, bg)
printAt(19, 9, "| GAME OVER |", fg, bg)
printAt(19, 10, "| PLAY AGAIN(Y/N)? |", fg, bg)
printAt(19, 11, "+----------------------------------------+", fg, bg)
termbox.SetCursor(48, 10)
termbox.Flush()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Ch == 'y' || ev.Ch == 'Y' {
break
} else {
return
}
}
}
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <iomanip>
#include <iostream>
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3, sq = 9; sq <= n; p += 2) {
for (; n % p == 0; n /= p)
sum += p;
sq += (p + 1) << 2;
}
if (n > 1)
sum += n;
return sum;
}
int prime_divisor_sum(int n) {
int sum = 0;
if ((n & 1) == 0) {
sum += 2;
n >>= 1;
while ((n & 1) == 0)
n >>= 1;
}
for (int p = 3, sq = 9; sq <= n; p += 2) {
if (n % p == 0) {
sum += p;
n /= p;
while (n % p == 0)
n /= p;
}
sq += (p + 1) << 2;
}
if (n > 1)
sum += n;
return sum;
}
int main() {
const int limit = 30;
int dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;
std::cout << "First " << limit << " Ruth-Aaron numbers (factors):\n";
for (int n = 2, count = 0; count < limit; ++n) {
fsum2 = prime_factor_sum(n);
if (fsum1 == fsum2) {
++count;
std::cout << std::setw(5) << n - 1
<< (count % 10 == 0 ? '\n' : ' ');
}
fsum1 = fsum2;
}
std::cout << "\nFirst " << limit << " Ruth-Aaron numbers (divisors):\n";
for (int n = 2, count = 0; count < limit; ++n) {
dsum2 = prime_divisor_sum(n);
if (dsum1 == dsum2) {
++count;
std::cout << std::setw(5) << n - 1
<< (count % 10 == 0 ? '\n' : ' ');
}
dsum1 = dsum2;
}
dsum1 = 0, fsum1 = 0, dsum2 = 0, fsum2 = 0;
for (int n = 2;; ++n) {
int fsum3 = prime_factor_sum(n);
if (fsum1 == fsum2 && fsum2 == fsum3) {
std::cout << "\nFirst Ruth-Aaron triple (factors): " << n - 2
<< '\n';
break;
}
fsum1 = fsum2;
fsum2 = fsum3;
}
for (int n = 2;; ++n) {
int dsum3 = prime_divisor_sum(n);
if (dsum1 == dsum2 && dsum2 == dsum3) {
std::cout << "\nFirst Ruth-Aaron triple (divisors): " << n - 2
<< '\n';
break;
}
dsum1 = dsum2;
dsum2 = dsum3;
}
}
| package main
import (
"fmt"
"rcu"
)
func prune(a []int) []int {
prev := a[0]
b := []int{prev}
for i := 1; i < len(a); i++ {
if a[i] != prev {
b = append(b, a[i])
prev = a[i]
}
}
return b
}
func main() {
var resF, resD, resT, factors1 []int
factors2 := []int{2}
factors3 := []int{3}
var sum1, sum2, sum3 int = 0, 2, 3
var countF, countD, countT int
for n := 2; countT < 1 || countD < 30 || countF < 30; n++ {
factors1 = factors2
factors2 = factors3
factors3 = rcu.PrimeFactors(n + 2)
sum1 = sum2
sum2 = sum3
sum3 = rcu.SumInts(factors3)
if countF < 30 && sum1 == sum2 {
resF = append(resF, n)
countF++
}
if sum1 == sum2 && sum2 == sum3 {
resT = append(resT, n)
countT++
}
if countD < 30 {
factors4 := make([]int, len(factors1))
copy(factors4, factors1)
factors5 := make([]int, len(factors2))
copy(factors5, factors2)
factors4 = prune(factors4)
factors5 = prune(factors5)
if rcu.SumInts(factors4) == rcu.SumInts(factors5) {
resD = append(resD, n)
countD++
}
}
}
fmt.Println("First 30 Ruth-Aaron numbers (factors):")
fmt.Println(resF)
fmt.Println("\nFirst 30 Ruth-Aaron numbers (divisors):")
fmt.Println(resD)
fmt.Println("\nFirst Ruth-Aaron triple (factors):")
fmt.Println(resT[0])
resT = resT[:0]
factors1 = factors1[:0]
factors2 = factors2[:1]
factors2[0] = 2
factors3 = factors3[:1]
factors3[0] = 3
countT = 0
for n := 2; countT < 1; n++ {
factors1 = factors2
factors2 = factors3
factors3 = prune(rcu.PrimeFactors(n + 2))
sum1 = sum2
sum2 = sum3
sum3 = rcu.SumInts(factors3)
if sum1 == sum2 && sum2 == sum3 {
resT = append(resT, n)
countT++
}
}
fmt.Println("\nFirst Ruth-Aaron triple (divisors):")
fmt.Println(resT[0])
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
bool duffinian(int n) {
if (n == 2)
return false;
int total = 1, power = 2, m = n;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (int p = 3; p * p <= n; p += 2) {
int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (m == n)
return false;
if (n > 1)
total *= n + 1;
return std::gcd(total, m) == 1;
}
int main() {
std::cout << "First 50 Duffinian numbers:\n";
for (int n = 1, count = 0; count < 50; ++n) {
if (duffinian(n))
std::cout << std::setw(3) << n << (++count % 10 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 50 Duffinian triplets:\n";
for (int n = 1, m = 0, count = 0; count < 50; ++n) {
if (duffinian(n))
++m;
else
m = 0;
if (m == 3) {
std::ostringstream os;
os << '(' << n - 2 << ", " << n - 1 << ", " << n << ')';
std::cout << std::left << std::setw(24) << os.str()
<< (++count % 3 == 0 ? '\n' : ' ');
}
}
std::cout << '\n';
}
| package main
import (
"fmt"
"math"
"rcu"
)
func isSquare(n int) bool {
s := int(math.Sqrt(float64(n)))
return s*s == n
}
func main() {
limit := 200000
d := rcu.PrimeSieve(limit-1, true)
d[1] = false
for i := 2; i < limit; i++ {
if !d[i] {
continue
}
if i%2 == 0 && !isSquare(i) && !isSquare(i/2) {
d[i] = false
continue
}
sigmaSum := rcu.SumInts(rcu.Divisors(i))
if rcu.Gcd(sigmaSum, i) != 1 {
d[i] = false
}
}
var duff []int
for i := 1; i < len(d); i++ {
if d[i] {
duff = append(duff, i)
}
}
fmt.Println("First 50 Duffinian numbers:")
rcu.PrintTable(duff[0:50], 10, 3, false)
var triplets [][3]int
for i := 2; i < limit; i++ {
if d[i] && d[i-1] && d[i-2] {
triplets = append(triplets, [3]int{i - 2, i - 1, i})
}
}
fmt.Println("\nFirst 56 Duffinian triplets:")
for i := 0; i < 14; i++ {
s := fmt.Sprintf("%6v", triplets[i*4:i*4+4])
fmt.Println(s[1 : len(s)-1])
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
std::vector<int> prime_factors(int n) {
std::vector<int> factors;
if (n > 1 && (n & 1) == 0) {
factors.push_back(2);
while ((n & 1) == 0)
n >>= 1;
}
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
factors.push_back(p);
while (n % p == 0)
n /= p;
}
}
if (n > 1)
factors.push_back(n);
return factors;
}
int main() {
const int limit = 1000000;
const int imax = limit / 6;
std::vector<bool> sieve = prime_sieve(imax + 1);
std::vector<bool> sphenic(limit + 1, false);
for (int i = 0; i <= imax; ++i) {
if (!sieve[i])
continue;
int jmax = std::min(imax, limit / (i * i));
if (jmax <= i)
break;
for (int j = i + 1; j <= jmax; ++j) {
if (!sieve[j])
continue;
int p = i * j;
int kmax = std::min(imax, limit / p);
if (kmax <= j)
break;
for (int k = j + 1; k <= kmax; ++k) {
if (!sieve[k])
continue;
assert(p * k <= limit);
sphenic[p * k] = true;
}
}
}
std::cout << "Sphenic numbers < 1000:\n";
for (int i = 0, n = 0; i < 1000; ++i) {
if (!sphenic[i])
continue;
++n;
std::cout << std::setw(3) << i << (n % 15 == 0 ? '\n' : ' ');
}
std::cout << "\nSphenic triplets < 10,000:\n";
for (int i = 0, n = 0; i < 10000; ++i) {
if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {
++n;
std::cout << "(" << i - 2 << ", " << i - 1 << ", " << i << ")"
<< (n % 3 == 0 ? '\n' : ' ');
}
}
int count = 0, triplets = 0, s200000 = 0, t5000 = 0;
for (int i = 0; i < limit; ++i) {
if (!sphenic[i])
continue;
++count;
if (count == 200000)
s200000 = i;
if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {
++triplets;
if (triplets == 5000)
t5000 = i;
}
}
std::cout << "\nNumber of sphenic numbers < 1,000,000: " << count << '\n';
std::cout << "Number of sphenic triplets < 1,000,000: " << triplets << '\n';
auto factors = prime_factors(s200000);
assert(factors.size() == 3);
std::cout << "The 200,000th sphenic number: " << s200000 << " = "
<< factors[0] << " * " << factors[1] << " * " << factors[2]
<< '\n';
std::cout << "The 5,000th sphenic triplet: (" << t5000 - 2 << ", "
<< t5000 - 1 << ", " << t5000 << ")\n";
}
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
const limit = 1000000
limit2 := int(math.Cbrt(limit))
primes := rcu.Primes(limit / 6)
pc := len(primes)
var sphenic []int
fmt.Println("Sphenic numbers less than 1,000:")
for i := 0; i < pc-2; i++ {
if primes[i] > limit2 {
break
}
for j := i + 1; j < pc-1; j++ {
prod := primes[i] * primes[j]
if prod+primes[j+1] >= limit {
break
}
for k := j + 1; k < pc; k++ {
res := prod * primes[k]
if res >= limit {
break
}
sphenic = append(sphenic, res)
}
}
}
sort.Ints(sphenic)
ix := sort.Search(len(sphenic), func(i int) bool { return sphenic[i] >= 1000 })
rcu.PrintTable(sphenic[:ix], 15, 3, false)
fmt.Println("\nSphenic triplets less than 10,000:")
var triplets [][3]int
for i := 0; i < len(sphenic)-2; i++ {
s := sphenic[i]
if sphenic[i+1] == s+1 && sphenic[i+2] == s+2 {
triplets = append(triplets, [3]int{s, s + 1, s + 2})
}
}
ix = sort.Search(len(triplets), func(i int) bool { return triplets[i][2] >= 10000 })
for i := 0; i < ix; i++ {
fmt.Printf("%4d ", triplets[i])
if (i+1)%3 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThere are %s sphenic numbers less than 1,000,000.\n", rcu.Commatize(len(sphenic)))
fmt.Printf("There are %s sphenic triplets less than 1,000,000.\n", rcu.Commatize(len(triplets)))
s := sphenic[199999]
pf := rcu.PrimeFactors(s)
fmt.Printf("The 200,000th sphenic number is %s (%d*%d*%d).\n", rcu.Commatize(s), pf[0], pf[1], pf[2])
fmt.Printf("The 5,000th sphenic triplet is %v.\n.", triplets[4999])
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
{
if(*first == depth)
{
tree.push_back(*first);
++first;
}
else
{
tree.push_back(MakeTree(first, last, depth + 1));
first = find(first + 1, last, depth);
}
}
return tree;
}
void PrintTree(input_iterator auto first, input_iterator auto last)
{
cout << "[";
for(auto it = first; it != last; ++it)
{
if(it != first) cout << ", ";
if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)
{
cout << *it;
}
else
{
if(it->type() == typeid(unsigned int))
{
cout << any_cast<unsigned int>(*it);
}
else
{
const auto& subTree = any_cast<vector<any>>(*it);
PrintTree(subTree.begin(), subTree.end());
}
}
}
cout << "]";
}
int main(void)
{
auto execises = vector<vector<unsigned int>> {
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3}
};
for(const auto& e : execises)
{
auto tree = MakeTree(e.begin(), e.end());
PrintTree(e.begin(), e.end());
cout << " Nests to:\n";
PrintTree(tree.begin(), tree.end());
cout << "\n\n";
}
}
| package main
import "fmt"
type any = interface{}
func toTree(list []int) any {
s := []any{[]any{}}
for _, n := range list {
for n != len(s) {
if n > len(s) {
inner := []any{}
s[len(s)-1] = append(s[len(s)-1].([]any), inner)
s = append(s, inner)
} else {
s = s[0 : len(s)-1]
}
}
s[len(s)-1] = append(s[len(s)-1].([]any), n)
for i := len(s) - 2; i >= 0; i-- {
le := len(s[i].([]any))
s[i].([]any)[le-1] = s[i+1]
}
}
return s[0]
}
func main() {
tests := [][]int{
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3},
}
for _, test := range tests {
nest := toTree(test)
fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", test), nest)
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <any>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
vector<any> tree;
while (first < last && depth <= *first)
{
if(*first == depth)
{
tree.push_back(*first);
++first;
}
else
{
tree.push_back(MakeTree(first, last, depth + 1));
first = find(first + 1, last, depth);
}
}
return tree;
}
void PrintTree(input_iterator auto first, input_iterator auto last)
{
cout << "[";
for(auto it = first; it != last; ++it)
{
if(it != first) cout << ", ";
if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)
{
cout << *it;
}
else
{
if(it->type() == typeid(unsigned int))
{
cout << any_cast<unsigned int>(*it);
}
else
{
const auto& subTree = any_cast<vector<any>>(*it);
PrintTree(subTree.begin(), subTree.end());
}
}
}
cout << "]";
}
int main(void)
{
auto execises = vector<vector<unsigned int>> {
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3}
};
for(const auto& e : execises)
{
auto tree = MakeTree(e.begin(), e.end());
PrintTree(e.begin(), e.end());
cout << " Nests to:\n";
PrintTree(tree.begin(), tree.end());
cout << "\n\n";
}
}
| package main
import "fmt"
type any = interface{}
func toTree(list []int) any {
s := []any{[]any{}}
for _, n := range list {
for n != len(s) {
if n > len(s) {
inner := []any{}
s[len(s)-1] = append(s[len(s)-1].([]any), inner)
s = append(s, inner)
} else {
s = s[0 : len(s)-1]
}
}
s[len(s)-1] = append(s[len(s)-1].([]any), n)
for i := len(s) - 2; i >= 0; i-- {
le := len(s[i].([]any))
s[i].([]any)[le-1] = s[i+1]
}
}
return s[0]
}
func main() {
tests := [][]int{
{},
{1, 2, 4},
{3, 1, 3, 1},
{1, 2, 3, 1},
{3, 2, 1, 3},
{3, 3, 3, 1, 1, 3, 3, 3},
}
for _, test := range tests {
nest := toTree(test)
fmt.Printf("%17s => %v\n", fmt.Sprintf("%v", test), nest)
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <map>
#include <set>
#include <regex>
using namespace std;
map<string, string> terminals;
map<string, vector<vector<string>>> nonterminalRules;
map<string, set<string>> nonterminalFirst;
map<string, vector<string>> nonterminalCode;
int main(int argc, char **argv) {
if (argc < 3) {
cout << "Usage: <input file> <output file>" << endl;
return 1;
}
ifstream inFile(argv[1]);
ofstream outFile(argv[2]);
regex blankLine(R"(^\s*$)");
regex terminalPattern(R"((\w+)\s+(.+))");
regex rulePattern(R"(^!!\s*(\w+)\s*->\s*((?:\w+\s*)*)$)");
regex argPattern(R"(\$(\d+))");
smatch results;
string line;
while (true) {
getline(inFile, line);
if (regex_match(line, blankLine))
break;
regex_match(line, results, terminalPattern);
terminals[results[1]] = results[2];
}
outFile << "#include <iostream>" << endl;
outFile << "#include <fstream>" << endl;
outFile << "#include <string>" << endl;
outFile << "#include <regex>" << endl;
outFile << "using namespace std;" << endl << endl;
outFile << "string input, nextToken, nextTokenValue;" << endl;
outFile << "string prevToken, prevTokenValue;" << endl << endl;
outFile << "void advanceToken() {" << endl;
outFile << " static smatch results;" << endl << endl;
outFile << " prevToken = nextToken;" << endl;
outFile << " prevTokenValue = nextTokenValue;" << endl << endl;
for (auto i = terminals.begin(); i != terminals.end(); ++i) {
string name = i->first + "_pattern";
string pattern = i->second;
outFile << " static regex " << name << "(R\"(^\\s*(" << pattern << "))\");" << endl;
outFile << " if (regex_search(input, results, " << name << ", regex_constants::match_continuous)) {" << endl;
outFile << " nextToken = \"" << i->first << "\";" << endl;
outFile << " nextTokenValue = results[1];" << endl;
outFile << " input = regex_replace(input, " << name << ", \"\");" << endl;
outFile << " return;" << endl;
outFile << " }" << endl << endl;
}
outFile << " static regex eof(R\"(\\s*)\");" << endl;
outFile << " if (regex_match(input, results, eof, regex_constants::match_continuous)) {" << endl;
outFile << " nextToken = \"\";" << endl;
outFile << " nextTokenValue = \"\";" << endl;
outFile << " return;" << endl;
outFile << " }" << endl << endl;
outFile << " throw \"Unknown token\";" << endl;
outFile << "}" << endl << endl;
outFile << "bool same(string symbol) {" << endl;
outFile << " if (symbol == nextToken) {" << endl;
outFile << " advanceToken();" << endl;
outFile << " return true;" << endl;
outFile << " }" << endl;
outFile << " return false;" << endl;
outFile << "}" << endl << endl;
while (true) {
getline(inFile, line);
if (regex_match(line, results, rulePattern))
break;
outFile << line << endl;
}
while (true) {
string name = results[1];
stringstream ss(results[2]);
string tempString;
vector<string> tempVector;
while (ss >> tempString)
tempVector.push_back(tempString);
nonterminalRules[name].push_back(tempVector);
string code = "";
while (true) {
getline(inFile, line);
if (!inFile || regex_match(line, results, rulePattern))
break;
line = regex_replace(line, argPattern, "results[$1]");
code += line + "\n";
}
nonterminalCode[name].push_back(code);
if (!inFile)
break;
}
bool done = false;
while (!done)
for (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {
string name = i->first;
done = true;
if (nonterminalFirst.find(i->first) == nonterminalFirst.end())
nonterminalFirst[i->first] = set<string>();
for (int j = 0; j < i->second.size(); ++j) {
if (i->second[j].size() == 0)
nonterminalFirst[i->first].insert("");
else {
string first = i->second[j][0];
if (nonterminalFirst.find(first) != nonterminalFirst.end()) {
for (auto k = nonterminalFirst[first].begin(); k != nonterminalFirst[first].end(); ++k) {
if (nonterminalFirst[name].find(*k) == nonterminalFirst[name].end()) {
nonterminalFirst[name].insert(*k);
done = false;
}
}
} else if (nonterminalFirst[name].find(first) == nonterminalFirst[name].end()) {
nonterminalFirst[name].insert(first);
done = false;
}
}
}
}
for (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {
string name = i->first + "_rule";
outFile << "string " << name << "();" << endl;
}
outFile << endl;
for (auto i = nonterminalRules.begin(); i != nonterminalRules.end(); ++i) {
string name = i->first + "_rule";
outFile << "string " << name << "() {" << endl;
outFile << " vector<string> results;" << endl;
outFile << " results.push_back(\"\");" << endl << endl;
int epsilon = -1;
for (int j = 0; epsilon == -1 && j < i->second.size(); ++j)
if (i->second[j].size() == 0)
epsilon = j;
for (int j = 0; j < i->second.size(); ++j) {
if (j == epsilon)
continue;
string token = i->second[j][0];
if (terminals.find(token) != terminals.end())
outFile << " if (nextToken == \"" << i->second[j][0] << "\") {" << endl;
else {
outFile << " if (";
bool first = true;
for (auto k = nonterminalFirst[token].begin(); k != nonterminalFirst[token].end(); ++k, first = false) {
if (!first)
outFile << " || ";
outFile << "nextToken == \"" << (*k) << "\"";
}
outFile << ") {" << endl;
}
for (int k = 0; k < i->second[j].size(); ++k) {
if (terminals.find(i->second[j][k]) != terminals.end()) {
outFile << " if(same(\"" << i->second[j][k] << "\"))" << endl;
outFile << " results.push_back(prevTokenValue);" << endl;
outFile << " else" << endl;
outFile << " throw \"Syntax error - mismatched token\";" << endl;
} else
outFile << " results.push_back(" << i->second[j][k] << "_rule());" << endl;
}
outFile << nonterminalCode[i->first][j];
outFile << " }" << endl << endl;
}
if (epsilon == -1)
outFile << " throw \"Syntax error - unmatched token\";" << endl;
else
outFile << nonterminalCode[i->first][epsilon];
outFile << "}" << endl << endl;
}
outFile << "int main(int argc, char **argv) {" << endl;
outFile << " if(argc < 2) {" << endl;
outFile << " cout << \"Usage: <input file>\" << endl;" << endl;
outFile << " return 1;" << endl;
outFile << " }" << endl << endl;
outFile << " ifstream file(argv[1]);" << endl;
outFile << " string line;" << endl;
outFile << " input = \"\";" << endl << endl;
outFile << " while(true) {" << endl;
outFile << " getline(file, line);" << endl;
outFile << " if(!file) break;" << endl;
outFile << " input += line + \"\\n\";" << endl;
outFile << " }" << endl << endl;
outFile << " advanceToken();" << endl << endl;
outFile << " start_rule();" << endl;
outFile << "}" << endl;
}
| package main
import (
"fmt"
"go/ast"
"go/parser"
"log"
)
func labelStr(label int) string {
return fmt.Sprintf("_%04d", label)
}
type binexp struct {
op, left, right string
kind, index int
}
func main() {
x := "(one + two) * three - four * five"
fmt.Println("Expression to parse: ", x)
f, err := parser.ParseExpr(x)
if err != nil {
log.Fatal(err)
}
fmt.Println("\nThe abstract syntax tree for this expression:")
ast.Print(nil, f)
fmt.Println("\nThe corresponding three-address code:")
var binexps []binexp
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.BinaryExpr:
sx, ok1 := x.X.(*ast.Ident)
sy, ok2 := x.Y.(*ast.Ident)
op := x.Op.String()
if ok1 && ok2 {
binexps = append(binexps, binexp{op, sx.Name, sy.Name, 3, 0})
} else if !ok1 && ok2 {
binexps = append(binexps, binexp{op, "<addr>", sy.Name, 2, 0})
} else if ok1 && !ok2 {
binexps = append(binexps, binexp{op, sx.Name, "<addr>", 1, 0})
} else {
binexps = append(binexps, binexp{op, "<addr>", "<addr>", 0, 0})
}
}
return true
})
for i := 0; i < len(binexps); i++ {
binexps[i].index = i
}
label, last := 0, -1
var ops, args []binexp
var labels []string
for i, be := range binexps {
if be.kind == 0 {
ops = append(ops, be)
}
if be.kind != 3 {
continue
}
label++
ls := labelStr(label)
fmt.Printf(" %s = %s %s %s\n", ls, be.left, be.op, be.right)
for j := i - 1; j > last; j-- {
be2 := binexps[j]
if be2.kind == 2 {
label++
ls2 := labelStr(label)
fmt.Printf(" %s = %s %s %s\n", ls2, ls, be2.op, be2.right)
ls = ls2
be = be2
} else if be2.kind == 1 {
label++
ls2 := labelStr(label)
fmt.Printf(" %s = %s %s %s\n", ls2, be2.left, be2.op, ls)
ls = ls2
be = be2
}
}
args = append(args, be)
labels = append(labels, ls)
lea, leo := len(args), len(ops)
for lea >= 2 {
if i < len(binexps)-1 && args[lea-2].index <= ops[leo-1].index {
break
}
label++
ls2 := labelStr(label)
fmt.Printf(" %s = %s %s %s\n", ls2, labels[lea-2], ops[leo-1].op, labels[lea-1])
ops = ops[0 : leo-1]
args = args[0 : lea-1]
labels = labels[0 : lea-1]
lea--
leo--
args[lea-1] = be
labels[lea-1] = ls2
}
last = i
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include<iostream>
#include<string>
#include<boost/filesystem.hpp>
#include<boost/format.hpp>
#include<boost/iostreams/device/mapped_file.hpp>
#include<optional>
#include<algorithm>
#include<iterator>
#include<execution>
#include"dependencies/xxhash.hpp"
template<typename T, typename V, typename F>
size_t for_each_adjacent_range(T begin, T end, V getvalue, F callback) {
size_t partitions = 0;
while (begin != end) {
auto const& value = getvalue(*begin);
auto current = begin;
while (++current != end && getvalue(*current) == value);
callback(begin, current, value);
++partitions;
begin = current;
}
return partitions;
}
namespace bi = boost::iostreams;
namespace fs = boost::filesystem;
struct file_entry {
public:
explicit file_entry(fs::directory_entry const & entry)
: path_{entry.path()}, size_{fs::file_size(entry)}
{}
auto size() const { return size_; }
auto const& path() const { return path_; }
auto get_hash() {
if (!hash_)
hash_ = compute_hash();
return *hash_;
}
private:
xxh::hash64_t compute_hash() {
bi::mapped_file_source source;
source.open<fs::wpath>(this->path());
if (!source.is_open()) {
std::cerr << "Cannot open " << path() << std::endl;
throw std::runtime_error("Cannot open file");
}
xxh::hash_state64_t hash_stream;
hash_stream.update(source.data(), size_);
return hash_stream.digest();
}
private:
fs::wpath path_;
uintmax_t size_;
std::optional<xxh::hash64_t> hash_;
};
using vector_type = std::vector<file_entry>;
using iterator_type = vector_type::iterator;
auto find_files_in_dir(fs::wpath const& path, vector_type& file_vector, uintmax_t min_size = 1) {
size_t found = 0, ignored = 0;
if (!fs::is_directory(path)) {
std::cerr << path << " is not a directory!" << std::endl;
}
else {
std::cerr << "Searching " << path << std::endl;
for (auto& e : fs::recursive_directory_iterator(path)) {
++found;
if (fs::is_regular_file(e) && fs::file_size(e) >= min_size)
file_vector.emplace_back(e);
else ++ignored;
}
}
return std::make_tuple(found, ignored);
}
int main(int argn, char* argv[])
{
vector_type files;
for (auto i = 1; i < argn; ++i) {
fs::wpath path(argv[i]);
auto [found, ignored] = find_files_in_dir(path, files);
std::cerr << boost::format{
" %1$6d files found\n"
" %2$6d files ignored\n"
" %3$6d files added\n" } % found % ignored % (found - ignored)
<< std::endl;
}
std::cerr << "Found " << files.size() << " regular files" << std::endl;
std::sort(std::execution::par_unseq, files.begin(), files.end()
, [](auto const& a, auto const& b) { return a.size() > b.size(); }
);
for_each_adjacent_range(
std::begin(files)
, std::end(files)
, [](vector_type::value_type const& f) { return f.size(); }
, [](auto start, auto end, auto file_size) {
size_t nr_of_files = std::distance(start, end);
if (nr_of_files > 1) {
std::sort(start, end, [](auto& a, auto& b) {
auto const& ha = a.get_hash();
auto const& hb = b.get_hash();
auto const& pa = a.path();
auto const& pb = b.path();
return std::tie(ha, pa) < std::tie(hb, pb);
});
for_each_adjacent_range(
start
, end
, [](vector_type::value_type& f) { return f.get_hash(); }
, [file_size](auto hstart, auto hend, auto hash) {
size_t hnr_of_files = std::distance(hstart, hend);
if (hnr_of_files > 1) {
std::cout << boost::format{ "%1$3d files with hash %3$016x and size %2$d\n" }
% hnr_of_files % file_size % hash;
std::for_each(hstart, hend, [hash, file_size](auto& e) {
std::cout << '\t' << e.path() << '\n';
}
);
}
}
);
}
}
);
return 0;
}
| package main
import (
"fmt"
"crypto/md5"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"time"
)
type fileData struct {
filePath string
info os.FileInfo
}
type hash [16]byte
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func checksum(filePath string) hash {
bytes, err := ioutil.ReadFile(filePath)
check(err)
return hash(md5.Sum(bytes))
}
func findDuplicates(dirPath string, minSize int64) [][2]fileData {
var dups [][2]fileData
m := make(map[hash]fileData)
werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && info.Size() >= minSize {
h := checksum(path)
fd, ok := m[h]
fd2 := fileData{path, info}
if !ok {
m[h] = fd2
} else {
dups = append(dups, [2]fileData{fd, fd2})
}
}
return nil
})
check(werr)
return dups
}
func main() {
dups := findDuplicates(".", 1)
fmt.Println("The following pairs of files have the same size and the same hash:\n")
fmt.Println("File name Size Date last modified")
fmt.Println("==========================================================")
sort.Slice(dups, func(i, j int) bool {
return dups[i][0].info.Size() > dups[j][0].info.Size()
})
for _, dup := range dups {
for i := 0; i < 2; i++ {
d := dup[i]
fmt.Printf("%-20s %8d %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))
}
fmt.Println()
}
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <iostream>
#include <vector>
std::vector<bool> prime_sieve(size_t limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (size_t i = 4; i < limit; i += 2)
sieve[i] = false;
for (size_t p = 3; ; p += 2) {
size_t q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
size_t inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
bool substring_prime(const std::vector<bool>& sieve, unsigned int n) {
for (; n != 0; n /= 10) {
if (!sieve[n])
return false;
for (unsigned int p = 10; p < n; p *= 10) {
if (!sieve[n % p])
return false;
}
}
return true;
}
int main() {
const unsigned int limit = 500;
std::vector<bool> sieve = prime_sieve(limit);
for (unsigned int i = 2; i < limit; ++i) {
if (substring_prime(sieve, i))
std::cout << i << '\n';
}
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(499)
var sprimes []int
for _, p := range primes {
digits := rcu.Digits(p, 10)
var b1 = true
for _, d := range digits {
if !rcu.IsPrime(d) {
b1 = false
break
}
}
if b1 {
if len(digits) < 3 {
sprimes = append(sprimes, p)
} else {
b2 := rcu.IsPrime(digits[0]*10 + digits[1])
b3 := rcu.IsPrime(digits[1]*10 + digits[2])
if b2 && b3 {
sprimes = append(sprimes, p)
}
}
}
}
fmt.Println("Found", len(sprimes), "primes < 500 where all substrings are also primes, namely:")
fmt.Println(sprimes)
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <iostream>
#include <vector>
std::vector<bool> prime_sieve(size_t limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (size_t i = 4; i < limit; i += 2)
sieve[i] = false;
for (size_t p = 3; ; p += 2) {
size_t q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
size_t inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
bool substring_prime(const std::vector<bool>& sieve, unsigned int n) {
for (; n != 0; n /= 10) {
if (!sieve[n])
return false;
for (unsigned int p = 10; p < n; p *= 10) {
if (!sieve[n % p])
return false;
}
}
return true;
}
int main() {
const unsigned int limit = 500;
std::vector<bool> sieve = prime_sieve(limit);
for (unsigned int i = 2; i < limit; ++i) {
if (substring_prime(sieve, i))
std::cout << i << '\n';
}
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(499)
var sprimes []int
for _, p := range primes {
digits := rcu.Digits(p, 10)
var b1 = true
for _, d := range digits {
if !rcu.IsPrime(d) {
b1 = false
break
}
}
if b1 {
if len(digits) < 3 {
sprimes = append(sprimes, p)
} else {
b2 := rcu.IsPrime(digits[0]*10 + digits[1])
b3 := rcu.IsPrime(digits[1]*10 + digits[2])
if b2 && b3 {
sprimes = append(sprimes, p)
}
}
}
}
fmt.Println("Found", len(sprimes), "primes < 500 where all substrings are also primes, namely:")
fmt.Println(sprimes)
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
using integer = boost::multiprecision::cpp_int;
using rational = boost::rational<integer>;
integer sylvester_next(const integer& n) {
return n * n - n + 1;
}
int main() {
std::cout << "First 10 elements in Sylvester's sequence:\n";
integer term = 2;
rational sum = 0;
for (int i = 1; i <= 10; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
sum += rational(1, term);
term = sylvester_next(term);
}
std::cout << "Sum of reciprocals: " << sum << '\n';
}
| package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
two := big.NewInt(2)
next := new(big.Int)
sylvester := []*big.Int{two}
prod := new(big.Int).Set(two)
count := 1
for count < 10 {
next.Add(prod, one)
sylvester = append(sylvester, new(big.Int).Set(next))
count++
prod.Mul(prod, next)
}
fmt.Println("The first 10 terms in the Sylvester sequence are:")
for i := 0; i < 10; i++ {
fmt.Println(sylvester[i])
}
sumRecip := new(big.Rat)
for _, s := range sylvester {
sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))
}
fmt.Println("\nThe sum of their reciprocals as a rational number is:")
fmt.Println(sumRecip)
fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
fmt.Println(sumRecip.FloatString(211))
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2;
dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2;
dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1;
dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << 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 + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
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 ) c |= ( 1 << xx );
}
return c;
}
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 );
}
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;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13;
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( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct node
{
int val;
unsigned char neighbors;
};
class nSolver
{
public:
nSolver()
{
dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2;
dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2;
dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1;
dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = len;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
}
private:
bool search( int x, int y, int w )
{
if( w > max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << 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 + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int a, b;
for( int xx = 0; xx < 8; xx++ )
{
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 ) c |= ( 1 << xx );
}
return c;
}
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 );
}
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;
}
}
int wid, hei, max, dx[8], dy[8];
node* arr;
};
int main( int argc, char* argv[] )
{
int wid; string p;
p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13;
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( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
| package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
template <typename T>
void print(const std::vector<T> v) {
std::cout << "{ ";
for (const auto& e : v) {
std::cout << e << " ";
}
std::cout << "}";
}
template <typename T>
auto orderDisjointArrayItems(std::vector<T> M, std::vector<T> N) {
std::vector<T*> M_p(std::size(M));
for (auto i = 0; i < std::size(M_p); ++i) {
M_p[i] = &M[i];
}
for (auto e : N) {
auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool {
if (c != nullptr) {
if (*c == e) return true;
}
return false;
});
if (i != std::end(M_p)) {
*i = nullptr;
}
}
for (auto i = 0; i < std::size(N); ++i) {
auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool {
return c == nullptr;
});
if (j != std::end(M_p)) {
*j = &M[std::distance(std::begin(M_p), j)];
**j = N[i];
}
}
return M;
}
int main() {
std::vector<std::vector<std::vector<std::string>>> l = {
{ { "the", "cat", "sat", "on", "the", "mat" }, { "mat", "cat" } },
{ { "the", "cat", "sat", "on", "the", "mat" },{ "cat", "mat" } },
{ { "A", "B", "C", "A", "B", "C", "A", "B", "C" },{ "C", "A", "C", "A" } },
{ { "A", "B", "C", "A", "B", "D", "A", "B", "E" },{ "E", "A", "D", "A" } },
{ { "A", "B" },{ "B" } },
{ { "A", "B" },{ "B", "A" } },
{ { "A", "B", "B", "A" },{ "B", "A" } }
};
for (const auto& e : l) {
std::cout << "M: ";
print(e[0]);
std::cout << ", N: ";
print(e[1]);
std::cout << ", M': ";
auto res = orderDisjointArrayItems<std::string>(e[0], e[1]);
print(res);
std::cout << std::endl;
}
std::cin.ignore();
std::cin.get();
return 0;
}
| package main
import (
"fmt"
"sort"
"strings"
)
type indexSort struct {
val sort.Interface
ind []int
}
func (s indexSort) Len() int { return len(s.ind) }
func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }
func (s indexSort) Swap(i, j int) {
s.val.Swap(s.ind[i], s.ind[j])
s.ind[i], s.ind[j] = s.ind[j], s.ind[i]
}
func disjointSliceSort(m, n []string) []string {
s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}
used := make(map[int]bool)
for _, nw := range n {
for i, mw := range m {
if used[i] || mw != nw {
continue
}
used[i] = true
s.ind = append(s.ind, i)
break
}
}
sort.Sort(s)
return s.val.(sort.StringSlice)
}
func disjointStringSort(m, n string) string {
return strings.Join(
disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ")
}
func main() {
for _, data := range []struct{ m, n string }{
{"the cat sat on the mat", "mat cat"},
{"the cat sat on the mat", "cat mat"},
{"A B C A B C A B C", "C A C A"},
{"A B C A B D A B E", "E A D A"},
{"A B", "B"},
{"A B", "B A"},
{"A B B A", "B A"},
} {
mp := disjointStringSort(data.m, data.n)
fmt.Printf("%s → %s » %s\n", data.m, data.n, mp)
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| var m = ` leading spaces
and blank lines`
|
Generate an equivalent Go version of this C++ code. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| var m = ` leading spaces
and blank lines`
|
Produce a functionally identical Go code for the snippet given in C++. | #include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {
{"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};
tab_t tab2 {
{"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};
std::ostream& operator<<(std::ostream& o, const tab_t& t) {
for(size_t i = 0; i < t.size(); ++i) {
o << i << ":";
for(const auto& e : t[i])
o << '\t' << e;
o << std::endl;
}
return o;
}
tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
std::unordered_multimap<std::string, size_t> hashmap;
for(size_t i = 0; i < a.size(); ++i) {
hashmap.insert(std::make_pair(a[i][columna], i));
}
tab_t result;
for(size_t i = 0; i < b.size(); ++i) {
auto range = hashmap.equal_range(b[i][columnb]);
for(auto it = range.first; it != range.second; ++it) {
tab_t::value_type row;
row.insert(row.end() , a[it->second].begin() , a[it->second].end());
row.insert(row.end() , b[i].begin() , b[i].end());
result.push_back(std::move(row));
}
}
return result;
}
int main(int argc, char const *argv[])
{
using namespace std;
int ret = 0;
cout << "Table A: " << endl << tab1 << endl;
cout << "Table B: " << endl << tab2 << endl;
auto tab3 = Join(tab1, 1, tab2, 0);
cout << "Joined tables: " << endl << tab3 << endl;
return ret;
}
| package main
import "fmt"
func main() {
tableA := []struct {
value int
key string
}{
{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
{28, "Alan"},
}
tableB := []struct {
key string
value string
}{
{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
}
h := map[string][]int{}
for i, r := range tableA {
h[r.key] = append(h[r.key], i)
}
for _, x := range tableB {
for _, a := range h[x.key] {
fmt.Println(tableA[a], x)
}
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_counter(int limit) : count_(limit, 1) {
if (limit > 0)
count_[0] = 0;
if (limit > 1)
count_[1] = 0;
for (int i = 4; i < limit; i += 2)
count_[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count_[p]) {
for (int q = sq; q < limit; q += p << 1)
count_[q] = 0;
}
sq += (p + 1) << 2;
}
std::partial_sum(count_.begin(), count_.end(), count_.begin());
}
int ramanujan_max(int n) {
return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}
int ramanujan_prime(const prime_counter& pc, int n) {
int max = ramanujan_max(n);
for (int i = max; i >= 0; --i) {
if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
return i + 1;
}
return 0;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
prime_counter pc(1 + ramanujan_max(100000));
for (int i = 1; i <= 100; ++i) {
std::cout << std::setw(5) << ramanujan_prime(pc, i)
<< (i % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (int n = 1000; n <= 100000; n *= 10) {
std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
<< ".\n";
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\nElapsed time: "
<< std::chrono::duration<double>(end - start).count() * 1000
<< " milliseconds\n";
}
| package main
import (
"fmt"
"math"
"rcu"
"time"
)
var count []int
func primeCounter(limit int) {
count = make([]int, limit)
for i := 0; i < limit; i++ {
count[i] = 1
}
if limit > 0 {
count[0] = 0
}
if limit > 1 {
count[1] = 0
}
for i := 4; i < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
|
Generate an equivalent Go version of this C++ code. | #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_counter(int limit) : count_(limit, 1) {
if (limit > 0)
count_[0] = 0;
if (limit > 1)
count_[1] = 0;
for (int i = 4; i < limit; i += 2)
count_[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count_[p]) {
for (int q = sq; q < limit; q += p << 1)
count_[q] = 0;
}
sq += (p + 1) << 2;
}
std::partial_sum(count_.begin(), count_.end(), count_.begin());
}
int ramanujan_max(int n) {
return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}
int ramanujan_prime(const prime_counter& pc, int n) {
int max = ramanujan_max(n);
for (int i = max; i >= 0; --i) {
if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
return i + 1;
}
return 0;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
prime_counter pc(1 + ramanujan_max(100000));
for (int i = 1; i <= 100; ++i) {
std::cout << std::setw(5) << ramanujan_prime(pc, i)
<< (i % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (int n = 1000; n <= 100000; n *= 10) {
std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
<< ".\n";
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\nElapsed time: "
<< std::chrono::duration<double>(end - start).count() * 1000
<< " milliseconds\n";
}
| package main
import (
"fmt"
"math"
"rcu"
"time"
)
var count []int
func primeCounter(limit int) {
count = make([]int, limit)
for i := 0; i < limit; i++ {
count[i] = 1
}
if limit > 0 {
count[0] = 0
}
if limit > 1 {
count[1] = 0
}
for i := 4; i < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_counter(int limit) : count_(limit, 1) {
if (limit > 0)
count_[0] = 0;
if (limit > 1)
count_[1] = 0;
for (int i = 4; i < limit; i += 2)
count_[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count_[p]) {
for (int q = sq; q < limit; q += p << 1)
count_[q] = 0;
}
sq += (p + 1) << 2;
}
std::partial_sum(count_.begin(), count_.end(), count_.begin());
}
int ramanujan_max(int n) {
return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}
int ramanujan_prime(const prime_counter& pc, int n) {
int max = ramanujan_max(n);
for (int i = max; i >= 0; --i) {
if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
return i + 1;
}
return 0;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
prime_counter pc(1 + ramanujan_max(100000));
for (int i = 1; i <= 100; ++i) {
std::cout << std::setw(5) << ramanujan_prime(pc, i)
<< (i % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (int n = 1000; n <= 100000; n *= 10) {
std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
<< ".\n";
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\nElapsed time: "
<< std::chrono::duration<double>(end - start).count() * 1000
<< " milliseconds\n";
}
| package main
import (
"fmt"
"math"
"rcu"
"time"
)
var count []int
func primeCounter(limit int) {
count = make([]int, limit)
for i := 0; i < limit; i++ {
count[i] = 1
}
if limit > 0 {
count[0] = 0
}
if limit > 1 {
count[1] = 0
}
for i := 4; i < limit; i += 2 {
count[i] = 0
}
for p, sq := 3, 9; sq < limit; p += 2 {
if count[p] != 0 {
for q := sq; q < limit; q += p << 1 {
count[q] = 0
}
}
sq += (p + 1) << 2
}
sum := 0
for i := 0; i < limit; i++ {
sum += count[i]
count[i] = sum
}
}
func primeCount(n int) int {
if n < 1 {
return 0
}
return count[n]
}
func ramanujanMax(n int) int {
fn := float64(n)
return int(math.Ceil(4 * fn * math.Log(4*fn)))
}
func ramanujanPrime(n int) int {
if n == 1 {
return 2
}
for i := ramanujanMax(n); i >= 2*n; i-- {
if i%2 == 1 {
continue
}
if primeCount(i)-primeCount(i/2) < n {
return i + 1
}
}
return 0
}
func main() {
start := time.Now()
primeCounter(1 + ramanujanMax(1e6))
fmt.Println("The first 100 Ramanujan primes are:")
rams := make([]int, 100)
for n := 0; n < 100; n++ {
rams[n] = ramanujanPrime(n + 1)
}
for i, r := range rams {
fmt.Printf("%5s ", rcu.Commatize(r))
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe 1,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(1000)))
fmt.Printf("\nThe 10,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(10000)))
fmt.Printf("\nThe 100,000th Ramanujan prime is %6s\n", rcu.Commatize(ramanujanPrime(100000)))
fmt.Printf("\nThe 1,000,000th Ramanujan prime is %7s\n", rcu.Commatize(ramanujanPrime(1000000)))
fmt.Println("\nTook", time.Since(start))
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
}
auto perfect_powers(uint128_t n) {
std::vector<uint128_t> result;
for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)
for (uint128_t p = i * i; p < n; p *= i)
result.push_back(p);
unique_sort(result);
return result;
}
auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {
std::vector<uint128_t> result;
auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));
auto s = sqrt(to / 8);
for (uint128_t b = 2; b <= c; ++b) {
uint128_t b3 = b * b * b;
for (uint128_t a = 2; a <= s; ++a) {
uint128_t p = b3 * a * a;
if (p >= to)
break;
if (p >= from && !binary_search(pps.begin(), pps.end(), p))
result.push_back(p);
}
}
unique_sort(result);
return result;
}
uint128_t totient(uint128_t n) {
uint128_t tot = n;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
tot -= tot >> 1;
}
for (uint128_t p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
tot -= tot / p;
}
}
if (n > 1)
tot -= tot / n;
return tot;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
const uint128_t limit = 1000000000000000;
auto pps = perfect_powers(limit);
auto ach = achilles(1, 1000000, pps);
std::cout << "First 50 Achilles numbers:\n";
for (size_t i = 0; i < 50 && i < ach.size(); ++i)
std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' ');
std::cout << "\nFirst 50 strong Achilles numbers:\n";
for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)
if (binary_search(ach.begin(), ach.end(), totient(ach[i])))
std::cout << std::setw(6) << ach[i]
<< (++count % 10 == 0 ? '\n' : ' ');
int digits = 2;
std::cout << "\nNumber of Achilles numbers with:\n";
for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {
size_t count = achilles(from, to, pps).size();
std::cout << std::setw(2) << digits << " digits: " << count << '\n';
from = to;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector.end());
vector.erase(std::unique(vector.begin(), vector.end()), vector.end());
}
auto perfect_powers(uint128_t n) {
std::vector<uint128_t> result;
for (uint128_t i = 2, s = sqrt(n); i <= s; ++i)
for (uint128_t p = i * i; p < n; p *= i)
result.push_back(p);
unique_sort(result);
return result;
}
auto achilles(uint128_t from, uint128_t to, const std::vector<uint128_t>& pps) {
std::vector<uint128_t> result;
auto c = static_cast<uint128_t>(std::cbrt(static_cast<double>(to / 4)));
auto s = sqrt(to / 8);
for (uint128_t b = 2; b <= c; ++b) {
uint128_t b3 = b * b * b;
for (uint128_t a = 2; a <= s; ++a) {
uint128_t p = b3 * a * a;
if (p >= to)
break;
if (p >= from && !binary_search(pps.begin(), pps.end(), p))
result.push_back(p);
}
}
unique_sort(result);
return result;
}
uint128_t totient(uint128_t n) {
uint128_t tot = n;
if ((n & 1) == 0) {
while ((n & 1) == 0)
n >>= 1;
tot -= tot >> 1;
}
for (uint128_t p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
tot -= tot / p;
}
}
if (n > 1)
tot -= tot / n;
return tot;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
const uint128_t limit = 1000000000000000;
auto pps = perfect_powers(limit);
auto ach = achilles(1, 1000000, pps);
std::cout << "First 50 Achilles numbers:\n";
for (size_t i = 0; i < 50 && i < ach.size(); ++i)
std::cout << std::setw(4) << ach[i] << ((i + 1) % 10 == 0 ? '\n' : ' ');
std::cout << "\nFirst 50 strong Achilles numbers:\n";
for (size_t i = 0, count = 0; count < 50 && i < ach.size(); ++i)
if (binary_search(ach.begin(), ach.end(), totient(ach[i])))
std::cout << std::setw(6) << ach[i]
<< (++count % 10 == 0 ? '\n' : ' ');
int digits = 2;
std::cout << "\nNumber of Achilles numbers with:\n";
for (uint128_t from = 1, to = 100; to <= limit; to *= 10, ++digits) {
size_t count = achilles(from, to, pps).size();
std::cout << std::setw(2) << digits << " digits: " << count << '\n';
from = to;
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iomanip>
#include <iostream>
bool odd_square_free_semiprime(int n) {
if ((n & 1) == 0)
return false;
int count = 0;
for (int i = 3; i * i <= n; i += 2) {
for (; n % i == 0; n /= i) {
if (++count > 1)
return false;
}
}
return count == 1;
}
int main() {
const int n = 1000;
std::cout << "Odd square-free semiprimes < " << n << ":\n";
int count = 0;
for (int i = 1; i < n; i += 2) {
if (odd_square_free_semiprime(i)) {
++count;
std::cout << std::setw(4) << i;
if (count % 20 == 0)
std::cout << '\n';
}
}
std::cout << "\nCount: " << count << '\n';
return 0;
}
| package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
primes := rcu.Primes(333)
var oss []int
for i := 1; i < len(primes)-1; i++ {
for j := i + 1; j < len(primes); j++ {
n := primes[i] * primes[j]
if n >= 1000 {
break
}
oss = append(oss, n)
}
}
sort.Ints(oss)
fmt.Println("Odd squarefree semiprimes under 1,000:")
for i, n := range oss {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found.\n", len(oss))
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <iomanip>
#include <iostream>
bool odd_square_free_semiprime(int n) {
if ((n & 1) == 0)
return false;
int count = 0;
for (int i = 3; i * i <= n; i += 2) {
for (; n % i == 0; n /= i) {
if (++count > 1)
return false;
}
}
return count == 1;
}
int main() {
const int n = 1000;
std::cout << "Odd square-free semiprimes < " << n << ":\n";
int count = 0;
for (int i = 1; i < n; i += 2) {
if (odd_square_free_semiprime(i)) {
++count;
std::cout << std::setw(4) << i;
if (count % 20 == 0)
std::cout << '\n';
}
}
std::cout << "\nCount: " << count << '\n';
return 0;
}
| package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
primes := rcu.Primes(333)
var oss []int
for i := 1; i < len(primes)-1; i++ {
for j := i + 1; j < len(primes); j++ {
n := primes[i] * primes[j]
if n >= 1000 {
break
}
oss = append(oss, n)
}
}
sort.Ints(oss)
fmt.Println("Odd squarefree semiprimes under 1,000:")
for i, n := range oss {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found.\n", len(oss))
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length/std::sqrt(2.0);
y_ = 2 * x_;
angle_ = 45;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F--XF--F--XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF+G+XF--F--XF+G+X";
else
t += c;
}
return t;
}
void sierpinski_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ -= length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
case 'G':
line(out);
break;
case '+':
angle_ = (angle_ + 45) % 360;
break;
case '-':
angle_ = (angle_ - 45) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_curve s;
s.write(out, 545, 7, 5);
return 0;
}
| package main
import (
"github.com/fogleman/gg"
"math"
)
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h float64
func lineTo(newX, newY float64) {
dc.LineTo(newX-width/2+h, height-newY+2*h)
cx, cy = newX, newY
}
func lineN() { lineTo(cx, cy-2*h) }
func lineS() { lineTo(cx, cy+2*h) }
func lineE() { lineTo(cx+2*h, cy) }
func lineW() { lineTo(cx-2*h, cy) }
func lineNW() { lineTo(cx-h, cy-h) }
func lineNE() { lineTo(cx+h, cy-h) }
func lineSE() { lineTo(cx+h, cy+h) }
func lineSW() { lineTo(cx-h, cy+h) }
func sierN(level int) {
if level == 1 {
lineNE()
lineN()
lineNW()
} else {
sierN(level - 1)
lineNE()
sierE(level - 1)
lineN()
sierW(level - 1)
lineNW()
sierN(level - 1)
}
}
func sierE(level int) {
if level == 1 {
lineSE()
lineE()
lineNE()
} else {
sierE(level - 1)
lineSE()
sierS(level - 1)
lineE()
sierN(level - 1)
lineNE()
sierE(level - 1)
}
}
func sierS(level int) {
if level == 1 {
lineSW()
lineS()
lineSE()
} else {
sierS(level - 1)
lineSW()
sierW(level - 1)
lineS()
sierE(level - 1)
lineSE()
sierS(level - 1)
}
}
func sierW(level int) {
if level == 1 {
lineNW()
lineW()
lineSW()
} else {
sierW(level - 1)
lineNW()
sierN(level - 1)
lineW()
sierS(level - 1)
lineSW()
sierW(level - 1)
}
}
func squareCurve(level int) {
sierN(level)
lineNE()
sierE(level)
lineSE()
sierS(level)
lineSW()
sierW(level)
lineNW()
lineNE()
}
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
level := 5
cx, cy = width/2, height
h = cx / math.Pow(2, float64(level+1))
squareCurve(level)
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_curve.png")
}
|
Translate the given C++ code snippet into Go without altering its behavior. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length/std::sqrt(2.0);
y_ = 2 * x_;
angle_ = 45;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F--XF--F--XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF+G+XF--F--XF+G+X";
else
t += c;
}
return t;
}
void sierpinski_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ -= length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
case 'G':
line(out);
break;
case '+':
angle_ = (angle_ + 45) % 360;
break;
case '-':
angle_ = (angle_ - 45) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_curve s;
s.write(out, 545, 7, 5);
return 0;
}
| package main
import (
"github.com/fogleman/gg"
"math"
)
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h float64
func lineTo(newX, newY float64) {
dc.LineTo(newX-width/2+h, height-newY+2*h)
cx, cy = newX, newY
}
func lineN() { lineTo(cx, cy-2*h) }
func lineS() { lineTo(cx, cy+2*h) }
func lineE() { lineTo(cx+2*h, cy) }
func lineW() { lineTo(cx-2*h, cy) }
func lineNW() { lineTo(cx-h, cy-h) }
func lineNE() { lineTo(cx+h, cy-h) }
func lineSE() { lineTo(cx+h, cy+h) }
func lineSW() { lineTo(cx-h, cy+h) }
func sierN(level int) {
if level == 1 {
lineNE()
lineN()
lineNW()
} else {
sierN(level - 1)
lineNE()
sierE(level - 1)
lineN()
sierW(level - 1)
lineNW()
sierN(level - 1)
}
}
func sierE(level int) {
if level == 1 {
lineSE()
lineE()
lineNE()
} else {
sierE(level - 1)
lineSE()
sierS(level - 1)
lineE()
sierN(level - 1)
lineNE()
sierE(level - 1)
}
}
func sierS(level int) {
if level == 1 {
lineSW()
lineS()
lineSE()
} else {
sierS(level - 1)
lineSW()
sierW(level - 1)
lineS()
sierE(level - 1)
lineSE()
sierS(level - 1)
}
}
func sierW(level int) {
if level == 1 {
lineNW()
lineW()
lineSW()
} else {
sierW(level - 1)
lineNW()
sierN(level - 1)
lineW()
sierS(level - 1)
lineSW()
sierW(level - 1)
}
}
func squareCurve(level int) {
sierN(level)
lineNE()
sierE(level)
lineSE()
sierS(level)
lineSW()
sierW(level)
lineNW()
lineNE()
}
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
level := 5
cx, cy = width/2, height
h = cx / math.Pow(2, float64(level+1))
squareCurve(level)
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_curve.png")
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include <utility>
#include <sstream>
std::string mostFreqKHashing ( const std::string & input , int k ) {
std::ostringstream oss ;
std::map<char, int> frequencies ;
for ( char c : input ) {
frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;
}
std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;
std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,
std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ;
int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }
else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;
for ( int i = 0 ; i < letters.size( ) ; i++ ) {
oss << std::get<0>( letters[ i ] ) ;
oss << std::get<1>( letters[ i ] ) ;
}
std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;
if ( letters.size( ) >= k ) {
return output ;
}
else {
return output.append( "NULL0" ) ;
}
}
int mostFreqKSimilarity ( const std::string & first , const std::string & second ) {
int i = 0 ;
while ( i < first.length( ) - 1 ) {
auto found = second.find_first_of( first.substr( i , 2 ) ) ;
if ( found != std::string::npos )
return std::stoi ( first.substr( i , 2 )) ;
else
i += 2 ;
}
return 0 ;
}
int mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {
return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;
}
int main( ) {
std::string s1("LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" ) ;
std::string s2( "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" ) ;
std::cout << "MostFreqKHashing( s1 , 2 ) = " << mostFreqKHashing( s1 , 2 ) << '\n' ;
std::cout << "MostFreqKHashing( s2 , 2 ) = " << mostFreqKHashing( s2 , 2 ) << '\n' ;
return 0 ;
}
| package main
import (
"fmt"
"sort"
)
type cf struct {
c rune
f int
}
func reverseStr(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func indexOfCf(cfs []cf, r rune) int {
for i, cf := range cfs {
if cf.c == r {
return i
}
}
return -1
}
func minOf(i, j int) int {
if i < j {
return i
}
return j
}
func mostFreqKHashing(input string, k int) string {
var cfs []cf
for _, r := range input {
ix := indexOfCf(cfs, r)
if ix >= 0 {
cfs[ix].f++
} else {
cfs = append(cfs, cf{r, 1})
}
}
sort.SliceStable(cfs, func(i, j int) bool {
return cfs[i].f > cfs[j].f
})
acc := ""
min := minOf(len(cfs), k)
for _, cf := range cfs[:min] {
acc += fmt.Sprintf("%c%c", cf.c, cf.f)
}
return acc
}
func mostFreqKSimilarity(input1, input2 string) int {
similarity := 0
runes1, runes2 := []rune(input1), []rune(input2)
for i := 0; i < len(runes1); i += 2 {
for j := 0; j < len(runes2); j += 2 {
if runes1[i] == runes2[j] {
freq1, freq2 := runes1[i+1], runes2[j+1]
if freq1 != freq2 {
continue
}
similarity += int(freq1)
}
}
}
return similarity
}
func mostFreqKSDF(input1, input2 string, k, maxDistance int) {
fmt.Println("input1 :", input1)
fmt.Println("input2 :", input2)
s1 := mostFreqKHashing(input1, k)
s2 := mostFreqKHashing(input2, k)
fmt.Printf("mfkh(input1, %d) = ", k)
for i, c := range s1 {
if i%2 == 0 {
fmt.Printf("%c", c)
} else {
fmt.Printf("%d", c)
}
}
fmt.Printf("\nmfkh(input2, %d) = ", k)
for i, c := range s2 {
if i%2 == 0 {
fmt.Printf("%c", c)
} else {
fmt.Printf("%d", c)
}
}
result := maxDistance - mostFreqKSimilarity(s1, s2)
fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result)
}
func main() {
pairs := [][2]string{
{"research", "seeking"},
{"night", "nacht"},
{"my", "a"},
{"research", "research"},
{"aaaaabbbb", "ababababa"},
{"significant", "capabilities"},
}
for _, pair := range pairs {
mostFreqKSDF(pair[0], pair[1], 2, 10)
}
s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"
s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"
mostFreqKSDF(s1, s2, 2, 100)
s1 = "abracadabra12121212121abracadabra12121212121"
s2 = reverseStr(s1)
mostFreqKSDF(s1, s2, 2, 100)
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
unsigned int reverse(unsigned int base, unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= base)
rev = rev * base + (n % base);
return rev;
}
class palindrome_generator {
public:
explicit palindrome_generator(unsigned int base)
: base_(base), upper_(base) {}
unsigned int next_palindrome();
private:
unsigned int base_;
unsigned int lower_ = 1;
unsigned int upper_;
unsigned int next_ = 0;
bool even_ = false;
};
unsigned int palindrome_generator::next_palindrome() {
++next_;
if (next_ == upper_) {
if (even_) {
lower_ = upper_;
upper_ *= base_;
}
next_ = lower_;
even_ = !even_;
}
return even_ ? next_ * upper_ + reverse(base_, next_)
: next_ * lower_ + reverse(base_, next_ / base_);
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
std::string to_string(unsigned int base, unsigned int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
void print_palindromic_primes(unsigned int base, unsigned int limit) {
auto width =
static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));
unsigned int count = 0;
auto columns = 80 / (width + 1);
std::cout << "Base " << base << " palindromic primes less than " << limit
<< ":\n";
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit) {
if (is_prime(palindrome)) {
++count;
std::cout << std::setw(width) << to_string(base, palindrome)
<< (count % columns == 0 ? '\n' : ' ');
}
}
if (count % columns != 0)
std::cout << '\n';
std::cout << "Count: " << count << '\n';
}
void count_palindromic_primes(unsigned int base, unsigned int limit) {
unsigned int count = 0;
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit)
if (is_prime(palindrome))
++count;
std::cout << "Number of base " << base << " palindromic primes less than "
<< limit << ": " << count << '\n';
}
int main() {
print_palindromic_primes(10, 1000);
std::cout << '\n';
print_palindromic_primes(10, 100000);
std::cout << '\n';
count_palindromic_primes(10, 1000000000);
std::cout << '\n';
print_palindromic_primes(16, 500);
}
| package main
import (
"fmt"
"rcu"
)
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n /= 10
}
return rev
}
func main() {
primes := rcu.Primes(99999)
var pals []int
for _, p := range primes {
if p == reversed(p) {
pals = append(pals, p)
}
}
fmt.Println("Palindromic primes under 1,000:")
var smallPals, bigPals []int
for _, p := range pals {
if p < 1000 {
smallPals = append(smallPals, p)
} else {
bigPals = append(bigPals, p)
}
}
rcu.PrintTable(smallPals, 10, 3, false)
fmt.Println()
fmt.Println(len(smallPals), "such primes found.")
fmt.Println("\nAdditional palindromic primes under 100,000:")
rcu.PrintTable(bigPals, 10, 6, true)
fmt.Println()
fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.")
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
unsigned int reverse(unsigned int base, unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= base)
rev = rev * base + (n % base);
return rev;
}
class palindrome_generator {
public:
explicit palindrome_generator(unsigned int base)
: base_(base), upper_(base) {}
unsigned int next_palindrome();
private:
unsigned int base_;
unsigned int lower_ = 1;
unsigned int upper_;
unsigned int next_ = 0;
bool even_ = false;
};
unsigned int palindrome_generator::next_palindrome() {
++next_;
if (next_ == upper_) {
if (even_) {
lower_ = upper_;
upper_ *= base_;
}
next_ = lower_;
even_ = !even_;
}
return even_ ? next_ * upper_ + reverse(base_, next_)
: next_ * lower_ + reverse(base_, next_ / base_);
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
std::string to_string(unsigned int base, unsigned int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
void print_palindromic_primes(unsigned int base, unsigned int limit) {
auto width =
static_cast<unsigned int>(std::ceil(std::log(limit) / std::log(base)));
unsigned int count = 0;
auto columns = 80 / (width + 1);
std::cout << "Base " << base << " palindromic primes less than " << limit
<< ":\n";
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit) {
if (is_prime(palindrome)) {
++count;
std::cout << std::setw(width) << to_string(base, palindrome)
<< (count % columns == 0 ? '\n' : ' ');
}
}
if (count % columns != 0)
std::cout << '\n';
std::cout << "Count: " << count << '\n';
}
void count_palindromic_primes(unsigned int base, unsigned int limit) {
unsigned int count = 0;
palindrome_generator pgen(base);
unsigned int palindrome;
while ((palindrome = pgen.next_palindrome()) < limit)
if (is_prime(palindrome))
++count;
std::cout << "Number of base " << base << " palindromic primes less than "
<< limit << ": " << count << '\n';
}
int main() {
print_palindromic_primes(10, 1000);
std::cout << '\n';
print_palindromic_primes(10, 100000);
std::cout << '\n';
count_palindromic_primes(10, 1000000000);
std::cout << '\n';
print_palindromic_primes(16, 500);
}
| package main
import (
"fmt"
"rcu"
)
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n /= 10
}
return rev
}
func main() {
primes := rcu.Primes(99999)
var pals []int
for _, p := range primes {
if p == reversed(p) {
pals = append(pals, p)
}
}
fmt.Println("Palindromic primes under 1,000:")
var smallPals, bigPals []int
for _, p := range pals {
if p < 1000 {
smallPals = append(smallPals, p)
} else {
bigPals = append(bigPals, p)
}
}
rcu.PrintTable(smallPals, 10, 3, false)
fmt.Println()
fmt.Println(len(smallPals), "such primes found.")
fmt.Println("\nAdditional palindromic primes under 100,000:")
rcu.PrintTable(bigPals, 10, 6, true)
fmt.Println()
fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.")
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
bool contains_all_vowels_once(const std::string& word) {
std::bitset<5> vowels;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
size_t bit = 0;
switch (ch) {
case 'a': bit = 0; break;
case 'e': bit = 1; break;
case 'i': bit = 2; break;
case 'o': bit = 3; break;
case 'u': bit = 4; break;
default: continue;
}
if (vowels.test(bit))
return false;
vowels.set(bit);
}
return vowels.all();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
if (word.size() > 10 && contains_all_vowels_once(word))
std::cout << std::setw(2) << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 10 {
words = append(words, s)
}
}
count := 0
fmt.Println("Words which contain all 5 vowels once in", wordList, "\b:\n")
for _, word := range words {
ca, ce, ci, co, cu := 0, 0, 0, 0, 0
for _, r := range word {
switch r {
case 'a':
ca++
case 'e':
ce++
case 'i':
ci++
case 'o':
co++
case 'u':
cu++
}
}
if ca == 1 && ce == 1 && ci == 1 && co == 1 && cu == 1 {
count++
fmt.Printf("%2d: %s\n", count, word)
}
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int levenshtein_distance(const std::string& str1, const std::string& str2) {
size_t m = str1.size(), n = str2.size();
std::vector<int> cost(n + 1);
std::iota(cost.begin(), cost.end(), 0);
for (size_t i = 0; i < m; ++i) {
cost[0] = i + 1;
int prev = i;
for (size_t j = 0; j < n; ++j) {
int c = (str1[i] == str2[j]) ? prev
: 1 + std::min(std::min(cost[j + 1], cost[j]), prev);
prev = cost[j + 1];
cost[j + 1] = c;
}
}
return cost[n];
}
template <typename T>
void print_vector(const std::vector<T>& vec) {
auto i = vec.begin();
if (i == vec.end())
return;
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
}
int main(int argc, char** argv) {
if (argc != 3) {
std::cerr << "usage: " << argv[0] << " dictionary word\n";
return EXIT_FAILURE;
}
std::ifstream in(argv[1]);
if (!in) {
std::cerr << "Cannot open file " << argv[1] << '\n';
return EXIT_FAILURE;
}
std::string word(argv[2]);
if (word.empty()) {
std::cerr << "Word must not be empty\n";
return EXIT_FAILURE;
}
constexpr size_t max_dist = 4;
std::vector<std::string> matches[max_dist + 1];
std::string match;
while (getline(in, match)) {
int distance = levenshtein_distance(word, match);
if (distance <= max_dist)
matches[distance].push_back(match);
}
for (size_t dist = 0; dist <= max_dist; ++dist) {
if (matches[dist].empty())
continue;
std::cout << "Words at Levenshtein distance of " << dist
<< " (" << 100 - (100 * dist)/word.size()
<< "% similarity) from '" << word << "':\n";
print_vector(matches[dist]);
std::cout << "\n\n";
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
)
func levenshtein(s, t string) int {
d := make([][]int, len(s)+1)
for i := range d {
d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i
}
for j := range d[0] {
d[0][j] = j
}
for j := 1; j <= len(t); j++ {
for i := 1; i <= len(s); i++ {
if s[i-1] == t[j-1] {
d[i][j] = d[i-1][j-1]
} else {
min := d[i-1][j]
if d[i][j-1] < min {
min = d[i][j-1]
}
if d[i-1][j-1] < min {
min = d[i-1][j-1]
}
d[i][j] = min + 1
}
}
}
return d[len(s)][len(t)]
}
func main() {
search := "complition"
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
words := bytes.Fields(b)
var lev [4][]string
for _, word := range words {
s := string(word)
ld := levenshtein(search, s)
if ld < 4 {
lev[ld] = append(lev[ld], s)
}
}
fmt.Printf("Input word: %s\n\n", search)
for i := 1; i < 4; i++ {
length := float64(len(search))
similarity := (length - float64(i)) * 100 / length
fmt.Printf("Words which are %4.1f%% similar:\n", similarity)
fmt.Println(lev[i])
fmt.Println()
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <array>
#include <iostream>
#include <map>
#include <vector>
#include <primesieve.hpp>
using digit_set = std::array<int, 10>;
digit_set get_digits(uint64_t n) {
digit_set result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
int main() {
std::cout.imbue(std::locale(""));
primesieve::iterator pi;
using map_type =
std::map<digit_set, std::vector<uint64_t>, std::greater<digit_set>>;
map_type anaprimes;
for (uint64_t limit = 1000; limit <= 10000000000;) {
uint64_t prime = pi.next_prime();
if (prime > limit) {
size_t max_length = 0;
std::vector<map_type::iterator> groups;
for (auto i = anaprimes.begin(); i != anaprimes.end(); ++i) {
if (i->second.size() > max_length) {
groups.clear();
max_length = i->second.size();
}
if (max_length == i->second.size())
groups.push_back(i);
}
std::cout << "Largest group(s) of anaprimes before " << limit
<< ": " << max_length << " members:\n";
for (auto i : groups) {
std::cout << " First: " << i->second.front()
<< " Last: " << i->second.back() << '\n';
}
std::cout << '\n';
anaprimes.clear();
limit *= 10;
}
anaprimes[get_digits(prime)].push_back(prime);
}
}
| package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
const limit = int(1e10)
const maxIndex = 9
primes := rcu.Primes(limit)
anaprimes := make(map[int][]int)
for _, p := range primes {
digs := rcu.Digits(p, 10)
key := 1
for _, dig := range digs {
key *= primes[dig]
}
if _, ok := anaprimes[key]; ok {
anaprimes[key] = append(anaprimes[key], p)
} else {
anaprimes[key] = []int{p}
}
}
largest := make([]int, maxIndex+1)
groups := make([][][]int, maxIndex+1)
for key := range anaprimes {
v := anaprimes[key]
nd := len(rcu.Digits(v[0], 10))
c := len(v)
if c > largest[nd-1] {
largest[nd-1] = c
groups[nd-1] = [][]int{v}
} else if c == largest[nd-1] {
groups[nd-1] = append(groups[nd-1], v)
}
}
j := 1000
for i := 2; i <= maxIndex; i++ {
js := rcu.Commatize(j)
ls := rcu.Commatize(largest[i])
fmt.Printf("Largest group(s) of anaprimes before %s: %s members:\n", js, ls)
sort.Slice(groups[i], func(k, l int) bool {
return groups[i][k][0] < groups[i][l][0]
})
for _, g := range groups[i] {
fmt.Printf(" First: %s Last: %s\n", rcu.Commatize(g[0]), rcu.Commatize(g[len(g)-1]))
}
j *= 10
fmt.Println()
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <iostream>
#include <optional>
using namespace std;
class TropicalAlgebra
{
optional<double> m_value;
public:
friend std::ostream& operator<<(std::ostream&, const TropicalAlgebra&);
friend TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept;
TropicalAlgebra() = default;
explicit TropicalAlgebra(double value) noexcept
: m_value{value} {}
TropicalAlgebra& operator+=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
*this = rhs;
}
else if (!rhs.m_value)
{
}
else
{
*m_value = max(*rhs.m_value, *m_value);
}
return *this;
}
TropicalAlgebra& operator*=(const TropicalAlgebra& rhs) noexcept
{
if(!m_value)
{
}
else if (!rhs.m_value)
{
*this = rhs;
}
else
{
*m_value += *rhs.m_value;
}
return *this;
}
};
inline TropicalAlgebra operator+(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs += rhs;
return lhs;
}
inline TropicalAlgebra operator*(TropicalAlgebra lhs, const TropicalAlgebra& rhs) noexcept
{
lhs *= rhs;
return lhs;
}
inline TropicalAlgebra pow(const TropicalAlgebra& base, unsigned int exponent) noexcept
{
auto result = base;
for(unsigned int i = 1; i < exponent; i++)
{
result *= base;
}
return result;
}
ostream& operator<<(ostream& os, const TropicalAlgebra& pt)
{
if(!pt.m_value) cout << "-Inf\n";
else cout << *pt.m_value << "\n";
return os;
}
int main(void) {
const TropicalAlgebra a(-2);
const TropicalAlgebra b(-1);
const TropicalAlgebra c(-0.5);
const TropicalAlgebra d(-0.001);
const TropicalAlgebra e(0);
const TropicalAlgebra h(1.5);
const TropicalAlgebra i(2);
const TropicalAlgebra j(5);
const TropicalAlgebra k(7);
const TropicalAlgebra l(8);
const TropicalAlgebra m;
cout << "2 * -2 == " << i * a;
cout << "-0.001 + -Inf == " << d + m;
cout << "0 * -Inf == " << e * m;
cout << "1.5 + -1 == " << h + b;
cout << "-0.5 * 0 == " << c * e;
cout << "pow(5, 7) == " << pow(j, 7);
cout << "5 * (8 + 7)) == " << j * (l + k);
cout << "5 * 8 + 5 * 7 == " << j * l + j * k;
}
| package main
import (
"fmt"
"log"
"math"
)
var MinusInf = math.Inf(-1)
type MaxTropical struct{ r float64 }
func newMaxTropical(r float64) MaxTropical {
if math.IsInf(r, 1) || math.IsNaN(r) {
log.Fatal("Argument must be a real number or negative infinity.")
}
return MaxTropical{r}
}
func (t MaxTropical) eq(other MaxTropical) bool {
return t.r == other.r
}
func (t MaxTropical) add(other MaxTropical) MaxTropical {
if t.r == MinusInf {
return other
}
if other.r == MinusInf {
return t
}
return newMaxTropical(math.Max(t.r, other.r))
}
func (t MaxTropical) mul(other MaxTropical) MaxTropical {
if t.r == 0 {
return other
}
if other.r == 0 {
return t
}
return newMaxTropical(t.r + other.r)
}
func (t MaxTropical) pow(e int) MaxTropical {
if e < 1 {
log.Fatal("Exponent must be a positive integer.")
}
if e == 1 {
return t
}
p := t
for i := 2; i <= e; i++ {
p = p.mul(t)
}
return p
}
func (t MaxTropical) String() string {
return fmt.Sprintf("%g", t.r)
}
func main() {
data := [][]float64{
{2, -2, 1},
{-0.001, MinusInf, 0},
{0, MinusInf, 1},
{1.5, -1, 0},
{-0.5, 0, 1},
}
for _, d := range data {
a := newMaxTropical(d[0])
b := newMaxTropical(d[1])
if d[2] == 0 {
fmt.Printf("%s ⊕ %s = %s\n", a, b, a.add(b))
} else {
fmt.Printf("%s ⊗ %s = %s\n", a, b, a.mul(b))
}
}
c := newMaxTropical(5)
fmt.Printf("%s ^ 7 = %s\n", c, c.pow(7))
d := newMaxTropical(8)
e := newMaxTropical(7)
f := c.mul(d.add(e))
g := c.mul(d).add(c.mul(e))
fmt.Printf("%s ⊗ (%s ⊕ %s) = %s\n", c, d, e, f)
fmt.Printf("%s ⊗ %s ⊕ %s ⊗ %s = %s\n", c, d, c, e, g)
fmt.Printf("%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\n", c, d, e, c, d, c, e, f.eq(g))
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
| package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const (
gameOver = iota
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
|
Write a version of this C++ function in Go with identical behavior. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
| package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const (
gameOver = iota
piggedOut
rolls
pointSpending
holds
turn
gameOverSummary
player1 = PlayerID(0)
player2 = PlayerID(1)
noPlayer = PlayerID(-1)
maxScore = 100
scoreChaseStrat = iota
rollCountStrat
)
func pluralS(n int) string {
if n != 1 {
return "s"
}
return ""
}
func New() *PigGameData {
return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}
func (pg *PigGameData) statusMessage(id MessageID) string {
var msg string
switch id {
case gameOver:
msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
case piggedOut:
msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
case rolls:
msg = fmt.Sprintf(" Rolls %d", pg.lastRoll)
case pointSpending:
msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
case holds:
msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
case turn:
msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
case gameOverSummary:
msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
}
return msg
}
func (pg *PigGameData) PrintStatus(id MessageID) {
if pg.verbose {
fmt.Println(pg.statusMessage(id))
}
}
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
if pg.GameOver() {
pg.PrintStatus(gameOver)
return false
}
if pg.turnCount == 0 {
pg.player = player2
pg.NextPlayer()
}
pg.lastRoll = rand.Intn(6) + 1
pg.PrintStatus(rolls)
pg.turnRollCount++
if pg.lastRoll == 1 {
pg.PrintStatus(piggedOut)
pg.NextPlayer()
} else {
pg.turnScore += pg.lastRoll
pg.PrintStatus(pointSpending)
success := false
switch id {
case scoreChaseStrat:
success = pg.scoreChaseStrategy()
case rollCountStrat:
success = pg.rollCountStrategy()
}
if success {
pg.Hold()
pg.NextPlayer()
}
}
return true
}
func (pg *PigGameData) PlayerScore(id PlayerID) int {
if id == noPlayer {
return pg.scores[pg.player]
}
return pg.scores[id]
}
func (pg *PigGameData) GameOver() bool {
return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}
func (pg *PigGameData) Winner() PlayerID {
for index, score := range pg.scores {
if score >= maxScore {
return PlayerID(index)
}
}
return noPlayer
}
func (pg *PigGameData) otherPlayer() PlayerID {
return 1 - pg.player
}
func (pg *PigGameData) Hold() {
pg.scores[pg.player] += pg.turnScore
pg.PrintStatus(holds)
pg.turnRollCount, pg.turnScore = 0, 0
}
func (pg *PigGameData) NextPlayer() {
pg.turnCount++
pg.turnRollCount, pg.turnScore = 0, 0
pg.player = pg.otherPlayer()
pg.PrintStatus(turn)
}
func (pg *PigGameData) rollCountStrategy() bool {
return pg.turnRollCount >= 3
}
func (pg *PigGameData) scoreChaseStrategy() bool {
myScore := pg.PlayerScore(pg.player)
otherScore := pg.PlayerScore(pg.otherPlayer())
myPendingScore := pg.turnScore + myScore
return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}
func main() {
rand.Seed(time.Now().UnixNano())
pg := New()
pg.verbose = true
strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}
for !pg.GameOver() {
pg.Play(strategies[pg.player])
}
pg.PrintStatus(gameOverSummary)
}
|
Write a version of this C++ function in Go with identical behavior. |
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;
if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;
if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;
if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;
thisTerm = (int)ab;
if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){
t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;
haveTerm = true; return false;
}
cfn = chooseCFN();
return true;
}
void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}
void consumeTerm(int n){
if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}
else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}
}
public:
NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){
}};
| package cf
import "math"
type NG8 struct {
A12, A1, A2, A int64
B12, B1, B2, B int64
}
var (
NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}
NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}
NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}
NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}
)
func (ng *NG8) needsIngest() bool {
if ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {
return true
}
x := ng.A / ng.B
return ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x
}
func (ng *NG8) isDone() bool {
return ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0
}
func (ng *NG8) ingestWhich() bool {
if ng.B == 0 && ng.B2 == 0 {
return true
}
if ng.B == 0 || ng.B2 == 0 {
return false
}
x1 := float64(ng.A1) / float64(ng.B1)
x2 := float64(ng.A2) / float64(ng.B2)
x := float64(ng.A) / float64(ng.B)
return math.Abs(x1-x) > math.Abs(x2-x)
}
func (ng *NG8) ingest(isN1 bool, t int64) {
if isN1 {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,
ng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1
} else {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,
ng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2
}
}
func (ng *NG8) ingestInfinite(isN1 bool) {
if isN1 {
ng.A2, ng.A, ng.B2, ng.B =
ng.A12, ng.A1,
ng.B12, ng.B1
} else {
ng.A1, ng.A, ng.B1, ng.B =
ng.A12, ng.A2,
ng.B12, ng.B2
}
}
func (ng *NG8) egest(t int64) {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.B12, ng.B1, ng.B2, ng.B,
ng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t
}
func (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {
return func() NextFn {
next1, next2 := N1(), N2()
done := false
sinceEgest := 0
return func() (int64, bool) {
if done {
return 0, false
}
for ng.needsIngest() {
sinceEgest++
if sinceEgest > limit {
done = true
return 0, false
}
isN1 := ng.ingestWhich()
next := next2
if isN1 {
next = next1
}
if t, ok := next(); ok {
ng.ingest(isN1, t)
} else {
ng.ingestInfinite(isN1)
}
}
sinceEgest = 0
t := ng.A / ng.B
ng.egest(t)
done = ng.isDone()
return t, true
}
}
}
|
Port the provided C++ code into Go while preserving the original functionality. |
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return true;} else ab = ((double)a)/b;
if (b2==0){cfn = 1; return true;} else a2b2 = ((double)a2)/b2;
if (b1==0){cfn = 0; return true;} else a1b1 = ((double)a1)/b1;
if (b12==0){cfn = chooseCFN(); return true;} else a12b12 = ((double)a12)/b12;
thisTerm = (int)ab;
if (thisTerm==(int)a1b1 and thisTerm==(int)a2b2 and thisTerm==(int)a12b12){
t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm; t=a2; a2=b2; b2=t-b2*thisTerm; t=a12; a12=b12; b12=t-b12*thisTerm;
haveTerm = true; return false;
}
cfn = chooseCFN();
return true;
}
void consumeTerm(){if(cfn==0){a=a1; a2=a12; b=b1; b2=b12;} else{a=a2; a1=a12; b=b2; b1=b12;}}
void consumeTerm(int n){
if(cfn==0){t=a; a=a1; a1=t+a1*n; t=a2; a2=a12; a12=t+a12*n; t=b; b=b1; b1=t+b1*n; t=b2; b2=b12; b12=t+b12*n;}
else{t=a; a=a2; a2=t+a2*n; t=a1; a1=a12; a12=t+a12*n; t=b; b=b2; b2=t+b2*n; t=b1; b1=b12; b12=t+b12*n;}
}
public:
NG_8(int a12, int a1, int a2, int a, int b12, int b1, int b2, int b): a12(a12), a1(a1), a2(a2), a(a), b12(b12), b1(b1), b2(b2), b(b){
}};
| package cf
import "math"
type NG8 struct {
A12, A1, A2, A int64
B12, B1, B2, B int64
}
var (
NG8Add = NG8{0, 1, 1, 0, 0, 0, 0, 1}
NG8Sub = NG8{0, 1, -1, 0, 0, 0, 0, 1}
NG8Mul = NG8{1, 0, 0, 0, 0, 0, 0, 1}
NG8Div = NG8{0, 1, 0, 0, 0, 0, 1, 0}
)
func (ng *NG8) needsIngest() bool {
if ng.B12 == 0 || ng.B1 == 0 || ng.B2 == 0 || ng.B == 0 {
return true
}
x := ng.A / ng.B
return ng.A1/ng.B1 != x || ng.A2/ng.B2 != x && ng.A12/ng.B12 != x
}
func (ng *NG8) isDone() bool {
return ng.B12 == 0 && ng.B1 == 0 && ng.B2 == 0 && ng.B == 0
}
func (ng *NG8) ingestWhich() bool {
if ng.B == 0 && ng.B2 == 0 {
return true
}
if ng.B == 0 || ng.B2 == 0 {
return false
}
x1 := float64(ng.A1) / float64(ng.B1)
x2 := float64(ng.A2) / float64(ng.B2)
x := float64(ng.A) / float64(ng.B)
return math.Abs(x1-x) > math.Abs(x2-x)
}
func (ng *NG8) ingest(isN1 bool, t int64) {
if isN1 {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A2+ng.A12*t, ng.A+ng.A1*t, ng.A12, ng.A1,
ng.B2+ng.B12*t, ng.B+ng.B1*t, ng.B12, ng.B1
} else {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.A1+ng.A12*t, ng.A12, ng.A+ng.A2*t, ng.A2,
ng.B1+ng.B12*t, ng.B12, ng.B+ng.B2*t, ng.B2
}
}
func (ng *NG8) ingestInfinite(isN1 bool) {
if isN1 {
ng.A2, ng.A, ng.B2, ng.B =
ng.A12, ng.A1,
ng.B12, ng.B1
} else {
ng.A1, ng.A, ng.B1, ng.B =
ng.A12, ng.A2,
ng.B12, ng.B2
}
}
func (ng *NG8) egest(t int64) {
ng.A12, ng.A1, ng.A2, ng.A,
ng.B12, ng.B1, ng.B2, ng.B =
ng.B12, ng.B1, ng.B2, ng.B,
ng.A12-ng.B12*t, ng.A1-ng.B1*t, ng.A2-ng.B2*t, ng.A-ng.B*t
}
func (ng NG8) ApplyTo(N1, N2 ContinuedFraction, limit int) ContinuedFraction {
return func() NextFn {
next1, next2 := N1(), N2()
done := false
sinceEgest := 0
return func() (int64, bool) {
if done {
return 0, false
}
for ng.needsIngest() {
sinceEgest++
if sinceEgest > limit {
done = true
return 0, false
}
isN1 := ng.ingestWhich()
next := next2
if isN1 {
next = next1
}
if t, ok := next(); ok {
ng.ingest(isN1, t)
} else {
ng.ingestInfinite(isN1)
}
}
sinceEgest = 0
t := ng.A / ng.B
ng.egest(t)
done = ng.isDone()
return t, true
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
| package main
import (
"flag"
"fmt"
"math"
"math/big"
"os"
)
var maxRev = big.NewInt(math.MaxUint64 / 10)
var ten = big.NewInt(10)
func reverseInt(v *big.Int, result *big.Int) *big.Int {
if v.Cmp(maxRev) <= 0 {
result.SetUint64(reverseUint64(v.Uint64()))
} else {
if true {
s := reverseString(v.String())
result.SetString(s, 10)
} else {
v := new(big.Int).Set(v)
digit := new(big.Int)
result.SetUint64(0)
for v.BitLen() > 0 {
v.QuoRem(v, ten, digit)
result.Mul(result, ten)
result.Add(result, digit)
}
}
}
return result
}
func reverseUint64(v uint64) uint64 {
var r uint64
for v > 0 {
r *= 10
r += v % 10
v /= 10
}
return r
}
func reverseString(s string) string {
b := make([]byte, len(s))
for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {
b[i] = s[j]
}
return string(b)
}
var known = make(map[string]bool)
func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {
v, r := new(big.Int).SetUint64(n), new(big.Int)
reverseInt(v, r)
seen := make(map[string]bool)
isLychrel = true
isSeed = true
for i := iter; i > 0; i-- {
str := v.String()
if seen[str] {
isLychrel = true
break
}
if ans, ok := known[str]; ok {
isLychrel = ans
isSeed = false
break
}
seen[str] = true
v = v.Add(v, r)
reverseInt(v, r)
if v.Cmp(r) == 0 {
isLychrel = false
isSeed = false
break
}
}
for k := range seen {
known[k] = isLychrel
}
return isLychrel, isSeed
}
func main() {
max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive")
iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter)
var seeds []uint64
var related int
var pals []uint64
for i := uint64(1); i <= *max; i++ {
if l, s := Lychrel(i, *iter); l {
if s {
seeds = append(seeds, i)
} else {
related++
}
if i == reverseUint64(i) {
pals = append(pals, i)
}
}
}
fmt.Println(" Number of Lychrel seeds:", len(seeds))
fmt.Println(" Lychrel seeds:", seeds)
fmt.Println(" Number of related:", related)
fmt.Println("Number of Lychrel palindromes:", len(pals))
fmt.Println(" Lychrel palindromes:", pals)
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <iostream>
#include <map>
#include <vector>
#include <gmpxx.h>
using integer = mpz_class;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty())
return;
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::map<integer, std::pair<bool, integer>> cache;
std::vector<integer> seeds, related, palindromes;
for (integer n = 1; n <= 10000; ++n) {
std::pair<bool, integer> p(true, n);
std::vector<integer> seen;
integer rev = reverse(n);
integer sum = n;
for (int i = 0; i < 500; ++i) {
sum += rev;
rev = reverse(sum);
if (rev == sum) {
p.first = false;
p.second = 0;
break;
}
auto iter = cache.find(sum);
if (iter != cache.end()) {
p = iter->second;
break;
}
seen.push_back(sum);
}
for (integer s : seen)
cache.emplace(s, p);
if (!p.first)
continue;
if (p.second == n)
seeds.push_back(n);
else
related.push_back(n);
if (n == reverse(n))
palindromes.push_back(n);
}
std::cout << "number of seeds: " << seeds.size() << '\n';
std::cout << "seeds: ";
print_vector(seeds);
std::cout << "number of related: " << related.size() << '\n';
std::cout << "palindromes: ";
print_vector(palindromes);
return 0;
}
| package main
import (
"flag"
"fmt"
"math"
"math/big"
"os"
)
var maxRev = big.NewInt(math.MaxUint64 / 10)
var ten = big.NewInt(10)
func reverseInt(v *big.Int, result *big.Int) *big.Int {
if v.Cmp(maxRev) <= 0 {
result.SetUint64(reverseUint64(v.Uint64()))
} else {
if true {
s := reverseString(v.String())
result.SetString(s, 10)
} else {
v := new(big.Int).Set(v)
digit := new(big.Int)
result.SetUint64(0)
for v.BitLen() > 0 {
v.QuoRem(v, ten, digit)
result.Mul(result, ten)
result.Add(result, digit)
}
}
}
return result
}
func reverseUint64(v uint64) uint64 {
var r uint64
for v > 0 {
r *= 10
r += v % 10
v /= 10
}
return r
}
func reverseString(s string) string {
b := make([]byte, len(s))
for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 {
b[i] = s[j]
}
return string(b)
}
var known = make(map[string]bool)
func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) {
v, r := new(big.Int).SetUint64(n), new(big.Int)
reverseInt(v, r)
seen := make(map[string]bool)
isLychrel = true
isSeed = true
for i := iter; i > 0; i-- {
str := v.String()
if seen[str] {
isLychrel = true
break
}
if ans, ok := known[str]; ok {
isLychrel = ans
isSeed = false
break
}
seen[str] = true
v = v.Add(v, r)
reverseInt(v, r)
if v.Cmp(r) == 0 {
isLychrel = false
isSeed = false
break
}
}
for k := range seen {
known[k] = isLychrel
}
return isLychrel, isSeed
}
func main() {
max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive")
iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter)
var seeds []uint64
var related int
var pals []uint64
for i := uint64(1); i <= *max; i++ {
if l, s := Lychrel(i, *iter); l {
if s {
seeds = append(seeds, i)
} else {
related++
}
if i == reverseUint64(i) {
pals = append(pals, i)
}
}
}
fmt.Println(" Number of Lychrel seeds:", len(seeds))
fmt.Println(" Lychrel seeds:", seeds)
fmt.Println(" Number of related:", related)
fmt.Println("Number of Lychrel palindromes:", len(pals))
fmt.Println(" Lychrel palindromes:", pals)
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
}
}
std::cout << "\n\n" << count << " such numbers found.\n";
}
| package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
const nondecimal = "abcdef"
c := 0
for i := int64(0); i <= 500; i++ {
hex := strconv.FormatInt(i, 16)
if strings.ContainsAny(nondecimal, hex) {
fmt.Printf("%3d ", i)
c++
if c%15 == 0 {
fmt.Println()
}
}
}
fmt.Printf("\n\n%d such numbers found.\n", c)
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
}
}
std::cout << "\n\n" << count << " such numbers found.\n";
}
| package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
const nondecimal = "abcdef"
c := 0
for i := int64(0); i <= 500; i++ {
hex := strconv.FormatInt(i, 16)
if strings.ContainsAny(nondecimal, hex) {
fmt.Printf("%3d ", i)
c++
if c%15 == 0 {
fmt.Println()
}
}
}
fmt.Printf("\n\n%d such numbers found.\n", c)
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <map>
#include <vector>
#include <primesieve.hpp>
class erdos_selfridge {
public:
explicit erdos_selfridge(int limit);
uint64_t get_prime(int index) const { return primes_[index].first; }
int get_category(int index);
private:
std::vector<std::pair<uint64_t, int>> primes_;
size_t get_index(uint64_t prime) const;
};
erdos_selfridge::erdos_selfridge(int limit) {
primesieve::iterator iter;
for (int i = 0; i < limit; ++i)
primes_.emplace_back(iter.next_prime(), 0);
}
int erdos_selfridge::get_category(int index) {
auto& pair = primes_[index];
if (pair.second != 0)
return pair.second;
int max_category = 0;
uint64_t n = pair.first + 1;
for (int i = 0; n > 1; ++i) {
uint64_t p = primes_[i].first;
if (p * p > n)
break;
int count = 0;
for (; n % p == 0; ++count)
n /= p;
if (count != 0) {
int category = (p <= 3) ? 1 : 1 + get_category(i);
max_category = std::max(max_category, category);
}
}
if (n > 1) {
int category = (n <= 3) ? 1 : 1 + get_category(get_index(n));
max_category = std::max(max_category, category);
}
pair.second = max_category;
return max_category;
}
size_t erdos_selfridge::get_index(uint64_t prime) const {
auto it = std::lower_bound(primes_.begin(), primes_.end(), prime,
[](const std::pair<uint64_t, int>& p,
uint64_t n) { return p.first < n; });
assert(it != primes_.end());
assert(it->first == prime);
return std::distance(primes_.begin(), it);
}
auto get_primes_by_category(erdos_selfridge& es, int limit) {
std::map<int, std::vector<uint64_t>> primes_by_category;
for (int i = 0; i < limit; ++i) {
uint64_t prime = es.get_prime(i);
int category = es.get_category(i);
primes_by_category[category].push_back(prime);
}
return primes_by_category;
}
int main() {
const int limit1 = 200, limit2 = 1000000;
erdos_selfridge es(limit2);
std::cout << "First 200 primes:\n";
for (const auto& p : get_primes_by_category(es, limit1)) {
std::cout << "Category " << p.first << ":\n";
for (size_t i = 0, n = p.second.size(); i != n; ++i) {
std::cout << std::setw(4) << p.second[i]
<< ((i + 1) % 15 == 0 ? '\n' : ' ');
}
std::cout << "\n\n";
}
std::cout << "First 1,000,000 primes:\n";
for (const auto& p : get_primes_by_category(es, limit2)) {
const auto& v = p.second;
std::cout << "Category " << std::setw(2) << p.first << ": "
<< "first = " << std::setw(7) << v.front()
<< " last = " << std::setw(8) << v.back()
<< " count = " << v.size() << '\n';
}
}
| package main
import (
"fmt"
"math"
"rcu"
)
var limit = int(math.Log(1e6) * 1e6 * 1.2)
var primes = rcu.Primes(limit)
var prevCats = make(map[int]int)
func cat(p int) int {
if v, ok := prevCats[p]; ok {
return v
}
pf := rcu.PrimeFactors(p + 1)
all := true
for _, f := range pf {
if f != 2 && f != 3 {
all = false
break
}
}
if all {
return 1
}
if p > 2 {
len := len(pf)
for i := len - 1; i >= 1; i-- {
if pf[i-1] == pf[i] {
pf = append(pf[:i], pf[i+1:]...)
}
}
}
for c := 2; c <= 11; c++ {
all := true
for _, f := range pf {
if cat(f) >= c {
all = false
break
}
}
if all {
prevCats[p] = c
return c
}
}
return 12
}
func main() {
es := make([][]int, 12)
fmt.Println("First 200 primes:\n")
for _, p := range primes[0:200] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 6; c++ {
if len(es[c-1]) > 0 {
fmt.Println("Category", c, "\b:")
fmt.Println(es[c-1])
fmt.Println()
}
}
fmt.Println("First million primes:\n")
for _, p := range primes[200:1e6] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 12; c++ {
e := es[c-1]
if len(e) > 0 {
format := "Category %-2d: First = %7d Last = %8d Count = %6d\n"
fmt.Printf(format, c, e[0], e[len(e)-1], len(e))
}
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
struct range {
range(int lo, int hi) : low(lo), high(hi) {}
int low;
int high;
};
std::ostream& operator<<(std::ostream& out, const range& r) {
return out << r.low << '-' << r.high;
}
class ranges {
public:
ranges() {}
explicit ranges(std::initializer_list<range> init) : ranges_(init) {}
void add(int n);
void remove(int n);
bool empty() const { return ranges_.empty(); }
private:
friend std::ostream& operator<<(std::ostream& out, const ranges& r);
std::list<range> ranges_;
};
void ranges::add(int n) {
for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {
if (n + 1 < i->low) {
ranges_.emplace(i, n, n);
return;
}
if (n > i->high + 1)
continue;
if (n + 1 == i->low)
i->low = n;
else if (n == i->high + 1)
i->high = n;
else
return;
if (i != ranges_.begin()) {
auto prev = std::prev(i);
if (prev->high + 1 == i->low) {
i->low = prev->low;
ranges_.erase(prev);
}
}
auto next = std::next(i);
if (next != ranges_.end() && next->low - 1 == i->high) {
i->high = next->high;
ranges_.erase(next);
}
return;
}
ranges_.emplace_back(n, n);
}
void ranges::remove(int n) {
for (auto i = ranges_.begin(); i != ranges_.end(); ++i) {
if (n < i->low)
return;
if (n == i->low) {
if (++i->low > i->high)
ranges_.erase(i);
return;
}
if (n == i->high) {
if (--i->high < i->low)
ranges_.erase(i);
return;
}
if (n > i->low & n < i->high) {
int low = i->low;
i->low = n + 1;
ranges_.emplace(i, low, n - 1);
return;
}
}
}
std::ostream& operator<<(std::ostream& out, const ranges& r) {
if (!r.empty()) {
auto i = r.ranges_.begin();
out << *i++;
for (; i != r.ranges_.end(); ++i)
out << ',' << *i;
}
return out;
}
void test_add(ranges& r, int n) {
r.add(n);
std::cout << " add " << std::setw(2) << n << " => " << r << '\n';
}
void test_remove(ranges& r, int n) {
r.remove(n);
std::cout << " remove " << std::setw(2) << n << " => " << r << '\n';
}
void test1() {
ranges r;
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 77);
test_add(r, 79);
test_add(r, 78);
test_remove(r, 77);
test_remove(r, 78);
test_remove(r, 79);
}
void test2() {
ranges r{{1,3}, {5,5}};
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 1);
test_remove(r, 4);
test_add(r, 7);
test_add(r, 8);
test_add(r, 6);
test_remove(r, 7);
}
void test3() {
ranges r{{1,5}, {10,25}, {27,30}};
std::cout << "Start: \"" << r << "\"\n";
test_add(r, 26);
test_add(r, 9);
test_add(r, 7);
test_remove(r, 26);
test_remove(r, 9);
test_remove(r, 7);
}
int main() {
test1();
std::cout << '\n';
test2();
std::cout << '\n';
test3();
return 0;
}
| package main
import (
"fmt"
"strings"
)
type rng struct{ from, to int }
type fn func(rngs *[]rng, n int)
func (r rng) String() string { return fmt.Sprintf("%d-%d", r.from, r.to) }
func rangesAdd(rngs []rng, n int) []rng {
if len(rngs) == 0 {
rngs = append(rngs, rng{n, n})
return rngs
}
for i, r := range rngs {
if n < r.from-1 {
rngs = append(rngs, rng{})
copy(rngs[i+1:], rngs[i:])
rngs[i] = rng{n, n}
return rngs
} else if n == r.from-1 {
rngs[i] = rng{n, r.to}
return rngs
} else if n <= r.to {
return rngs
} else if n == r.to+1 {
rngs[i] = rng{r.from, n}
if i < len(rngs)-1 && (n == rngs[i+1].from || n+1 == rngs[i+1].from) {
rngs[i] = rng{r.from, rngs[i+1].to}
copy(rngs[i+1:], rngs[i+2:])
rngs[len(rngs)-1] = rng{}
rngs = rngs[:len(rngs)-1]
}
return rngs
} else if i == len(rngs)-1 {
rngs = append(rngs, rng{n, n})
return rngs
}
}
return rngs
}
func rangesRemove(rngs []rng, n int) []rng {
if len(rngs) == 0 {
return rngs
}
for i, r := range rngs {
if n <= r.from-1 {
return rngs
} else if n == r.from && n == r.to {
copy(rngs[i:], rngs[i+1:])
rngs[len(rngs)-1] = rng{}
rngs = rngs[:len(rngs)-1]
return rngs
} else if n == r.from {
rngs[i] = rng{n + 1, r.to}
return rngs
} else if n < r.to {
rngs[i] = rng{r.from, n - 1}
rngs = append(rngs, rng{})
copy(rngs[i+2:], rngs[i+1:])
rngs[i+1] = rng{n + 1, r.to}
return rngs
} else if n == r.to {
rngs[i] = rng{r.from, n - 1}
return rngs
}
}
return rngs
}
func standard(rngs []rng) string {
if len(rngs) == 0 {
return ""
}
var sb strings.Builder
for _, r := range rngs {
sb.WriteString(fmt.Sprintf("%s,", r))
}
s := sb.String()
return s[:len(s)-1]
}
func main() {
const add = 0
const remove = 1
fns := []fn{
func(prngs *[]rng, n int) {
*prngs = rangesAdd(*prngs, n)
fmt.Printf(" add %2d => %s\n", n, standard(*prngs))
},
func(prngs *[]rng, n int) {
*prngs = rangesRemove(*prngs, n)
fmt.Printf(" remove %2d => %s\n", n, standard(*prngs))
},
}
var rngs []rng
ops := [][2]int{{add, 77}, {add, 79}, {add, 78}, {remove, 77}, {remove, 78}, {remove, 79}}
fmt.Printf("Start: %q\n", standard(rngs))
for _, op := range ops {
fns[op[0]](&rngs, op[1])
}
rngs = []rng{{1, 3}, {5, 5}}
ops = [][2]int{{add, 1}, {remove, 4}, {add, 7}, {add, 8}, {add, 6}, {remove, 7}}
fmt.Printf("\nStart: %q\n", standard(rngs))
for _, op := range ops {
fns[op[0]](&rngs, op[1])
}
rngs = []rng{{1, 5}, {10, 25}, {27, 30}}
ops = [][2]int{{add, 26}, {add, 9}, {add, 7}, {remove, 26}, {remove, 9}, {remove, 7}}
fmt.Printf("\nStart: %q\n", standard(rngs))
for _, op := range ops {
fns[op[0]](&rngs, op[1])
}
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
a = sqrt(big_int(a * a * a));
++count;
if (a > max) {
max = a;
max_count = count;
}
}
return std::make_tuple(count, max_count, max, max.get_str().size());
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "n l[n] i[n] h[n]\n";
std::cout << "--------------------------------\n";
for (int n = 20; n < 40; ++n) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(2) << n << " " << std::setw(2) << count
<< " " << std::setw(2) << max_count << " " << max
<< '\n';
}
std::cout << '\n';
std::cout << " n l[n] i[n] d[n]\n";
std::cout << "----------------------------------------\n";
for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,
275485, 1267909, 2264915, 5812827, 7110201, 56261531,
92502777, 172376627, 604398963}) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(11) << n << " " << std::setw(3) << count
<< " " << std::setw(3) << max_count << " " << digits
<< '\n';
}
}
| package main
import (
"fmt"
"log"
big "github.com/ncw/gmp"
"rcu"
)
var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)
func juggler(n int64) (int, int, *big.Int, int) {
if n < 1 {
log.Fatal("Starting value must be a positive integer.")
}
count := 0
maxCount := 0
a := big.NewInt(n)
max := big.NewInt(n)
tmp := new(big.Int)
for a.Cmp(one) != 0 {
if tmp.Rem(a, two).Cmp(zero) == 0 {
a.Sqrt(a)
} else {
tmp.Mul(a, a)
tmp.Mul(tmp, a)
a.Sqrt(tmp)
}
count++
if a.Cmp(max) > 0 {
max.Set(a)
maxCount = count
}
}
return count, maxCount, max, len(max.String())
}
func main() {
fmt.Println("n l[n] i[n] h[n]")
fmt.Println("-----------------------------------")
for n := int64(20); n < 40; n++ {
count, maxCount, max, _ := juggler(n)
cmax := rcu.Commatize(int(max.Int64()))
fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax)
}
fmt.Println()
nums := []int64{
113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,
2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,
}
fmt.Println(" n l[n] i[n] d[n]")
fmt.Println("-------------------------------------")
for _, n := range nums {
count, maxCount, _, digits := juggler(n)
cn := rcu.Commatize(int(n))
fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits))
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
a = sqrt(big_int(a * a * a));
++count;
if (a > max) {
max = a;
max_count = count;
}
}
return std::make_tuple(count, max_count, max, max.get_str().size());
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "n l[n] i[n] h[n]\n";
std::cout << "--------------------------------\n";
for (int n = 20; n < 40; ++n) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(2) << n << " " << std::setw(2) << count
<< " " << std::setw(2) << max_count << " " << max
<< '\n';
}
std::cout << '\n';
std::cout << " n l[n] i[n] d[n]\n";
std::cout << "----------------------------------------\n";
for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,
275485, 1267909, 2264915, 5812827, 7110201, 56261531,
92502777, 172376627, 604398963}) {
auto [count, max_count, max, digits] = juggler(n);
std::cout << std::setw(11) << n << " " << std::setw(3) << count
<< " " << std::setw(3) << max_count << " " << digits
<< '\n';
}
}
| package main
import (
"fmt"
"log"
big "github.com/ncw/gmp"
"rcu"
)
var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)
func juggler(n int64) (int, int, *big.Int, int) {
if n < 1 {
log.Fatal("Starting value must be a positive integer.")
}
count := 0
maxCount := 0
a := big.NewInt(n)
max := big.NewInt(n)
tmp := new(big.Int)
for a.Cmp(one) != 0 {
if tmp.Rem(a, two).Cmp(zero) == 0 {
a.Sqrt(a)
} else {
tmp.Mul(a, a)
tmp.Mul(tmp, a)
a.Sqrt(tmp)
}
count++
if a.Cmp(max) > 0 {
max.Set(a)
maxCount = count
}
}
return count, maxCount, max, len(max.String())
}
func main() {
fmt.Println("n l[n] i[n] h[n]")
fmt.Println("-----------------------------------")
for n := int64(20); n < 40; n++ {
count, maxCount, max, _ := juggler(n)
cmax := rcu.Commatize(int(max.Int64()))
fmt.Printf("%2d %2d %2d %s\n", n, count, maxCount, cmax)
}
fmt.Println()
nums := []int64{
113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,
2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,
}
fmt.Println(" n l[n] i[n] d[n]")
fmt.Println("-------------------------------------")
for _, n := range nums {
count, maxCount, _, digits := juggler(n)
cn := rcu.Commatize(int(n))
fmt.Printf("%11s %3d %3d %s\n", cn, count, maxCount, rcu.Commatize(digits))
}
}
|
Write the same algorithm in Go as shown in this C++ implementation. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_square {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = (size - length)/2;
y_ = length;
angle_ = 0;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "F+XF+F+XF";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string sierpinski_square::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
if (c == 'X')
t += "XF-F+F-XF+F+XF-F+F-X";
else
t += c;
}
return t;
}
void sierpinski_square::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ += length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void sierpinski_square::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
line(out);
break;
case '+':
angle_ = (angle_ + 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
int main() {
std::ofstream out("sierpinski_square.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
sierpinski_square s;
s.write(out, 635, 5, 5);
return 0;
}
| package main
import (
"github.com/fogleman/gg"
"github.com/trubitsyn/go-lindenmayer"
"log"
"math"
)
const twoPi = 2 * math.Pi
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h, theta float64
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2,
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
operations['+']()
operations['F']()
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
| package main
import (
"fmt"
"math"
"sort"
)
const adj = 0.0001
var primes = []uint64{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
}
func gcd(x, y uint64) uint64 {
for y != 0 {
x, y = y, x%y
}
return x
}
func isSquareFree(x uint64) bool {
for _, p := range primes {
p2 := p * p
if p2 > x {
break
}
if x%p2 == 0 {
return false
}
}
return true
}
func iroot(x, p uint64) uint64 {
return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)
}
func ipow(x, p uint64) uint64 {
prod := uint64(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func powerful(n, k uint64) []uint64 {
set := make(map[uint64]bool)
var f func(m, r uint64)
f = func(m, r uint64) {
if r < k {
set[m] = true
return
}
for v := uint64(1); v <= iroot(n/m, r); v++ {
if r > k {
if !isSquareFree(v) || gcd(m, v) != 1 {
continue
}
}
f(m*ipow(v, r), r-1)
}
}
f(1, (1<<k)-1)
list := make([]uint64, 0, len(set))
for key := range set {
list = append(list, key)
}
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list
}
func main() {
power := uint64(10)
for k := uint64(2); k <= 10; k++ {
power *= 10
a := powerful(power, k)
le := len(a)
h, t := a[0:5], a[le-5:]
fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t)
}
fmt.Println()
for k := uint64(2); k <= 10; k++ {
power := uint64(1)
var counts []int
for j := uint64(0); j < k+10; j++ {
a := powerful(power, k)
counts = append(counts, len(a))
power *= 10
}
j := k + 10
fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts)
}
}
|
Write the same code in Go as shown below in C++. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
bool is_square_free(uint64_t n) {
static constexpr uint64_t primes[] {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
};
for (auto p : primes) {
auto p2 = p * p;
if (p2 > n)
break;
if (n % p2 == 0)
return false;
}
return true;
}
uint64_t iroot(uint64_t n, uint64_t r) {
static constexpr double adj = 1e-6;
return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}
uint64_t ipow(uint64_t n, uint64_t p) {
uint64_t prod = 1;
for (; p > 0; p >>= 1) {
if (p & 1)
prod *= n;
n *= n;
}
return prod;
}
std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
std::vector<uint64_t> result;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r < k) {
result.push_back(m);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
continue;
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
std::sort(result.begin(), result.end());
return result;
}
uint64_t powerful_count(uint64_t n, uint64_t k) {
uint64_t count = 0;
std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
if (r <= k) {
count += iroot(n/m, r);
return;
}
uint64_t root = iroot(n/m, r);
for (uint64_t v = 1; v <= root; ++v) {
if (is_square_free(v) && std::gcd(m, v) == 1)
f(m * ipow(v, r), r - 1);
}
};
f(1, 2*k - 1);
return count;
}
int main() {
const size_t max = 5;
for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
auto result = powerful(p, k);
std::cout << result.size() << " " << k
<< "-powerful numbers <= 10^" << k << ":";
for (size_t i = 0; i < result.size(); ++i) {
if (i == max)
std::cout << " ...";
else if (i < max || i + max >= result.size())
std::cout << ' ' << result[i];
}
std::cout << '\n';
}
std::cout << '\n';
for (uint64_t k = 2; k <= 10; ++k) {
std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
<< k + 10 << ":";
for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
std::cout << ' ' << powerful_count(p, k);
std::cout << '\n';
}
}
| package main
import (
"fmt"
"math"
"sort"
)
const adj = 0.0001
var primes = []uint64{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
}
func gcd(x, y uint64) uint64 {
for y != 0 {
x, y = y, x%y
}
return x
}
func isSquareFree(x uint64) bool {
for _, p := range primes {
p2 := p * p
if p2 > x {
break
}
if x%p2 == 0 {
return false
}
}
return true
}
func iroot(x, p uint64) uint64 {
return uint64(math.Pow(float64(x), 1.0/float64(p)) + adj)
}
func ipow(x, p uint64) uint64 {
prod := uint64(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func powerful(n, k uint64) []uint64 {
set := make(map[uint64]bool)
var f func(m, r uint64)
f = func(m, r uint64) {
if r < k {
set[m] = true
return
}
for v := uint64(1); v <= iroot(n/m, r); v++ {
if r > k {
if !isSquareFree(v) || gcd(m, v) != 1 {
continue
}
}
f(m*ipow(v, r), r-1)
}
}
f(1, (1<<k)-1)
list := make([]uint64, 0, len(set))
for key := range set {
list = append(list, key)
}
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list
}
func main() {
power := uint64(10)
for k := uint64(2); k <= 10; k++ {
power *= 10
a := powerful(power, k)
le := len(a)
h, t := a[0:5], a[le-5:]
fmt.Printf("%d %2d-powerful numbers <= 10^%-2d: %v ... %v\n", le, k, k, h, t)
}
fmt.Println()
for k := uint64(2); k <= 10; k++ {
power := uint64(1)
var counts []int
for j := uint64(0); j < k+10; j++ {
a := powerful(power, k)
counts = append(counts, len(a))
power *= 10
}
j := k + 10
fmt.Printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d): %v\n", k, j, counts)
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
void reverse(std::istream& in, std::ostream& out) {
constexpr size_t record_length = 80;
char record[record_length];
while (in.read(record, record_length)) {
std::reverse(std::begin(record), std::end(record));
out.write(record, record_length);
}
out.flush();
}
int main(int argc, char** argv) {
std::ifstream in("infile.dat", std::ios_base::binary);
if (!in) {
std::cerr << "Cannot open input file\n";
return EXIT_FAILURE;
}
std::ofstream out("outfile.dat", std::ios_base::binary);
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
try {
in.exceptions(std::ios_base::badbit);
out.exceptions(std::ios_base::badbit);
reverse(in, out);
} catch (const std::exception& ex) {
std::cerr << "I/O error: " << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func reverseBytes(bytes []byte) {
for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
bytes[i], bytes[j] = bytes[j], bytes[i]
}
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
in, err := os.Open("infile.dat")
check(err)
defer in.Close()
out, err := os.Create("outfile.dat")
check(err)
record := make([]byte, 80)
empty := make([]byte, 80)
for {
n, err := in.Read(record)
if err != nil {
if n == 0 {
break
} else {
out.Close()
log.Fatal(err)
}
}
reverseBytes(record)
out.Write(record)
copy(record, empty)
}
out.Close()
cmd := exec.Command("dd", "if=outfile.dat", "cbs=80", "conv=unblock")
bytes, err := cmd.Output()
check(err)
fmt.Println(string(bytes))
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <cstdlib>
#include <fstream>
#include <iostream>
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
const size_t len = word.size();
if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
std::cout << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
count := 0
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {
count++
fmt.Printf("%d: %s\n", count, s)
}
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <iostream>
bool is_giuga(unsigned int n) {
unsigned int m = n / 2;
auto test_factor = [&m, n](unsigned int p) -> bool {
if (m % p != 0)
return true;
m /= p;
return m % p != 0 && (n / p - 1) % p == 0;
};
if (!test_factor(3) || !test_factor(5))
return false;
static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};
for (unsigned int p = 7, i = 0; p * p <= m; ++i) {
if (!test_factor(p))
return false;
p += wheel[i & 7];
}
return m == 1 || (n / m - 1) % m == 0;
}
int main() {
std::cout << "First 5 Giuga numbers:\n";
for (unsigned int i = 0, n = 6; i < 5; n += 4) {
if (is_giuga(n)) {
std::cout << n << '\n';
++i;
}
}
}
| package main
import "fmt"
var factors []int
var inc = []int{4, 2, 4, 2, 4, 6, 2, 6}
func primeFactors(n int) {
factors = factors[:0]
factors = append(factors, 2)
last := 2
n /= 2
for n%3 == 0 {
if last == 3 {
factors = factors[:0]
return
}
last = 3
factors = append(factors, 3)
n /= 3
}
for n%5 == 0 {
if last == 5 {
factors = factors[:0]
return
}
last = 5
factors = append(factors, 5)
n /= 5
}
for k, i := 7, 0; k*k <= n; {
if n%k == 0 {
if last == k {
factors = factors[:0]
return
}
last = k
factors = append(factors, k)
n /= k
} else {
k += inc[i]
i = (i + 1) % 8
}
}
if n > 1 {
factors = append(factors, n)
}
}
func main() {
const limit = 5
var giuga []int
for n := 6; len(giuga) < limit; n += 4 {
primeFactors(n)
if len(factors) > 2 {
isGiuga := true
for _, f := range factors {
if (n/f-1)%f != 0 {
isGiuga = false
break
}
}
if isGiuga {
giuga = append(giuga, n)
}
}
}
fmt.Println("The first", limit, "Giuga numbers are:")
fmt.Println(giuga)
}
|
Convert this C++ block to Go, preserving its control flow and logic. |
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
| package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
|
Write a version of this C++ function in Go with identical behavior. |
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int degree = polynomial.size() - 1;
int d = degree;
for (int i : polynomial)
{
if (d < degree)
{
if (i >= 0)
{
formatted += " + ";
}
else
{
formatted += " - ";
}
}
formatted += std::to_string(abs(i));
if (d > 1)
{
formatted += "x^" + std::to_string(d);
}
else if (d == 1)
{
formatted += "x";
}
d--;
}
return formatted;
}
std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
std::vector<int> quotient;
quotient = dividend;
int normalizer = divisor[0];
for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
{
quotient[i] /= normalizer;
int coef = quotient[i];
if (coef != 0)
{
for (int j = 1; j < divisor.size(); j++)
{
quotient[i + j] += -divisor[j] * coef;
}
}
}
return quotient;
}
int main(int argc, char **argv)
{
std::vector<int> dividend{ 1, -12, 0, -42};
std::vector<int> divisor{ 1, -3};
std::cout << frmtPolynomial(dividend) << "\n";
std::cout << frmtPolynomial(divisor) << "\n";
std::vector<int> quotient = syntheticDiv(dividend, divisor);
std::cout << frmtPolynomial(quotient, true) << "\n";
}
| package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
int divisor_count(int n) {
int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (int p = 3; p * p <= n; p += 2) {
int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
int limit = 1000;
switch (argc) {
case 1:
break;
case 2:
limit = std::strtol(argv[1], nullptr, 10);
if (limit <= 0) {
std::cerr << "Invalid limit\n";
return EXIT_FAILURE;
}
break;
default:
std::cerr << "usage: " << argv[0] << " [limit]\n";
return EXIT_FAILURE;
}
int width = static_cast<int>(std::ceil(std::log10(limit)));
int count = 0;
for (int i = 1;; ++i) {
int n = i * i;
if (n >= limit)
break;
int divisors = divisor_count(n);
if (divisors != 2 && is_prime(divisors))
std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\n' : ' ');
}
std::cout << "\nCount: " << count << '\n';
return EXIT_SUCCESS;
}
| package main
import (
"fmt"
"rcu"
)
func countDivisors(n int) int {
count := 0
i := 1
k := 1
if n%2 == 1 {
k = 2
}
for ; i*i <= n; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
}
return count
}
func main() {
const limit = 1e5
var results []int
for i := 2; i * i < limit; i++ {
n := countDivisors(i * i)
if n > 2 && rcu.IsPrime(n) {
results = append(results, i * i)
}
}
climit := rcu.Commatize(limit)
fmt.Printf("Positive integers under %7s whose number of divisors is an odd prime:\n", climit)
under1000 := 0
for i, n := range results {
fmt.Printf("%7s", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
if n < 1000 {
under1000++
}
}
fmt.Printf("\n\nFound %d such integers (%d under 1,000).\n", len(results), under1000)
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
int divisor_count(int n) {
int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (int p = 3; p * p <= n; p += 2) {
int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
int limit = 1000;
switch (argc) {
case 1:
break;
case 2:
limit = std::strtol(argv[1], nullptr, 10);
if (limit <= 0) {
std::cerr << "Invalid limit\n";
return EXIT_FAILURE;
}
break;
default:
std::cerr << "usage: " << argv[0] << " [limit]\n";
return EXIT_FAILURE;
}
int width = static_cast<int>(std::ceil(std::log10(limit)));
int count = 0;
for (int i = 1;; ++i) {
int n = i * i;
if (n >= limit)
break;
int divisors = divisor_count(n);
if (divisors != 2 && is_prime(divisors))
std::cout << std::setw(width) << n << (++count % 10 == 0 ? '\n' : ' ');
}
std::cout << "\nCount: " << count << '\n';
return EXIT_SUCCESS;
}
| package main
import (
"fmt"
"rcu"
)
func countDivisors(n int) int {
count := 0
i := 1
k := 1
if n%2 == 1 {
k = 2
}
for ; i*i <= n; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
}
return count
}
func main() {
const limit = 1e5
var results []int
for i := 2; i * i < limit; i++ {
n := countDivisors(i * i)
if n > 2 && rcu.IsPrime(n) {
results = append(results, i * i)
}
}
climit := rcu.Commatize(limit)
fmt.Printf("Positive integers under %7s whose number of divisors is an odd prime:\n", climit)
under1000 := 0
for i, n := range results {
fmt.Printf("%7s", rcu.Commatize(n))
if (i+1)%10 == 0 {
fmt.Println()
}
if n < 1000 {
under1000++
}
}
fmt.Printf("\n\nFound %d such integers (%d under 1,000).\n", len(results), under1000)
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
using word_list = std::vector<std::pair<std::string, std::string>>;
void print_words(std::ostream& out, const word_list& words) {
int n = 1;
for (const auto& pair : words) {
out << std::right << std::setw(2) << n++ << ": "
<< std::left << std::setw(14) << pair.first
<< pair.second << '\n';
}
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
const int min_length = 5;
std::string line;
std::set<std::string> dictionary;
while (getline(in, line)) {
if (line.size() >= min_length)
dictionary.insert(line);
}
word_list odd_words, even_words;
for (const std::string& word : dictionary) {
if (word.size() < min_length + 2*(min_length/2))
continue;
std::string odd_word, even_word;
for (auto w = word.begin(); w != word.end(); ++w) {
odd_word += *w;
if (++w == word.end())
break;
even_word += *w;
}
if (dictionary.find(odd_word) != dictionary.end())
odd_words.emplace_back(word, odd_word);
if (dictionary.find(even_word) != dictionary.end())
even_words.emplace_back(word, even_word);
}
std::cout << "Odd words:\n";
print_words(std::cout, odd_words);
std::cout << "\nEven words:\n";
print_words(std::cout, even_words);
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
count := 0
fmt.Println("The odd words with length > 4 in", wordList, "are:")
for _, word := range words {
rword := []rune(word)
if len(rword) > 8 {
var sb strings.Builder
for i := 0; i < len(rword); i += 2 {
sb.WriteRune(rword[i])
}
s := sb.String()
idx := sort.SearchStrings(words, s)
if idx < len(words) && words[idx] == s {
count = count + 1
fmt.Printf("%2d: %-12s -> %s\n", count, word, s)
}
}
}
}
|
Generate an equivalent Go version of this C++ code. | #include <iomanip>
#include <iostream>
#include <list>
#include <string>
#include <vector>
#include <utility>
#include <vector>
class nest_tree;
bool operator==(const nest_tree&, const nest_tree&);
class nest_tree {
public:
explicit nest_tree(const std::string& name) : name_(name) {}
nest_tree& add_child(const std::string& name) {
children_.emplace_back(name);
return children_.back();
}
void print(std::ostream& out) const {
print(out, 0);
}
const std::string& name() const {
return name_;
}
const std::list<nest_tree>& children() const {
return children_;
}
bool equals(const nest_tree& n) const {
return name_ == n.name_ && children_ == n.children_;
}
private:
void print(std::ostream& out, int level) const {
std::string indent(level * 4, ' ');
out << indent << name_ << '\n';
for (const nest_tree& child : children_)
child.print(out, level + 1);
}
std::string name_;
std::list<nest_tree> children_;
};
bool operator==(const nest_tree& a, const nest_tree& b) {
return a.equals(b);
}
class indent_tree {
public:
explicit indent_tree(const nest_tree& n) {
items_.emplace_back(0, n.name());
from_nest(n, 0);
}
void print(std::ostream& out) const {
for (const auto& item : items_)
std::cout << item.first << ' ' << item.second << '\n';
}
nest_tree to_nest() const {
nest_tree n(items_[0].second);
to_nest_(n, 1, 0);
return n;
}
private:
void from_nest(const nest_tree& n, int level) {
for (const nest_tree& child : n.children()) {
items_.emplace_back(level + 1, child.name());
from_nest(child, level + 1);
}
}
size_t to_nest_(nest_tree& n, size_t pos, int level) const {
while (pos < items_.size() && items_[pos].first == level + 1) {
nest_tree& child = n.add_child(items_[pos].second);
pos = to_nest_(child, pos + 1, level + 1);
}
return pos;
}
std::vector<std::pair<int, std::string>> items_;
};
int main() {
nest_tree n("RosettaCode");
auto& child1 = n.add_child("rocks");
auto& child2 = n.add_child("mocks");
child1.add_child("code");
child1.add_child("comparison");
child1.add_child("wiki");
child2.add_child("trolling");
std::cout << "Initial nest format:\n";
n.print(std::cout);
indent_tree i(n);
std::cout << "\nIndent format:\n";
i.print(std::cout);
nest_tree n2(i.to_nest());
std::cout << "\nFinal nest format:\n";
n2.print(std::cout);
std::cout << "\nAre initial and final nest formats equal? "
<< std::boolalpha << n.equals(n2) << '\n';
return 0;
}
| package main
import (
"fmt"
"io"
"os"
"strings"
)
type nNode struct {
name string
children []nNode
}
type iNode struct {
level int
name string
}
func printNest(n nNode, level int, w io.Writer) {
if level == 0 {
fmt.Fprintln(w, "\n==Nest form==\n")
}
fmt.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name)
for _, c := range n.children {
fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1))
printNest(c, level+1, w)
}
}
func toNest(iNodes []iNode, start, level int, n *nNode) {
if level == 0 {
n.name = iNodes[0].name
}
for i := start + 1; i < len(iNodes); i++ {
if iNodes[i].level == level+1 {
c := nNode{iNodes[i].name, nil}
toNest(iNodes, i, level+1, &c)
n.children = append(n.children, c)
} else if iNodes[i].level <= level {
return
}
}
}
func printIndent(iNodes []iNode, w io.Writer) {
fmt.Fprintln(w, "\n==Indent form==\n")
for _, n := range iNodes {
fmt.Fprintf(w, "%d %s\n", n.level, n.name)
}
}
func toIndent(n nNode, level int, iNodes *[]iNode) {
*iNodes = append(*iNodes, iNode{level, n.name})
for _, c := range n.children {
toIndent(c, level+1, iNodes)
}
}
func main() {
n1 := nNode{"RosettaCode", nil}
n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}}
n3 := nNode{"mocks", []nNode{{"trolling", nil}}}
n1.children = append(n1.children, n2, n3)
var sb strings.Builder
printNest(n1, 0, &sb)
s1 := sb.String()
fmt.Print(s1)
var iNodes []iNode
toIndent(n1, 0, &iNodes)
printIndent(iNodes, os.Stdout)
var n nNode
toNest(iNodes, 0, 0, &n)
sb.Reset()
printNest(n, 0, &sb)
s2 := sb.String()
fmt.Print(s2)
fmt.Println("\nRound trip test satisfied? ", s1 == s2)
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <map>
#include <iostream>
#include <string>
int main()
{
std::map<char, std::string> rep =
{{'a', "DCaBA"},
{'b', "E"},
{'r', "Fr"}};
std::string magic = "abracadabra";
for(auto it = magic.begin(); it != magic.end(); ++it)
{
if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())
{
*it = f->second.back();
f->second.pop_back();
}
}
std::cout << magic << "\n";
}
| package main
import (
"fmt"
"strings"
)
func main() {
s := "abracadabra"
ss := []byte(s)
var ixs []int
for ix, c := range s {
if c == 'a' {
ixs = append(ixs, ix)
}
}
repl := "ABaCD"
for i := 0; i < 5; i++ {
ss[ixs[i]] = repl[i]
}
s = string(ss)
s = strings.Replace(s, "b", "E", 1)
s = strings.Replace(s, "r", "F", 2)
s = strings.Replace(s, "F", "r", 1)
fmt.Println(s)
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <map>
#include <iostream>
#include <string>
int main()
{
std::map<char, std::string> rep =
{{'a', "DCaBA"},
{'b', "E"},
{'r', "Fr"}};
std::string magic = "abracadabra";
for(auto it = magic.begin(); it != magic.end(); ++it)
{
if(auto f = rep.find(*it); f != rep.end() && !f->second.empty())
{
*it = f->second.back();
f->second.pop_back();
}
}
std::cout << magic << "\n";
}
| package main
import (
"fmt"
"strings"
)
func main() {
s := "abracadabra"
ss := []byte(s)
var ixs []int
for ix, c := range s {
if c == 'a' {
ixs = append(ixs, ix)
}
}
repl := "ABaCD"
for i := 0; i < 5; i++ {
ss[ixs[i]] = repl[i]
}
s = string(ss)
s = strings.Replace(s, "b", "E", 1)
s = strings.Replace(s, "r", "F", 2)
s = strings.Replace(s, "F", "r", 1)
fmt.Println(s)
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
mpz_class repunit(std::string(prime, '1'), base);
if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
result.push_back(prime);
}
return result;
}
int main() {
std::vector<uint64_t> primes;
const uint64_t limit = 2700;
primesieve::generate_primes(limit, &primes);
std::vector<std::future<std::vector<uint64_t>>> futures;
for (uint32_t base = 2; base <= 36; ++base) {
futures.push_back(std::async(repunit_primes, base, primes));
}
std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
std::cout << "Base " << std::setw(2) << base << ':';
for (auto digits : futures[i].get())
std::cout << ' ' << digits;
std::cout << '\n';
}
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
if s.ProbablyPrime(15) {
rPrimes = append(rPrimes, p)
}
}
fmt.Printf("Base %2d: %v\n", b, rPrimes)
}
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
mpz_class repunit(std::string(prime, '1'), base);
if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
result.push_back(prime);
}
return result;
}
int main() {
std::vector<uint64_t> primes;
const uint64_t limit = 2700;
primesieve::generate_primes(limit, &primes);
std::vector<std::future<std::vector<uint64_t>>> futures;
for (uint32_t base = 2; base <= 36; ++base) {
futures.push_back(std::async(repunit_primes, base, primes));
}
std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
std::cout << "Base " << std::setw(2) << base << ':';
for (auto digits : futures[i].get())
std::cout << ' ' << digits;
std::cout << '\n';
}
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
if s.ProbablyPrime(15) {
rPrimes = append(rPrimes, p)
}
}
fmt.Printf("Base %2d: %v\n", b, rPrimes)
}
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_curzon(uint64_t n, uint64_t k) {
const uint64_t r = k * n;
return modpow(k, n, r + 1) == r;
}
int main() {
for (uint64_t k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
uint64_t count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
}
| package main
import (
"fmt"
"math/big"
)
func main() {
zero := big.NewInt(0)
one := big.NewInt(1)
for k := int64(2); k <= 10; k += 2 {
bk := big.NewInt(k)
fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
count := 0
n := int64(1)
pow := big.NewInt(k)
z := new(big.Int)
var curzon50 []int64
for {
z.Add(pow, one)
d := k*n + 1
bd := big.NewInt(d)
if z.Rem(z, bd).Cmp(zero) == 0 {
if count < 50 {
curzon50 = append(curzon50, n)
}
count++
if count == 50 {
for i := 0; i < len(curzon50); i++ {
fmt.Printf("%4d ", curzon50[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Print("\nOne thousandth: ")
}
if count == 1000 {
fmt.Println(n)
break
}
}
n++
pow.Mul(pow, bk)
}
fmt.Println()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.