Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in Go as shown in this C++ implementation. | #include <cassert>
#include <vector>
#include <QImage>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
matrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
size_t arows = a.rows();
size_t acolumns = a.columns();
size_t brows = b.rows();
size_t bcolumns = b.columns();
matrix<scalar_type> c(arows * brows, acolumns * bcolumns);
for (size_t i = 0; i < arows; ++i)
for (size_t j = 0; j < acolumns; ++j)
for (size_t k = 0; k < brows; ++k)
for (size_t l = 0; l < bcolumns; ++l)
c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);
return c;
}
bool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {
matrix<unsigned char> result = m;
for (int i = 0; i < order; ++i)
result = kronecker_product(result, m);
size_t height = result.rows();
size_t width = result.columns();
size_t bytesPerLine = 4 * ((width + 3)/4);
std::vector<uchar> imageData(bytesPerLine * height);
for (size_t i = 0; i < height; ++i)
for (size_t j = 0; j < width; ++j)
imageData[i * bytesPerLine + j] = result(i, j);
QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);
QVector<QRgb> colours(2);
colours[0] = qRgb(0, 0, 0);
colours[1] = qRgb(255, 255, 255);
image.setColorTable(colours);
return image.save(fileName);
}
int main() {
matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});
matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});
matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});
kronecker_fractal("vicsek.png", matrix1, 5);
kronecker_fractal("sierpinski_carpet.png", matrix2, 5);
kronecker_fractal("sierpinski_triangle.png", matrix3, 8);
return 0;
}
| package main
import "fmt"
type matrix [][]int
func (m1 matrix) kroneckerProduct(m2 matrix) matrix {
m := len(m1)
n := len(m1[0])
p := len(m2)
q := len(m2[0])
rtn := m * p
ctn := n * q
r := make(matrix, rtn)
for i := range r {
r[i] = make([]int, ctn)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
for k := 0; k < p; k++ {
for l := 0; l < q; l++ {
r[p*i+k][q*j+l] = m1[i][j] * m2[k][l]
}
}
}
}
return r
}
func (m matrix) kroneckerPower(n int) matrix {
pow := m
for i := 1; i < n; i++ {
pow = pow.kroneckerProduct(m)
}
return pow
}
func (m matrix) print(text string) {
fmt.Println(text, "fractal :\n")
for i := range m {
for j := range m[0] {
if m[i][j] == 1 {
fmt.Print("*")
} else {
fmt.Print(" ")
}
}
fmt.Println()
}
fmt.Println()
}
func main() {
m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}
m1.kroneckerPower(4).print("Vivsek")
m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}
m2.kroneckerPower(4).print("Sierpinski carpet")
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace std;
using namespace boost;
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
static const char_separator<char> sep(" ","#;,");
struct configs{
string fullname;
string favoritefruit;
bool needspelling;
bool seedsremoved;
vector<string> otherfamily;
} conf;
void parseLine(const string &line, configs &conf)
{
if (line[0] == '#' || line.empty())
return;
Tokenizer tokenizer(line, sep);
vector<string> tokens;
for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)
tokens.push_back(*iter);
if (tokens[0] == ";"){
algorithm::to_lower(tokens[1]);
if (tokens[1] == "needspeeling")
conf.needspelling = false;
if (tokens[1] == "seedsremoved")
conf.seedsremoved = false;
}
algorithm::to_lower(tokens[0]);
if (tokens[0] == "needspeeling")
conf.needspelling = true;
if (tokens[0] == "seedsremoved")
conf.seedsremoved = true;
if (tokens[0] == "fullname"){
for (unsigned int i=1; i<tokens.size(); i++)
conf.fullname += tokens[i] + " ";
conf.fullname.erase(conf.fullname.size() -1, 1);
}
if (tokens[0] == "favouritefruit")
for (unsigned int i=1; i<tokens.size(); i++)
conf.favoritefruit += tokens[i];
if (tokens[0] == "otherfamily"){
unsigned int i=1;
string tmp;
while (i<=tokens.size()){
if ( i == tokens.size() || tokens[i] ==","){
tmp.erase(tmp.size()-1, 1);
conf.otherfamily.push_back(tmp);
tmp = "";
i++;
}
else{
tmp += tokens[i];
tmp += " ";
i++;
}
}
}
}
int _tmain(int argc, TCHAR* argv[])
{
if (argc != 2)
{
wstring tmp = argv[0];
wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl;
return -1;
}
ifstream file (argv[1]);
if (file.is_open())
while(file.good())
{
char line[255];
file.getline(line, 255);
string linestring(line);
parseLine(linestring, conf);
}
else
{
cout << "Unable to open the file" << endl;
return -2;
}
cout << "Fullname= " << conf.fullname << endl;
cout << "Favorite Fruit= " << conf.favoritefruit << endl;
cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl;
cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl;
string otherFamily;
for (unsigned int i = 0; i < conf.otherfamily.size(); i++)
otherFamily += conf.otherfamily[i] + ", ";
otherFamily.erase(otherFamily.size()-2, 2);
cout << "Other Family= " << otherFamily << endl;
return 0;
}
| package config
import (
"errors"
"io"
"fmt"
"bytes"
"strings"
"io/ioutil"
)
var (
ENONE = errors.New("Requested value does not exist")
EBADTYPE = errors.New("Requested type and actual type do not match")
EBADVAL = errors.New("Value and type do not match")
)
type varError struct {
err error
n string
t VarType
}
func (err *varError) Error() string {
return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t)
}
type VarType int
const (
Bool VarType = 1 + iota
Array
String
)
func (t VarType) String() string {
switch t {
case Bool:
return "Bool"
case Array:
return "Array"
case String:
return "String"
}
panic("Unknown VarType")
}
type confvar struct {
Type VarType
Val interface{}
}
type Config struct {
m map[string]confvar
}
func Parse(r io.Reader) (c *Config, err error) {
c = new(Config)
c.m = make(map[string]confvar)
buf, err := ioutil.ReadAll(r)
if err != nil {
return
}
lines := bytes.Split(buf, []byte{'\n'})
for _, line := range lines {
line = bytes.TrimSpace(line)
if len(line) == 0 {
continue
}
switch line[0] {
case '#', ';':
continue
}
parts := bytes.SplitN(line, []byte{' '}, 2)
nam := string(bytes.ToLower(parts[0]))
if len(parts) == 1 {
c.m[nam] = confvar{Bool, true}
continue
}
if strings.Contains(string(parts[1]), ",") {
tmpB := bytes.Split(parts[1], []byte{','})
for i := range tmpB {
tmpB[i] = bytes.TrimSpace(tmpB[i])
}
tmpS := make([]string, 0, len(tmpB))
for i := range tmpB {
tmpS = append(tmpS, string(tmpB[i]))
}
c.m[nam] = confvar{Array, tmpS}
continue
}
c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))}
}
return
}
func (c *Config) Bool(name string) (bool, error) {
name = strings.ToLower(name)
if _, ok := c.m[name]; !ok {
return false, nil
}
if c.m[name].Type != Bool {
return false, &varError{EBADTYPE, name, Bool}
}
v, ok := c.m[name].Val.(bool)
if !ok {
return false, &varError{EBADVAL, name, Bool}
}
return v, nil
}
func (c *Config) Array(name string) ([]string, error) {
name = strings.ToLower(name)
if _, ok := c.m[name]; !ok {
return nil, &varError{ENONE, name, Array}
}
if c.m[name].Type != Array {
return nil, &varError{EBADTYPE, name, Array}
}
v, ok := c.m[name].Val.([]string)
if !ok {
return nil, &varError{EBADVAL, name, Array}
}
return v, nil
}
func (c *Config) String(name string) (string, error) {
name = strings.ToLower(name)
if _, ok := c.m[name]; !ok {
return "", &varError{ENONE, name, String}
}
if c.m[name].Type != String {
return "", &varError{EBADTYPE, name, String}
}
v, ok := c.m[name].Val.(string)
if !ok {
return "", &varError{EBADVAL, name, String}
}
return v, nil
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <algorithm>
#include <string>
#include <cctype>
struct icompare_char {
bool operator()(char c1, char c2) {
return std::toupper(c1) < std::toupper(c2);
}
};
struct compare {
bool operator()(std::string const& s1, std::string const& s2) {
if (s1.length() > s2.length())
return true;
if (s1.length() < s2.length())
return false;
return std::lexicographical_compare(s1.begin(), s1.end(),
s2.begin(), s2.end(),
icompare_char());
}
};
int main() {
std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
std::sort(strings, strings+8, compare());
return 0;
}
| package main
import (
"fmt"
"sort"
"strings"
)
type sortable []string
func (s sortable) Len() int { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
a, b := s[i], s[j]
if len(a) != len(b) {
return len(a) > len(b)
}
return strings.ToLower(a) < strings.ToLower(b)
}
func main() {
var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
fmt.Println(s, "(original)")
sort.Sort(s)
fmt.Println(s, "(sorted)")
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_prime(const integer& n, int reps = 50) {
return mpz_probab_prime_p(n.get_mpz_t(), reps);
}
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
return out.str();
}
bool is_circular_prime(const integer& p) {
if (!is_prime(p))
return false;
std::string str(to_string(p));
for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {
std::rotate(str.begin(), str.begin() + 1, str.end());
integer p2(str, 10);
if (p2 < p || !is_prime(p2))
return false;
}
return true;
}
integer next_repunit(const integer& n) {
integer p = 1;
while (p < n)
p = 10 * p + 1;
return p;
}
integer repunit(int digits) {
std::string str(digits, '1');
integer p(str);
return p;
}
void test_repunit(int digits) {
if (is_prime(repunit(digits), 10))
std::cout << "R(" << digits << ") is probably prime\n";
else
std::cout << "R(" << digits << ") is not prime\n";
}
int main() {
integer p = 2;
std::cout << "First 19 circular primes:\n";
for (int count = 0; count < 19; ++p) {
if (is_circular_prime(p)) {
if (count > 0)
std::cout << ", ";
std::cout << p;
++count;
}
}
std::cout << '\n';
std::cout << "Next 4 circular primes:\n";
p = next_repunit(p);
std::string str(to_string(p));
int digits = str.size();
for (int count = 0; count < 4; ) {
if (is_prime(p, 15)) {
if (count > 0)
std::cout << ", ";
std::cout << "R(" << digits << ")";
++count;
}
p = repunit(++digits);
}
std::cout << '\n';
test_repunit(5003);
test_repunit(9887);
test_repunit(15073);
test_repunit(25031);
test_repunit(35317);
test_repunit(49081);
return 0;
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"strings"
)
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func repunit(n int) *big.Int {
ones := strings.Repeat("1", n)
b, _ := new(big.Int).SetString(ones, 10)
return b
}
var circs = []int{}
func alreadyFound(n int) bool {
for _, i := range circs {
if i == n {
return true
}
}
return false
}
func isCircular(n int) bool {
nn := n
pow := 1
for nn > 0 {
pow *= 10
nn /= 10
}
nn = n
for {
nn *= 10
f := nn / pow
nn += f * (1 - pow)
if alreadyFound(nn) {
return false
}
if nn == n {
break
}
if !isPrime(nn) {
return false
}
}
return true
}
func main() {
fmt.Println("The first 19 circular primes are:")
digits := [4]int{1, 3, 7, 9}
q := []int{1, 2, 3, 5, 7, 9}
fq := []int{1, 2, 3, 5, 7, 9}
count := 0
for {
f := q[0]
fd := fq[0]
if isPrime(f) && isCircular(f) {
circs = append(circs, f)
count++
if count == 19 {
break
}
}
copy(q, q[1:])
q = q[:len(q)-1]
copy(fq, fq[1:])
fq = fq[:len(fq)-1]
if f == 2 || f == 5 {
continue
}
for _, d := range digits {
if d >= fd {
q = append(q, f*10+d)
fq = append(fq, fd)
}
}
}
fmt.Println(circs)
fmt.Println("\nThe next 4 circular primes, in repunit format, are:")
count = 0
var rus []string
for i := 7; count < 4; i++ {
if repunit(i).ProbablyPrime(10) {
count++
rus = append(rus, fmt.Sprintf("R(%d)", i))
}
}
fmt.Println(rus)
fmt.Println("\nThe following repunits are probably circular primes:")
for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} {
fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10))
}
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include "animationwidget.h"
#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {
setWindowTitle(tr("Animation"));
QFont font("Courier", 24);
QLabel* label = new QLabel("Hello World! ");
label->setFont(font);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(label);
QTimer* timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [label,this]() {
QString text = label->text();
std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());
label->setText(text);
});
timer->start(200);
}
void AnimationWidget::mousePressEvent(QMouseEvent*) {
right_ = !right_;
}
| package main
import (
"log"
"time"
"github.com/gdamore/tcell"
)
const (
msg = "Hello World! "
x0, y0 = 8, 3
shiftsPerSecond = 4
clicksToExit = 5
)
func main() {
s, err := tcell.NewScreen()
if err != nil {
log.Fatal(err)
}
if err = s.Init(); err != nil {
log.Fatal(err)
}
s.Clear()
s.EnableMouse()
tick := time.Tick(time.Second / shiftsPerSecond)
click := make(chan bool)
go func() {
for {
em, ok := s.PollEvent().(*tcell.EventMouse)
if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
continue
}
mx, my := em.Position()
if my == y0 && mx >= x0 && mx < x0+len(msg) {
click <- true
}
}
}()
for inc, shift, clicks := 1, 0, 0; ; {
select {
case <-tick:
shift = (shift + inc) % len(msg)
for i, r := range msg {
s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
}
s.Show()
case <-click:
clicks++
if clicks == clicksToExit {
s.Fini()
return
}
inc = len(msg) - inc
}
}
}
|
Generate an equivalent Go version of this C++ code. | #include <algorithm>
#include <iostream>
#include <iterator>
class radix_test
{
const int bit;
public:
radix_test(int offset) : bit(offset) {}
bool operator()(int value) const
{
if (bit == 31)
return value < 0;
else
return !(value & (1 << bit));
}
};
void lsd_radix_sort(int *first, int *last)
{
for (int lsb = 0; lsb < 32; ++lsb)
{
std::stable_partition(first, last, radix_test(lsb));
}
}
void msd_radix_sort(int *first, int *last, int msb = 31)
{
if (first != last && msb >= 0)
{
int *mid = std::partition(first, last, radix_test(msb));
msb--;
msd_radix_sort(first, mid, msb);
msd_radix_sort(mid, last, msb);
}
}
int main()
{
int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };
lsd_radix_sort(data, data + 8);
std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " "));
return 0;
}
| package main
import (
"bytes"
"encoding/binary"
"fmt"
)
type word int32
const wordLen = 4
const highBit = -1 << 31
var data = []word{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
buf := bytes.NewBuffer(nil)
ds := make([][]byte, len(data))
for i, x := range data {
binary.Write(buf, binary.LittleEndian, x^highBit)
b := make([]byte, wordLen)
buf.Read(b)
ds[i] = b
}
bins := make([][][]byte, 256)
for i := 0; i < wordLen; i++ {
for _, b := range ds {
bins[b[i]] = append(bins[b[i]], b)
}
j := 0
for k, bs := range bins {
copy(ds[j:], bs)
j += len(bs)
bins[k] = bs[:0]
}
}
fmt.Println("original:", data)
var w word
for i, b := range ds {
buf.Write(b)
binary.Read(buf, binary.LittleEndian, &w)
data[i] = w^highBit
}
fmt.Println("sorted: ", data)
}
|
Write the same code in Go as shown below in C++. | #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <algorithm>
#include <iterator>
#include <iostream>
template<typename ForwardIterator> void selection_sort(ForwardIterator begin,
ForwardIterator end) {
for(auto i = begin; i != end; ++i) {
std::iter_swap(i, std::min_element(i, end));
}
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
selection_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
selectionSort(a)
fmt.Println("after: ", a)
}
func selectionSort(a []int) {
last := len(a) - 1
for i := 0; i < last; i++ {
aMin := a[i]
iMin := i
for j := i + 1; j < len(a); j++ {
if a[j] < aMin {
aMin = a[j]
iMin = j
}
}
a[i], a[iMin] = aMin, a[i]
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t;
}
std::swap(n, k);
if (n % 4 == 3 && k % 4 == 3)
t = -t;
n %= k;
}
return k == 1 ? t : 0;
}
void print_table(std::ostream& out, int kmax, int nmax) {
out << "n\\k|";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << k;
out << "\n----";
for (int k = 0; k <= kmax; ++k)
out << "---";
out << '\n';
for (int n = 1; n <= nmax; n += 2) {
out << std::setw(2) << n << " |";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << jacobi(k, n);
out << '\n';
}
}
int main() {
print_table(std::cout, 20, 21);
return 0;
}
| package main
import (
"fmt"
"log"
"math/big"
)
func jacobi(a, n uint64) int {
if n%2 == 0 {
log.Fatal("'n' must be a positive odd integer")
}
a %= n
result := 1
for a != 0 {
for a%2 == 0 {
a /= 2
nn := n % 8
if nn == 3 || nn == 5 {
result = -result
}
}
a, n = n, a
if a%4 == 3 && n%4 == 3 {
result = -result
}
a %= n
}
if n == 1 {
return result
}
return 0
}
func main() {
fmt.Println("Using hand-coded version:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
fmt.Printf(" % d", jacobi(a, n))
}
fmt.Println()
}
ba, bn := new(big.Int), new(big.Int)
fmt.Println("\nUsing standard library function:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
ba.SetUint64(a)
bn.SetUint64(n)
fmt.Printf(" % d", big.Jacobi(ba, bn))
}
fmt.Println()
}
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t;
}
std::swap(n, k);
if (n % 4 == 3 && k % 4 == 3)
t = -t;
n %= k;
}
return k == 1 ? t : 0;
}
void print_table(std::ostream& out, int kmax, int nmax) {
out << "n\\k|";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << k;
out << "\n----";
for (int k = 0; k <= kmax; ++k)
out << "---";
out << '\n';
for (int n = 1; n <= nmax; n += 2) {
out << std::setw(2) << n << " |";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << jacobi(k, n);
out << '\n';
}
}
int main() {
print_table(std::cout, 20, 21);
return 0;
}
| package main
import (
"fmt"
"log"
"math/big"
)
func jacobi(a, n uint64) int {
if n%2 == 0 {
log.Fatal("'n' must be a positive odd integer")
}
a %= n
result := 1
for a != 0 {
for a%2 == 0 {
a /= 2
nn := n % 8
if nn == 3 || nn == 5 {
result = -result
}
}
a, n = n, a
if a%4 == 3 && n%4 == 3 {
result = -result
}
a %= n
}
if n == 1 {
return result
}
return 0
}
func main() {
fmt.Println("Using hand-coded version:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
fmt.Printf(" % d", jacobi(a, n))
}
fmt.Println()
}
ba, bn := new(big.Int), new(big.Int)
fmt.Println("\nUsing standard library function:")
fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9")
fmt.Println("---------------------------------")
for n := uint64(1); n <= 17; n += 2 {
fmt.Printf("%2d ", n)
for a := uint64(0); a <= 9; a++ {
ba.SetUint64(a)
bn.SetUint64(n)
fmt.Printf(" % d", big.Jacobi(ba, bn))
}
fmt.Println()
}
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
template<typename coordinate_type, size_t dimensions>
class point {
public:
point(std::array<coordinate_type, dimensions> c) : coords_(c) {}
point(std::initializer_list<coordinate_type> list) {
size_t n = std::min(dimensions, list.size());
std::copy_n(list.begin(), n, coords_.begin());
}
coordinate_type get(size_t index) const {
return coords_[index];
}
double distance(const point& pt) const {
double dist = 0;
for (size_t i = 0; i < dimensions; ++i) {
double d = get(i) - pt.get(i);
dist += d * d;
}
return dist;
}
private:
std::array<coordinate_type, dimensions> coords_;
};
template<typename coordinate_type, size_t dimensions>
std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {
out << '(';
for (size_t i = 0; i < dimensions; ++i) {
if (i > 0)
out << ", ";
out << pt.get(i);
}
out << ')';
return out;
}
template<typename coordinate_type, size_t dimensions>
class kdtree {
public:
typedef point<coordinate_type, dimensions> point_type;
private:
struct node {
node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}
coordinate_type get(size_t index) const {
return point_.get(index);
}
double distance(const point_type& pt) const {
return point_.distance(pt);
}
point_type point_;
node* left_;
node* right_;
};
node* root_ = nullptr;
node* best_ = nullptr;
double best_dist_ = 0;
size_t visited_ = 0;
std::vector<node> nodes_;
struct node_cmp {
node_cmp(size_t index) : index_(index) {}
bool operator()(const node& n1, const node& n2) const {
return n1.point_.get(index_) < n2.point_.get(index_);
}
size_t index_;
};
node* make_tree(size_t begin, size_t end, size_t index) {
if (end <= begin)
return nullptr;
size_t n = begin + (end - begin)/2;
auto i = nodes_.begin();
std::nth_element(i + begin, i + n, i + end, node_cmp(index));
index = (index + 1) % dimensions;
nodes_[n].left_ = make_tree(begin, n, index);
nodes_[n].right_ = make_tree(n + 1, end, index);
return &nodes_[n];
}
void nearest(node* root, const point_type& point, size_t index) {
if (root == nullptr)
return;
++visited_;
double d = root->distance(point);
if (best_ == nullptr || d < best_dist_) {
best_dist_ = d;
best_ = root;
}
if (best_dist_ == 0)
return;
double dx = root->get(index) - point.get(index);
index = (index + 1) % dimensions;
nearest(dx > 0 ? root->left_ : root->right_, point, index);
if (dx * dx >= best_dist_)
return;
nearest(dx > 0 ? root->right_ : root->left_, point, index);
}
public:
kdtree(const kdtree&) = delete;
kdtree& operator=(const kdtree&) = delete;
template<typename iterator>
kdtree(iterator begin, iterator end) : nodes_(begin, end) {
root_ = make_tree(0, nodes_.size(), 0);
}
template<typename func>
kdtree(func&& f, size_t n) {
nodes_.reserve(n);
for (size_t i = 0; i < n; ++i)
nodes_.push_back(f());
root_ = make_tree(0, nodes_.size(), 0);
}
bool empty() const { return nodes_.empty(); }
size_t visited() const { return visited_; }
double distance() const { return std::sqrt(best_dist_); }
const point_type& nearest(const point_type& pt) {
if (root_ == nullptr)
throw std::logic_error("tree is empty");
best_ = nullptr;
visited_ = 0;
best_dist_ = 0;
nearest(root_, pt, 0);
return best_->point_;
}
};
void test_wikipedia() {
typedef point<int, 2> point2d;
typedef kdtree<int, 2> tree2d;
point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };
tree2d tree(std::begin(points), std::end(points));
point2d n = tree.nearest({ 9, 2 });
std::cout << "Wikipedia example data:\n";
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
typedef point<double, 3> point3d;
typedef kdtree<double, 3> tree3d;
struct random_point_generator {
random_point_generator(double min, double max)
: engine_(std::random_device()()), distribution_(min, max) {}
point3d operator()() {
double x = distribution_(engine_);
double y = distribution_(engine_);
double z = distribution_(engine_);
return point3d({x, y, z});
}
std::mt19937 engine_;
std::uniform_real_distribution<double> distribution_;
};
void test_random(size_t count) {
random_point_generator rpg(0, 1);
tree3d tree(rpg, count);
point3d pt(rpg());
point3d n = tree.nearest(pt);
std::cout << "Random data (" << count << " points):\n";
std::cout << "point: " << pt << '\n';
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
int main() {
try {
test_wikipedia();
std::cout << '\n';
test_random(1000);
std::cout << '\n';
test_random(1000000);
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
return 0;
}
|
package main
import (
"fmt"
"math"
"math/rand"
"sort"
"time"
)
type point []float64
func (p point) sqd(q point) float64 {
var sum float64
for dim, pCoord := range p {
d := pCoord - q[dim]
sum += d * d
}
return sum
}
type kdNode struct {
domElt point
split int
left, right *kdNode
}
type kdTree struct {
n *kdNode
bounds hyperRect
}
type hyperRect struct {
min, max point
}
func (hr hyperRect) copy() hyperRect {
return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}
}
func newKd(pts []point, bounds hyperRect) kdTree {
var nk2 func([]point, int) *kdNode
nk2 = func(exset []point, split int) *kdNode {
if len(exset) == 0 {
return nil
}
sort.Sort(part{exset, split})
m := len(exset) / 2
d := exset[m]
for m+1 < len(exset) && exset[m+1][split] == d[split] {
m++
}
s2 := split + 1
if s2 == len(d) {
s2 = 0
}
return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}
}
return kdTree{nk2(pts, 0), bounds}
}
type part struct {
pts []point
dPart int
}
func (p part) Len() int { return len(p.pts) }
func (p part) Less(i, j int) bool {
return p.pts[i][p.dPart] < p.pts[j][p.dPart]
}
func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }
func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {
return nn(t.n, p, t.bounds, math.Inf(1))
}
func nn(kd *kdNode, target point, hr hyperRect,
maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {
if kd == nil {
return nil, math.Inf(1), 0
}
nodesVisited++
s := kd.split
pivot := kd.domElt
leftHr := hr.copy()
rightHr := hr.copy()
leftHr.max[s] = pivot[s]
rightHr.min[s] = pivot[s]
targetInLeft := target[s] <= pivot[s]
var nearerKd, furtherKd *kdNode
var nearerHr, furtherHr hyperRect
if targetInLeft {
nearerKd, nearerHr = kd.left, leftHr
furtherKd, furtherHr = kd.right, rightHr
} else {
nearerKd, nearerHr = kd.right, rightHr
furtherKd, furtherHr = kd.left, leftHr
}
var nv int
nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)
nodesVisited += nv
if distSqd < maxDistSqd {
maxDistSqd = distSqd
}
d := pivot[s] - target[s]
d *= d
if d > maxDistSqd {
return
}
if d = pivot.sqd(target); d < distSqd {
nearest = pivot
distSqd = d
maxDistSqd = distSqd
}
tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)
nodesVisited += nv
if tempSqd < distSqd {
nearest = tempNearest
distSqd = tempSqd
}
return
}
func main() {
rand.Seed(time.Now().Unix())
kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},
hyperRect{point{0, 0}, point{10, 10}})
showNearest("WP example data", kd, point{9, 2})
kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})
showNearest("1000 random 3d points", kd, randomPt(3))
}
func randomPt(dim int) point {
p := make(point, dim)
for d := range p {
p[d] = rand.Float64()
}
return p
}
func randomPts(dim, n int) []point {
p := make([]point, n)
for i := range p {
p[i] = randomPt(dim)
}
return p
}
func showNearest(heading string, kd kdTree, p point) {
fmt.Println()
fmt.Println(heading)
fmt.Println("point: ", p)
nn, ssq, nv := kd.nearest(p)
fmt.Println("nearest neighbor:", nn)
fmt.Println("distance: ", math.Sqrt(ssq))
fmt.Println("nodes visited: ", nv)
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
template<typename coordinate_type, size_t dimensions>
class point {
public:
point(std::array<coordinate_type, dimensions> c) : coords_(c) {}
point(std::initializer_list<coordinate_type> list) {
size_t n = std::min(dimensions, list.size());
std::copy_n(list.begin(), n, coords_.begin());
}
coordinate_type get(size_t index) const {
return coords_[index];
}
double distance(const point& pt) const {
double dist = 0;
for (size_t i = 0; i < dimensions; ++i) {
double d = get(i) - pt.get(i);
dist += d * d;
}
return dist;
}
private:
std::array<coordinate_type, dimensions> coords_;
};
template<typename coordinate_type, size_t dimensions>
std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {
out << '(';
for (size_t i = 0; i < dimensions; ++i) {
if (i > 0)
out << ", ";
out << pt.get(i);
}
out << ')';
return out;
}
template<typename coordinate_type, size_t dimensions>
class kdtree {
public:
typedef point<coordinate_type, dimensions> point_type;
private:
struct node {
node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}
coordinate_type get(size_t index) const {
return point_.get(index);
}
double distance(const point_type& pt) const {
return point_.distance(pt);
}
point_type point_;
node* left_;
node* right_;
};
node* root_ = nullptr;
node* best_ = nullptr;
double best_dist_ = 0;
size_t visited_ = 0;
std::vector<node> nodes_;
struct node_cmp {
node_cmp(size_t index) : index_(index) {}
bool operator()(const node& n1, const node& n2) const {
return n1.point_.get(index_) < n2.point_.get(index_);
}
size_t index_;
};
node* make_tree(size_t begin, size_t end, size_t index) {
if (end <= begin)
return nullptr;
size_t n = begin + (end - begin)/2;
auto i = nodes_.begin();
std::nth_element(i + begin, i + n, i + end, node_cmp(index));
index = (index + 1) % dimensions;
nodes_[n].left_ = make_tree(begin, n, index);
nodes_[n].right_ = make_tree(n + 1, end, index);
return &nodes_[n];
}
void nearest(node* root, const point_type& point, size_t index) {
if (root == nullptr)
return;
++visited_;
double d = root->distance(point);
if (best_ == nullptr || d < best_dist_) {
best_dist_ = d;
best_ = root;
}
if (best_dist_ == 0)
return;
double dx = root->get(index) - point.get(index);
index = (index + 1) % dimensions;
nearest(dx > 0 ? root->left_ : root->right_, point, index);
if (dx * dx >= best_dist_)
return;
nearest(dx > 0 ? root->right_ : root->left_, point, index);
}
public:
kdtree(const kdtree&) = delete;
kdtree& operator=(const kdtree&) = delete;
template<typename iterator>
kdtree(iterator begin, iterator end) : nodes_(begin, end) {
root_ = make_tree(0, nodes_.size(), 0);
}
template<typename func>
kdtree(func&& f, size_t n) {
nodes_.reserve(n);
for (size_t i = 0; i < n; ++i)
nodes_.push_back(f());
root_ = make_tree(0, nodes_.size(), 0);
}
bool empty() const { return nodes_.empty(); }
size_t visited() const { return visited_; }
double distance() const { return std::sqrt(best_dist_); }
const point_type& nearest(const point_type& pt) {
if (root_ == nullptr)
throw std::logic_error("tree is empty");
best_ = nullptr;
visited_ = 0;
best_dist_ = 0;
nearest(root_, pt, 0);
return best_->point_;
}
};
void test_wikipedia() {
typedef point<int, 2> point2d;
typedef kdtree<int, 2> tree2d;
point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };
tree2d tree(std::begin(points), std::end(points));
point2d n = tree.nearest({ 9, 2 });
std::cout << "Wikipedia example data:\n";
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
typedef point<double, 3> point3d;
typedef kdtree<double, 3> tree3d;
struct random_point_generator {
random_point_generator(double min, double max)
: engine_(std::random_device()()), distribution_(min, max) {}
point3d operator()() {
double x = distribution_(engine_);
double y = distribution_(engine_);
double z = distribution_(engine_);
return point3d({x, y, z});
}
std::mt19937 engine_;
std::uniform_real_distribution<double> distribution_;
};
void test_random(size_t count) {
random_point_generator rpg(0, 1);
tree3d tree(rpg, count);
point3d pt(rpg());
point3d n = tree.nearest(pt);
std::cout << "Random data (" << count << " points):\n";
std::cout << "point: " << pt << '\n';
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
int main() {
try {
test_wikipedia();
std::cout << '\n';
test_random(1000);
std::cout << '\n';
test_random(1000000);
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
return 0;
}
|
package main
import (
"fmt"
"math"
"math/rand"
"sort"
"time"
)
type point []float64
func (p point) sqd(q point) float64 {
var sum float64
for dim, pCoord := range p {
d := pCoord - q[dim]
sum += d * d
}
return sum
}
type kdNode struct {
domElt point
split int
left, right *kdNode
}
type kdTree struct {
n *kdNode
bounds hyperRect
}
type hyperRect struct {
min, max point
}
func (hr hyperRect) copy() hyperRect {
return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)}
}
func newKd(pts []point, bounds hyperRect) kdTree {
var nk2 func([]point, int) *kdNode
nk2 = func(exset []point, split int) *kdNode {
if len(exset) == 0 {
return nil
}
sort.Sort(part{exset, split})
m := len(exset) / 2
d := exset[m]
for m+1 < len(exset) && exset[m+1][split] == d[split] {
m++
}
s2 := split + 1
if s2 == len(d) {
s2 = 0
}
return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)}
}
return kdTree{nk2(pts, 0), bounds}
}
type part struct {
pts []point
dPart int
}
func (p part) Len() int { return len(p.pts) }
func (p part) Less(i, j int) bool {
return p.pts[i][p.dPart] < p.pts[j][p.dPart]
}
func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] }
func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) {
return nn(t.n, p, t.bounds, math.Inf(1))
}
func nn(kd *kdNode, target point, hr hyperRect,
maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) {
if kd == nil {
return nil, math.Inf(1), 0
}
nodesVisited++
s := kd.split
pivot := kd.domElt
leftHr := hr.copy()
rightHr := hr.copy()
leftHr.max[s] = pivot[s]
rightHr.min[s] = pivot[s]
targetInLeft := target[s] <= pivot[s]
var nearerKd, furtherKd *kdNode
var nearerHr, furtherHr hyperRect
if targetInLeft {
nearerKd, nearerHr = kd.left, leftHr
furtherKd, furtherHr = kd.right, rightHr
} else {
nearerKd, nearerHr = kd.right, rightHr
furtherKd, furtherHr = kd.left, leftHr
}
var nv int
nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd)
nodesVisited += nv
if distSqd < maxDistSqd {
maxDistSqd = distSqd
}
d := pivot[s] - target[s]
d *= d
if d > maxDistSqd {
return
}
if d = pivot.sqd(target); d < distSqd {
nearest = pivot
distSqd = d
maxDistSqd = distSqd
}
tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd)
nodesVisited += nv
if tempSqd < distSqd {
nearest = tempNearest
distSqd = tempSqd
}
return
}
func main() {
rand.Seed(time.Now().Unix())
kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}},
hyperRect{point{0, 0}, point{10, 10}})
showNearest("WP example data", kd, point{9, 2})
kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}})
showNearest("1000 random 3d points", kd, randomPt(3))
}
func randomPt(dim int) point {
p := make(point, dim)
for d := range p {
p[d] = rand.Float64()
}
return p
}
func randomPts(dim, n int) []point {
p := make([]point, n)
for i := range p {
p[i] = randomPt(dim)
}
return p
}
func showNearest(heading string, kd kdTree, p point) {
fmt.Println()
fmt.Println(heading)
fmt.Println("point: ", p)
nn, ssq, nv := kd.nearest(p)
fmt.Println("nearest neighbor:", nn)
fmt.Println("distance: ", math.Sqrt(ssq))
fmt.Println("nodes visited: ", nv)
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <iostream>
#include <algorithm>
void print_square(int i) {
std::cout << i*i << " ";
}
int main() {
int ary[]={1,2,3,4,5};
std::for_each(ary,ary+5,print_square);
return 0;
}
| package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <stdexcept>
template <typename Self>
class singleton
{
protected:
static Self*
sentry;
public:
static Self&
instance()
{
return *sentry;
}
singleton()
{
if(sentry)
throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
sentry = (Self*)this;
}
virtual ~singleton()
{
if(sentry == this)
sentry = 0;
}
};
template <typename Self>
Self*
singleton<Self>::sentry = 0;
#include <iostream>
#include <string>
using namespace
std;
class controller : public singleton<controller>
{
public:
controller(string const& name)
: name(name)
{
trace("begin");
}
~controller()
{
trace("end");
}
void
work()
{
trace("doing stuff");
}
void
trace(string const& message)
{
cout << name << ": " << message << endl;
}
string
name;
};
int
main()
{
controller*
first = new controller("first");
controller::instance().work();
delete first;
controller
second("second");
controller::instance().work();
try
{
controller
goner("goner");
controller::instance().work();
}
catch(exception const& error)
{
cout << error.what() << endl;
}
controller::instance().work();
controller
goner("goner");
controller::instance().work();
}
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
var (
instance string
once sync.Once
)
func claim(color string, w *sync.WaitGroup) {
time.Sleep(time.Duration(rand.Intn(1e8)))
log.Println("trying to claim", color)
once.Do(func() { instance = color })
log.Printf("tried %s. instance: %s", color, instance)
w.Done()
}
func main() {
rand.Seed(time.Now().Unix())
var w sync.WaitGroup
w.Add(2)
go claim("red", &w)
go claim("blue", &w)
w.Wait()
log.Println("after trying both, instance =", instance)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <stdexcept>
template <typename Self>
class singleton
{
protected:
static Self*
sentry;
public:
static Self&
instance()
{
return *sentry;
}
singleton()
{
if(sentry)
throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
sentry = (Self*)this;
}
virtual ~singleton()
{
if(sentry == this)
sentry = 0;
}
};
template <typename Self>
Self*
singleton<Self>::sentry = 0;
#include <iostream>
#include <string>
using namespace
std;
class controller : public singleton<controller>
{
public:
controller(string const& name)
: name(name)
{
trace("begin");
}
~controller()
{
trace("end");
}
void
work()
{
trace("doing stuff");
}
void
trace(string const& message)
{
cout << name << ": " << message << endl;
}
string
name;
};
int
main()
{
controller*
first = new controller("first");
controller::instance().work();
delete first;
controller
second("second");
controller::instance().work();
try
{
controller
goner("goner");
controller::instance().work();
}
catch(exception const& error)
{
cout << error.what() << endl;
}
controller::instance().work();
controller
goner("goner");
controller::instance().work();
}
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
var (
instance string
once sync.Once
)
func claim(color string, w *sync.WaitGroup) {
time.Sleep(time.Duration(rand.Intn(1e8)))
log.Println("trying to claim", color)
once.Do(func() { instance = color })
log.Printf("tried %s. instance: %s", color, instance)
w.Done()
}
func main() {
rand.Seed(time.Now().Unix())
var w sync.WaitGroup
w.Add(2)
go claim("red", &w)
go claim("blue", &w)
w.Wait()
log.Println("after trying both, instance =", instance)
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iostream>
#include <tuple>
union conv {
int i;
float f;
};
float nextUp(float d) {
if (isnan(d) || d == -INFINITY || d == INFINITY) return d;
if (d == 0.0) return FLT_EPSILON;
conv c;
c.f = d;
c.i++;
return c.f;
}
float nextDown(float d) {
if (isnan(d) || d == -INFINITY || d == INFINITY) return d;
if (d == 0.0) return -FLT_EPSILON;
conv c;
c.f = d;
c.i--;
return c.f;
}
auto safeAdd(float a, float b) {
return std::make_tuple(nextDown(a + b), nextUp(a + b));
}
int main() {
float a = 1.20f;
float b = 0.03f;
auto result = safeAdd(a, b);
printf("(%f + %f) is in the range (%0.16f, %0.16f)\n", a, b, std::get<0>(result), std::get<1>(result));
return 0;
}
| package main
import (
"fmt"
"math"
)
type interval struct {
lower, upper float64
}
func stepAway(x float64) interval {
return interval {
math.Nextafter(x, math.Inf(-1)),
math.Nextafter(x, math.Inf(1))}
}
func safeAdd(a, b float64) interval {
return stepAway(a + b)
}
func main() {
a, b := 1.2, .03
fmt.Println(a, b, safeAdd(a, b))
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <iostream>
#include <string>
using namespace std;
int main() {
string dog = "Benjamin", Dog = "Samba", DOG = "Bernie";
cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl;
}
| package dogs
import "fmt"
var dog = "Salt"
var Dog = "Pepper"
var DOG = "Mustard"
func PackageSees() map[*string]int {
fmt.Println("Package sees:", dog, Dog, DOG)
return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | for(int i = 10; i >= 0; --i)
std::cout << i << "\n";
| for i := 10; i >= 0; i-- {
fmt.Println(i)
}
|
Write the same code in Go as shown below in C++. | #include <fstream>
using namespace std;
int main()
{
ofstream file("new.txt");
file << "this is a string";
file.close();
return 0;
}
| import "io/ioutil"
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}
|
Write a version of this C++ function in Go with identical behavior. | for(int i = 0; i < 5; ++i) {
for(int j = 0; j < i; ++j)
std::cout.put('*');
std::cout.put('\n');
}
| package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("*")
}
fmt.Printf("\n")
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <iostream>
#include <cstdint>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
class palindrome_generator {
public:
palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),
digit_(digit), even_(false) {}
integer next_palindrome() {
++next_;
if (next_ == power_ * (digit_ + 1)) {
if (even_)
power_ *= 10;
next_ = digit_ * power_;
even_ = !even_;
}
return next_ * (even_ ? 10 * power_ : power_)
+ reverse(even_ ? next_ : next_/10);
}
private:
integer power_;
integer next_;
int digit_;
bool even_;
};
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
template<size_t len>
void print(integer (&array)[9][len]) {
for (int digit = 1; digit < 10; ++digit) {
std::cout << digit << ":";
for (int i = 0; i < len; ++i)
std::cout << ' ' << array[digit - 1][i];
std::cout << '\n';
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palindrome_generator pgen(digit);
for (int i = 0; i < m2; ) {
integer n = pgen.next_palindrome();
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n";
print(pg1);
std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n";
print(pg2);
std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n";
print(pg3);
return 0;
}
| package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func ord(n uint) string {
var suffix string
if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {
suffix = "th"
} else {
switch n % 10 {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
default:
suffix = "th"
}
}
return fmt.Sprintf("%s%s", commatize(n), suffix)
}
func main() {
const max = 10_000_000
data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},
{1e6, 1e6, 16}, {1e7, 1e7, 18}}
results := make(map[uint][]uint64)
for _, d := range data {
for i := d[0]; i <= d[1]; i++ {
results[i] = make([]uint64, 9)
}
}
var p uint64
outer:
for d := uint64(1); d < 10; d++ {
count := uint(0)
pow := uint64(1)
fl := d * 11
for nd := 3; nd < 20; nd++ {
slim := (d + 1) * pow
for s := d * pow; s < slim; s++ {
e := reverse(s)
mlim := uint64(1)
if nd%2 == 1 {
mlim = 10
}
for m := uint64(0); m < mlim; m++ {
if nd%2 == 0 {
p = s*pow*10 + e
} else {
p = s*pow*100 + m*pow*10 + e
}
if p%fl == 0 {
count++
if _, ok := results[count]; ok {
results[count][d-1] = p
}
if count == max {
continue outer
}
}
}
}
if nd%2 == 1 {
pow *= 10
}
}
}
for _, d := range data {
if d[0] != d[1] {
fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1]))
} else {
fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0]))
}
for i := 1; i <= 9; i++ {
fmt.Printf("%d: ", i)
for j := d[0]; j <= d[1]; j++ {
fmt.Printf("%*d ", d[2], results[j][i-1])
}
fmt.Println()
}
fmt.Println()
}
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <iostream>
#include <cstdint>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
class palindrome_generator {
public:
palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),
digit_(digit), even_(false) {}
integer next_palindrome() {
++next_;
if (next_ == power_ * (digit_ + 1)) {
if (even_)
power_ *= 10;
next_ = digit_ * power_;
even_ = !even_;
}
return next_ * (even_ ? 10 * power_ : power_)
+ reverse(even_ ? next_ : next_/10);
}
private:
integer power_;
integer next_;
int digit_;
bool even_;
};
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
template<size_t len>
void print(integer (&array)[9][len]) {
for (int digit = 1; digit < 10; ++digit) {
std::cout << digit << ":";
for (int i = 0; i < len; ++i)
std::cout << ' ' << array[digit - 1][i];
std::cout << '\n';
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palindrome_generator pgen(digit);
for (int i = 0; i < m2; ) {
integer n = pgen.next_palindrome();
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n";
print(pg1);
std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n";
print(pg2);
std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n";
print(pg3);
return 0;
}
| package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func ord(n uint) string {
var suffix string
if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {
suffix = "th"
} else {
switch n % 10 {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
default:
suffix = "th"
}
}
return fmt.Sprintf("%s%s", commatize(n), suffix)
}
func main() {
const max = 10_000_000
data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},
{1e6, 1e6, 16}, {1e7, 1e7, 18}}
results := make(map[uint][]uint64)
for _, d := range data {
for i := d[0]; i <= d[1]; i++ {
results[i] = make([]uint64, 9)
}
}
var p uint64
outer:
for d := uint64(1); d < 10; d++ {
count := uint(0)
pow := uint64(1)
fl := d * 11
for nd := 3; nd < 20; nd++ {
slim := (d + 1) * pow
for s := d * pow; s < slim; s++ {
e := reverse(s)
mlim := uint64(1)
if nd%2 == 1 {
mlim = 10
}
for m := uint64(0); m < mlim; m++ {
if nd%2 == 0 {
p = s*pow*10 + e
} else {
p = s*pow*100 + m*pow*10 + e
}
if p%fl == 0 {
count++
if _, ok := results[count]; ok {
results[count][d-1] = p
}
if count == max {
continue outer
}
}
}
}
if nd%2 == 1 {
pow *= 10
}
}
}
for _, d := range data {
if d[0] != d[1] {
fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1]))
} else {
fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0]))
}
for i := 1; i <= 9; i++ {
fmt.Printf("%d: ", i)
for j := d[0]; j <= d[1]; j++ {
fmt.Printf("%*d ", d[2], results[j][i-1])
}
fmt.Println()
}
fmt.Println()
}
}
|
Generate an equivalent Go version of this C++ code. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class sierpinski {
public:
void draw( int o ) {
colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;
colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;
bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC();
drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );
bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL );
LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );
LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" );
}
private:
void drawTri( HDC dc, float l, float t, float r, float b, int i ) {
float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f;
if( i ) {
drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );
drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );
drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );
}
bmp.setPenColor( colors[i % 6] );
MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL );
LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) );
LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );
LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) );
}
myBitmap bmp;
DWORD colors[6];
};
int main(int argc, char* argv[]) {
sierpinski s; s.draw( 12 );
return 0;
}
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
func main() {
const order = 8
const width = 1 << order
const margin = 10
bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
for y := 0; y < width; y++ {
for x := 0; x < width; x++ {
if x&y == 0 {
im.SetGray(x, y, gBlack)
}
}
}
f, err := os.Create("sierpinski.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class sierpinski {
public:
void draw( int o ) {
colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;
colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;
bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC();
drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );
bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL );
LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );
LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" );
}
private:
void drawTri( HDC dc, float l, float t, float r, float b, int i ) {
float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f;
if( i ) {
drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );
drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );
drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );
}
bmp.setPenColor( colors[i % 6] );
MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL );
LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) );
LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );
LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) );
}
myBitmap bmp;
DWORD colors[6];
};
int main(int argc, char* argv[]) {
sierpinski s; s.draw( 12 );
return 0;
}
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
func main() {
const order = 8
const width = 1 << order
const margin = 10
bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
for y := 0; y < width; y++ {
for x := 0; x < width; x++ {
if x&y == 0 {
im.SetGray(x, y, gBlack)
}
}
}
f, err := os.Create("sierpinski.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
for (int p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum, n, c := 0, 0, 0
fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:")
fmt.Println(" n cumulative sum")
for _, p := range primes {
n++
sum += p
if rcu.IsPrime(sum) {
c++
fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum))
}
}
fmt.Println()
fmt.Println(c, "such prime sums found")
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
for (int p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum, n, c := 0, 0, 0
fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:")
fmt.Println(" n cumulative sum")
for _, p := range primes {
n++
sum += p
if rcu.IsPrime(sum) {
c++
fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum))
}
}
fmt.Println()
fmt.Println(c, "such prime sums found")
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
| package main
import (
"fmt"
"sort"
)
func distinctSortedUnion(ll [][]int) []int {
var res []int
for _, l := range ll {
res = append(res, l...)
}
set := make(map[int]bool)
for _, e := range res {
set[e] = true
}
res = res[:0]
for key := range set {
res = append(res, key)
}
sort.Ints(res)
return res
}
func main() {
ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}
fmt.Println("Distinct sorted union of", ll, "is:")
fmt.Println(distinctSortedUnion(ll))
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
| package main
import (
"fmt"
"sort"
)
func distinctSortedUnion(ll [][]int) []int {
var res []int
for _, l := range ll {
res = append(res, l...)
}
set := make(map[int]bool)
for _, e := range res {
set[e] = true
}
res = res[:0]
for key := range set {
res = append(res, key)
}
sort.Ints(res)
return res
}
func main() {
ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}
fmt.Println("Distinct sorted union of", ll, "is:")
fmt.Println(distinctSortedUnion(ll))
}
|
Write the same algorithm in Go as shown in this C++ implementation. |
class N{
uint n,i,g,e,l;
public:
N(uint n): n(n-1),i{},g{},e(1),l(n-1){}
bool hasNext(){
g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;
if (l==2) {l=--n; e=1; return true;}
if (e<((1<<(l-1))-1)) {++e; return true;}
e=1; --l; return (l>0);
}
uint next() {return g;}
};
| package main
import "fmt"
const (
m = iota
c
cm
cmc
)
func ncs(s []int) [][]int {
if len(s) < 3 {
return nil
}
return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)
}
var skip = []int{m, cm, cm, cmc}
var incl = []int{c, c, cmc, cmc}
func n2(ss, tail []int, seq int) [][]int {
if len(tail) == 0 {
if seq != cmc {
return nil
}
return [][]int{ss}
}
return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),
n2(append(ss, tail[0]), tail[1:], incl[seq])...)
}
func main() {
ss := ncs([]int{1, 2, 3, 4})
fmt.Println(len(ss), "non-continuous subsequences:")
for _, s := range ss {
fmt.Println(" ", s)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <windows.h>
#include <string>
using namespace std;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
clear();
return true;
}
void clear()
{
ZeroMemory( pBits, width * height * sizeof( DWORD ) );
}
void setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD* dwpBits;
DWORD wb;
HANDLE file;
GetObject( bmp, sizeof( bitmap ), &bitmap );
dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() { return hdc; }
int getWidth() { return width; }
int getHeight() { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
void *pBits;
int width, height;
};
class fiboFractal
{
public:
fiboFractal( int l )
{
bmp.create( 600, 440 );
bmp.setPenColor( 0x00ff00 );
createWord( l ); createFractal();
bmp.saveBitmap( "path_to_save_bitmap" );
}
private:
void createWord( int l )
{
string a = "1", b = "0", c;
l -= 2;
while( l-- )
{ c = b + a; a = b; b = c; }
fWord = c;
}
void createFractal()
{
int n = 1, px = 10, dir,
py = 420, len = 1,
x = 0, y = -len, goingTo = 0;
HDC dc = bmp.getDC();
MoveToEx( dc, px, py, NULL );
for( string::iterator si = fWord.begin(); si != fWord.end(); si++ )
{
px += x; py += y;
LineTo( dc, px, py );
if( !( *si - 48 ) )
{
if( n & 1 ) dir = 1;
else dir = 0;
switch( goingTo )
{
case 0:
y = 0;
if( dir ){ x = len; goingTo = 1; }
else { x = -len; goingTo = 3; }
break;
case 1:
x = 0;
if( dir ) { y = len; goingTo = 2; }
else { y = -len; goingTo = 0; }
break;
case 2:
y = 0;
if( dir ) { x = -len; goingTo = 3; }
else { x = len; goingTo = 1; }
break;
case 3:
x = 0;
if( dir ) { y = -len; goingTo = 0; }
else { y = len; goingTo = 2; }
}
}
n++;
}
}
string fWord;
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
fiboFractal ff( 23 );
return system( "pause" );
}
| package main
import (
"github.com/fogleman/gg"
"strings"
)
func wordFractal(i int) string {
if i < 2 {
if i == 1 {
return "1"
}
return ""
}
var f1 strings.Builder
f1.WriteString("1")
var f2 strings.Builder
f2.WriteString("0")
for j := i - 2; j >= 1; j-- {
tmp := f2.String()
f2.WriteString(f1.String())
f1.Reset()
f1.WriteString(tmp)
}
return f2.String()
}
func draw(dc *gg.Context, x, y, dx, dy float64, wf string) {
for i, c := range wf {
dc.DrawLine(x, y, x+dx, y+dy)
x += dx
y += dy
if c == '0' {
tx := dx
dx = dy
if i%2 == 0 {
dx = -dy
}
dy = -tx
if i%2 == 0 {
dy = tx
}
}
}
}
func main() {
dc := gg.NewContext(450, 620)
dc.SetRGB(0, 0, 0)
dc.Clear()
wf := wordFractal(23)
draw(dc, 20, 20, 1, 0, wf)
dc.SetRGB(0, 1, 0)
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("fib_wordfractal.png")
}
|
Generate an equivalent Go version of this C++ code. | #include <cstdint>
#include <iostream>
#include <string>
#include <primesieve.hpp>
void print_twin_prime_count(long long limit) {
std::cout << "Number of twin prime pairs less than " << limit
<< " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n';
}
int main(int argc, char** argv) {
std::cout.imbue(std::locale(""));
if (argc > 1) {
for (int i = 1; i < argc; ++i) {
try {
print_twin_prime_count(std::stoll(argv[i]));
} catch (const std::exception& ex) {
std::cerr << "Cannot parse limit from '" << argv[i] << "'\n";
}
}
} else {
uint64_t limit = 10;
for (int power = 1; power < 12; ++power, limit *= 10)
print_twin_prime_count(limit);
}
return 0;
}
| package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := uint64(3)
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
c := sieve(1e10 - 1)
limit := 10
start := 3
twins := 0
for i := 1; i < 11; i++ {
for i := start; i < limit; i += 2 {
if !c[i] && !c[i-2] {
twins++
}
}
fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins))
start = limit + 1
limit *= 10
}
}
|
Change the following C++ code into Go without altering its purpose. |
class fifteenSolver{
const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};
int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};
unsigned long N2[100]{};
const bool fY(){
if (N4[n]<_n) return fN();
if (N2[n]==0x123456789abcdef0) {std::cout<<"Solution found in "<<n<<" moves :"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};
if (N4[n]==_n) return fN(); else return false;
}
const bool fN(){
if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}
if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}
if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}
if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}
return false;
}
void fI(){
const int g = (11-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);
}
void fG(){
const int g = (19-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);
}
void fE(){
const int g = (14-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);
}
void fL(){
const int g = (16-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);
}
public:
fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}
void Solve(){for(;not fY();++_n);}
};
| package main
import "fmt"
var (
Nr = [16]int{3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3}
Nc = [16]int{3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2}
)
var (
n, _n int
N0, N3, N4 [85]int
N2 [85]uint64
)
const (
i = 1
g = 8
e = 2
l = 4
)
func fY() bool {
if N2[n] == 0x123456789abcdef0 {
return true
}
if N4[n] <= _n {
return fN()
}
return false
}
func fZ(w int) bool {
if w&i > 0 {
fI()
if fY() {
return true
}
n--
}
if w&g > 0 {
fG()
if fY() {
return true
}
n--
}
if w&e > 0 {
fE()
if fY() {
return true
}
n--
}
if w&l > 0 {
fL()
if fY() {
return true
}
n--
}
return false
}
func fN() bool {
switch N0[n] {
case 0:
switch N3[n] {
case 'l':
return fZ(i)
case 'u':
return fZ(e)
default:
return fZ(i + e)
}
case 3:
switch N3[n] {
case 'r':
return fZ(i)
case 'u':
return fZ(l)
default:
return fZ(i + l)
}
case 1, 2:
switch N3[n] {
case 'l':
return fZ(i + l)
case 'r':
return fZ(i + e)
case 'u':
return fZ(e + l)
default:
return fZ(l + e + i)
}
case 12:
switch N3[n] {
case 'l':
return fZ(g)
case 'd':
return fZ(e)
default:
return fZ(e + g)
}
case 15:
switch N3[n] {
case 'r':
return fZ(g)
case 'd':
return fZ(l)
default:
return fZ(g + l)
}
case 13, 14:
switch N3[n] {
case 'l':
return fZ(g + l)
case 'r':
return fZ(e + g)
case 'd':
return fZ(e + l)
default:
return fZ(g + e + l)
}
case 4, 8:
switch N3[n] {
case 'l':
return fZ(i + g)
case 'u':
return fZ(g + e)
case 'd':
return fZ(i + e)
default:
return fZ(i + g + e)
}
case 7, 11:
switch N3[n] {
case 'd':
return fZ(i + l)
case 'u':
return fZ(g + l)
case 'r':
return fZ(i + g)
default:
return fZ(i + g + l)
}
default:
switch N3[n] {
case 'd':
return fZ(i + e + l)
case 'l':
return fZ(i + g + l)
case 'r':
return fZ(i + g + e)
case 'u':
return fZ(g + e + l)
default:
return fZ(i + g + e + l)
}
}
}
func fI() {
g := (11 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] + 4
N2[n+1] = N2[n] - a + (a << 16)
N3[n+1] = 'd'
N4[n+1] = N4[n]
cond := Nr[a>>uint(g)] <= N0[n]/4
if !cond {
N4[n+1]++
}
n++
}
func fG() {
g := (19 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] - 4
N2[n+1] = N2[n] - a + (a >> 16)
N3[n+1] = 'u'
N4[n+1] = N4[n]
cond := Nr[a>>uint(g)] >= N0[n]/4
if !cond {
N4[n+1]++
}
n++
}
func fE() {
g := (14 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] + 1
N2[n+1] = N2[n] - a + (a << 4)
N3[n+1] = 'r'
N4[n+1] = N4[n]
cond := Nc[a>>uint(g)] <= N0[n]%4
if !cond {
N4[n+1]++
}
n++
}
func fL() {
g := (16 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] - 1
N2[n+1] = N2[n] - a + (a >> 4)
N3[n+1] = 'l'
N4[n+1] = N4[n]
cond := Nc[a>>uint(g)] >= N0[n]%4
if !cond {
N4[n+1]++
}
n++
}
func fifteenSolver(n int, g uint64) {
N0[0] = n
N2[0] = g
N4[0] = 0
}
func solve() {
if fN() {
fmt.Print("Solution found in ", n, " moves: ")
for g := 1; g <= n; g++ {
fmt.Printf("%c", N3[g])
}
fmt.Println()
} else {
n = 0
_n++
solve()
}
}
func main() {
fifteenSolver(8, 0xfe169b4c0a73d852)
solve()
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <complex>
#include <cmath>
#include <iostream>
double const pi = 4 * std::atan(1);
int main()
{
for (int n = 2; n <= 10; ++n)
{
std::cout << n << ": ";
for (int k = 0; k < n; ++k)
std::cout << std::polar(1, 2*pi*k/n) << " ";
std::cout << std::endl;
}
}
| package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
for i := 0; i < n; i++ {
r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
}
return r
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <iostream>
#include <sstream>
typedef long long bigInt;
using namespace std;
class number
{
public:
number() { s = "0"; neg = false; }
number( bigInt a ) { set( a ); }
number( string a ) { set( a ); }
void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }
void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }
number operator * ( const number& b ) { return this->mul( b ); }
number& operator *= ( const number& b ) { *this = *this * b; return *this; }
number& operator = ( const number& b ) { s = b.s; return *this; }
friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; }
friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }
private:
number mul( const number& b )
{
number a; bool neg = false;
string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );
int xx, ss, rr, t, c, stp = 0;
string::reverse_iterator xi = bs.rbegin(), si, ri;
for( ; xi != bs.rend(); xi++ )
{
c = 0; ri = r.rbegin() + stp;
for( si = s.rbegin(); si != s.rend(); si++ )
{
xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;
ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;
( *ri++ ) = t + 48;
}
if( c > 0 ) ( *ri ) = c + 48;
stp++;
}
trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;
if( t & 1 ) a.s = "-" + r;
else a.s = r;
return a;
}
void trimLeft( string& r )
{
if( r.length() < 2 ) return;
for( string::iterator x = r.begin(); x != ( r.end() - 1 ); )
{
if( ( *x ) != '0' ) return;
x = r.erase( x );
}
}
void clearStr()
{
for( string::iterator x = s.begin(); x != s.end(); )
{
if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );
else x++;
}
}
string s;
bool neg;
};
int main( int argc, char* argv[] )
{
number a, b;
a.set( "18446744073709551616" ); b.set( "18446744073709551616" );
cout << a * b << endl << endl;
cout << "Factor 1 = "; cin >> a;
cout << "Factor 2 = "; cin >> b;
cout << "Product: = " << a * b << endl << endl;
return system( "pause" );
}
|
package main
import "fmt"
func d(b byte) byte {
if b < '0' || b > '9' {
panic("digit 0-9 expected")
}
return b - '0'
}
func add(x, y string) string {
if len(y) > len(x) {
x, y = y, x
}
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
if i <= len(y) {
c += d(y[len(y)-i])
}
s := d(x[len(x)-i]) + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mulDigit(x string, y byte) string {
if y == '0' {
return "0"
}
y = d(y)
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
s := d(x[len(x)-i])*y + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mul(x, y string) string {
result := mulDigit(x, y[len(y)-1])
for i, zeros := 2, ""; i <= len(y); i++ {
zeros += "0"
result = add(result, mulDigit(x, y[len(y)-i])+zeros)
}
return result
}
const n = "18446744073709551616"
func main() {
fmt.Println(mul(n, n))
}
|
Write the same code in Go as shown below in C++. | #include <iomanip>
#include <iostream>
#include <tuple>
std::tuple<uint64_t, uint64_t> solvePell(int n) {
int x = (int)sqrt(n);
if (x * x == n) {
return std::make_pair(1, 0);
}
int y = x;
int z = 1;
int r = 2 * x;
std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);
std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);
uint64_t a = 0;
uint64_t b = 0;
while (true) {
y = r * z - y;
z = (n - y * y) / z;
r = (x + y) / z;
e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));
f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));
a = std::get<1>(e) + x * std::get<1>(f);
b = std::get<1>(f);
if (a * a - n * b * b == 1) {
break;
}
}
return std::make_pair(a, b);
}
void test(int n) {
auto r = solvePell(n);
std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n';
}
int main() {
test(61);
test(109);
test(181);
test(277);
return 0;
}
| package main
import (
"fmt"
"math/big"
)
var big1 = new(big.Int).SetUint64(1)
func solvePell(nn uint64) (*big.Int, *big.Int) {
n := new(big.Int).SetUint64(nn)
x := new(big.Int).Set(n)
x.Sqrt(x)
y := new(big.Int).Set(x)
z := new(big.Int).SetUint64(1)
r := new(big.Int).Lsh(x, 1)
e1 := new(big.Int).SetUint64(1)
e2 := new(big.Int)
f1 := new(big.Int)
f2 := new(big.Int).SetUint64(1)
t := new(big.Int)
u := new(big.Int)
a := new(big.Int)
b := new(big.Int)
for {
t.Mul(r, z)
y.Sub(t, y)
t.Mul(y, y)
t.Sub(n, t)
z.Quo(t, z)
t.Add(x, y)
r.Quo(t, z)
u.Set(e1)
e1.Set(e2)
t.Mul(r, e2)
e2.Add(t, u)
u.Set(f1)
f1.Set(f2)
t.Mul(r, f2)
f2.Add(t, u)
t.Mul(x, f2)
a.Add(e2, t)
b.Set(f2)
t.Mul(a, a)
u.Mul(n, b)
u.Mul(u, b)
t.Sub(t, u)
if t.Cmp(big1) == 0 {
return a, b
}
}
}
func main() {
ns := []uint64{61, 109, 181, 277}
for _, n := range ns {
x, y := solvePell(n)
fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y)
}
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
bool contains_duplicates(std::string s)
{
std::sort(s.begin(), s.end());
return std::adjacent_find(s.begin(), s.end()) != s.end();
}
void game()
{
typedef std::string::size_type index;
std::string symbols = "0123456789";
unsigned int const selection_length = 4;
std::random_shuffle(symbols.begin(), symbols.end());
std::string selection = symbols.substr(0, selection_length);
std::string guess;
while (std::cout << "Your guess? ", std::getline(std::cin, guess))
{
if (guess.length() != selection_length
|| guess.find_first_not_of(symbols) != std::string::npos
|| contains_duplicates(guess))
{
std::cout << guess << " is not a valid guess!";
continue;
}
unsigned int bulls = 0;
unsigned int cows = 0;
for (index i = 0; i != selection_length; ++i)
{
index pos = selection.find(guess[i]);
if (pos == i)
++bulls;
else if (pos != std::string::npos)
++cows;
}
std::cout << bulls << " bulls, " << cows << " cows.\n";
if (bulls == selection_length)
{
std::cout << "Congratulations! You have won!\n";
return;
}
}
std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
std::exit(EXIT_FAILURE);
}
int main()
{
std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
std::string answer;
while (true)
{
while (true)
{
if (!std::getline(std::cin, answer))
{
std::cout << "I can't get an answer. Exiting.\n";
return EXIT_FAILURE;
}
if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
break;
if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
{
std::cout << "Ok. Goodbye.\n";
return EXIT_SUCCESS;
}
std::cout << "Please answer yes or no: ";
}
game();
std::cout << "Another game? ";
}
}
| package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
pat := make([]byte, 4)
rand.Seed(time.Now().Unix())
r := rand.Perm(9)
for i := range pat {
pat[i] = '1' + byte(r[i])
}
valid := []byte("123456789")
guess:
for in := bufio.NewReader(os.Stdin); ; {
fmt.Print("Guess: ")
guess, err := in.ReadString('\n')
if err != nil {
fmt.Println("\nSo, bye.")
return
}
guess = strings.TrimSpace(guess)
if len(guess) != 4 {
fmt.Println("Please guess a four digit number.")
continue
}
var cows, bulls int
for ig, cg := range guess {
if strings.IndexRune(guess[:ig], cg) >= 0 {
fmt.Printf("Repeated digit: %c\n", cg)
continue guess
}
switch bytes.IndexByte(pat, byte(cg)) {
case -1:
if bytes.IndexByte(valid, byte(cg)) == -1 {
fmt.Printf("Invalid digit: %c\n", cg)
continue guess
}
default:
cows++
case ig:
bulls++
}
}
fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
if bulls == 4 {
fmt.Println("You got it.")
return
}
}
}
|
Generate an equivalent Go version of this C++ code. | #include <algorithm>
#include <iostream>
#include <iterator>
template <typename RandomAccessIterator>
void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bool swapped = true;
while (begin != end-- && swapped) {
swapped = false;
for (auto i = begin; i != end; ++i) {
if (*(i + 1) < *i) {
std::iter_swap(i, i + 1);
swapped = true;
}
}
}
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bubble_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| package main
import "fmt"
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
bubblesort(list)
fmt.Println("sorted! ", list)
}
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
for index := 0; index < itemCount; index++ {
if a[index] > a[index+1] {
a[index], a[index+1] = a[index+1], a[index]
hasChanged = true
}
}
if hasChanged == false {
break
}
}
}
|
Generate an equivalent Go version of this C++ code. | #include <cmath>
#include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
unsigned int divisor_product(unsigned int n) {
return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));
}
int main() {
const unsigned int limit = 50;
std::cout << "Product of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(11) << divisor_product(n);
if (n % 5 == 0)
std::cout << '\n';
}
}
| package main
import "fmt"
func prodDivisors(n int) int {
prod := 1
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
prod *= i
j := n / i
if j != i {
prod *= j
}
}
i += k
}
return prod
}
func main() {
fmt.Println("The products of positive divisors for the first 50 positive integers are:")
for i := 1; i <= 50; i++ {
fmt.Printf("%9d ", prodDivisors(i))
if i%5 == 0 {
fmt.Println()
}
}
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <cmath>
#include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
unsigned int divisor_product(unsigned int n) {
return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));
}
int main() {
const unsigned int limit = 50;
std::cout << "Product of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(11) << divisor_product(n);
if (n % 5 == 0)
std::cout << '\n';
}
}
| package main
import "fmt"
func prodDivisors(n int) int {
prod := 1
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
prod *= i
j := n / i
if j != i {
prod *= j
}
}
i += k
}
return prod
}
func main() {
fmt.Println("The products of positive divisors for the first 50 positive integers are:")
for i := 1; i <= 50; i++ {
fmt.Printf("%9d ", prodDivisors(i))
if i%5 == 0 {
fmt.Println()
}
}
}
|
Generate an equivalent Go version of this C++ code. | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream input ( "input.txt" );
ofstream output ("output.txt");
if (output.is_open()) {
if (input.is_open()){
while (getline (input,line)) {
output << line << endl;
}
input.close();
}
else {
cout << "input.txt cannot be opened!\n";
}
output.close();
}
else {
cout << "output.txt cannot be written to!\n";
}
return 0;
}
| package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Println(err)
return
}
if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
fmt.Println(err)
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <iostream>
int main()
{
int a, b;
std::cin >> a >> b;
std::cout << "a+b = " << a+b << "\n";
std::cout << "a-b = " << a-b << "\n";
std::cout << "a*b = " << a*b << "\n";
std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
return 0;
}
| package main
import "fmt"
func main() {
var a, b int
fmt.Print("enter two integers: ")
fmt.Scanln(&a, &b)
fmt.Printf("%d + %d = %d\n", a, b, a+b)
fmt.Printf("%d - %d = %d\n", a, b, a-b)
fmt.Printf("%d * %d = %d\n", a, b, a*b)
fmt.Printf("%d / %d = %d\n", a, b, a/b)
fmt.Printf("%d %% %d = %d\n", a, b, a%b)
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main()
{
using namespace boost::numeric::ublas;
matrix<double> m(3,3);
for(int i=0; i!=m.size1(); ++i)
for(int j=0; j!=m.size2(); ++j)
m(i,j)=3*i+j;
std::cout << trans(m) << std::endl;
}
| package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
| package main
import "fmt"
func a(k int, x1, x2, x3, x4, x5 func() int) int {
var b func() int
b = func() int {
k--
return a(k, b, x1, x2, x3, x4)
}
if k <= 0 {
return x4() + x5()
}
return b()
}
func main() {
x := func(i int) func() int { return func() int { return i } }
fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <iostream>
bool a(bool in)
{
std::cout << "a" << std::endl;
return in;
}
bool b(bool in)
{
std::cout << "b" << std::endl;
return in;
}
void test(bool i, bool j) {
std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl;
std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl;
}
int main()
{
test(false, false);
test(false, true);
test(true, false);
test(true, true);
return 0;
}
| package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, true)
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
| package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
| package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <iomanip>
#include <iostream>
int mod(int n, int d) {
return (d + n % d) % d;
}
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;
}
void print_carmichael_numbers(int prime1) {
for (int h3 = 1; h3 < prime1; ++h3) {
for (int d = 1; d < h3 + prime1; ++d) {
if (mod((h3 + prime1) * (prime1 - 1), d) != 0
|| mod(-prime1 * prime1, h3) != mod(d, h3))
continue;
int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;
if (!is_prime(prime2))
continue;
int prime3 = 1 + prime1 * prime2/h3;
if (!is_prime(prime3))
continue;
if (mod(prime2 * prime3, prime1 - 1) != 1)
continue;
unsigned int c = prime1 * prime2 * prime3;
std::cout << std::setw(2) << prime1 << " x "
<< std::setw(4) << prime2 << " x "
<< std::setw(5) << prime3 << " = "
<< std::setw(10) << c << '\n';
}
}
}
int main() {
for (int p = 2; p <= 61; ++p) {
if (is_prime(p))
print_carmichael_numbers(p);
}
return 0;
}
| package main
import "fmt"
func mod(n, m int) int {
return ((n % m) + m) % m
}
func isPrime(n int) bool {
if n < 2 { return false }
if n % 2 == 0 { return n == 2 }
if n % 3 == 0 { return n == 3 }
d := 5
for d * d <= n {
if n % d == 0 { return false }
d += 2
if n % d == 0 { return false }
d += 4
}
return true
}
func carmichael(p1 int) {
for h3 := 2; h3 < p1; h3++ {
for d := 1; d < h3 + p1; d++ {
if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {
p2 := 1 + (p1 - 1) * (h3 + p1) / d
if !isPrime(p2) { continue }
p3 := 1 + p1 * p2 / h3
if !isPrime(p3) { continue }
if p2 * p3 % (p1 - 1) != 1 { continue }
c := p1 * p2 * p3
fmt.Printf("%2d %4d %5d %d\n", p1, p2, p3, c)
}
}
}
}
func main() {
fmt.Println("The following are Carmichael munbers for p1 <= 61:\n")
fmt.Println("p1 p2 p3 product")
fmt.Println("== == == =======")
for p1 := 2; p1 <= 61; p1++ {
if isPrime(p1) { carmichael(p1) }
}
}
|
Write a version of this C++ function in Go with identical behavior. | #include <cstdio>
void divisor_count_and_sum(unsigned int n,
unsigned int& divisor_count,
unsigned int& divisor_sum)
{
divisor_count = 0;
divisor_sum = 0;
for (unsigned int i = 1;; i++)
{
unsigned int j = n / i;
if (j < i)
break;
if (i * j != n)
continue;
divisor_sum += i;
divisor_count += 1;
if (i != j)
{
divisor_sum += j;
divisor_count += 1;
}
}
}
int main()
{
unsigned int arithmetic_count = 0;
unsigned int composite_count = 0;
for (unsigned int n = 1; arithmetic_count <= 1000000; n++)
{
unsigned int divisor_count;
unsigned int divisor_sum;
divisor_count_and_sum(n, divisor_count, divisor_sum);
unsigned int mean = divisor_sum / divisor_count;
if (mean * divisor_count != divisor_sum)
continue;
arithmetic_count++;
if (divisor_count > 2)
composite_count++;
if (arithmetic_count <= 100)
{
std::printf("%3u ", n);
if (arithmetic_count % 10 == 0)
std::printf("\n");
}
if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||
(arithmetic_count == 100000) || (arithmetic_count == 1000000))
{
std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count);
}
}
return 0;
}
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
arithmetic := []int{1}
primes := []int{}
limit := int(1e6)
for n := 3; len(arithmetic) < limit; n++ {
divs := rcu.Divisors(n)
if len(divs) == 2 {
primes = append(primes, n)
arithmetic = append(arithmetic, n)
} else {
mean := float64(rcu.SumInts(divs)) / float64(len(divs))
if mean == math.Trunc(mean) {
arithmetic = append(arithmetic, n)
}
}
}
fmt.Println("The first 100 arithmetic numbers are:")
rcu.PrintTable(arithmetic[0:100], 10, 3, false)
for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
last := arithmetic[x-1]
lastc := rcu.Commatize(last)
fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
pcount := sort.SearchInts(primes, last) + 1
if !rcu.IsPrime(last) {
pcount--
}
comp := x - pcount - 1
compc := rcu.Commatize(comp)
fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
}
}
|
Write a version of this C++ function in Go with identical behavior. | #include <cstdio>
void divisor_count_and_sum(unsigned int n,
unsigned int& divisor_count,
unsigned int& divisor_sum)
{
divisor_count = 0;
divisor_sum = 0;
for (unsigned int i = 1;; i++)
{
unsigned int j = n / i;
if (j < i)
break;
if (i * j != n)
continue;
divisor_sum += i;
divisor_count += 1;
if (i != j)
{
divisor_sum += j;
divisor_count += 1;
}
}
}
int main()
{
unsigned int arithmetic_count = 0;
unsigned int composite_count = 0;
for (unsigned int n = 1; arithmetic_count <= 1000000; n++)
{
unsigned int divisor_count;
unsigned int divisor_sum;
divisor_count_and_sum(n, divisor_count, divisor_sum);
unsigned int mean = divisor_sum / divisor_count;
if (mean * divisor_count != divisor_sum)
continue;
arithmetic_count++;
if (divisor_count > 2)
composite_count++;
if (arithmetic_count <= 100)
{
std::printf("%3u ", n);
if (arithmetic_count % 10 == 0)
std::printf("\n");
}
if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||
(arithmetic_count == 100000) || (arithmetic_count == 1000000))
{
std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count);
}
}
return 0;
}
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
arithmetic := []int{1}
primes := []int{}
limit := int(1e6)
for n := 3; len(arithmetic) < limit; n++ {
divs := rcu.Divisors(n)
if len(divs) == 2 {
primes = append(primes, n)
arithmetic = append(arithmetic, n)
} else {
mean := float64(rcu.SumInts(divs)) / float64(len(divs))
if mean == math.Trunc(mean) {
arithmetic = append(arithmetic, n)
}
}
}
fmt.Println("The first 100 arithmetic numbers are:")
rcu.PrintTable(arithmetic[0:100], 10, 3, false)
for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
last := arithmetic[x-1]
lastc := rcu.Commatize(last)
fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
pcount := sort.SearchInts(primes, last) + 1
if !rcu.IsPrime(last) {
pcount--
}
comp := x - pcount - 1
compc := rcu.Commatize(comp)
fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <windows.h>
#include <sstream>
#include <tchar.h>
using namespace std;
const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
void* getBits( void ) const { return pBits; }
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void* pBits;
int width, height, wid;
DWORD clr;
};
class bmpNoise
{
public:
bmpNoise()
{
QueryPerformanceFrequency( &_frequency );
_bmp.create( BMP_WID, BMP_HEI );
_frameTime = _fps = 0; _start = getTime(); _frames = 0;
}
void mainLoop()
{
float now = getTime();
if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }
HDC wdc, dc = _bmp.getDC();
unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );
for( int y = 0; y < BMP_HEI; y++ )
{
for( int x = 0; x < BMP_WID; x++ )
{
if( rand() % 10 < 5 ) memset( bits, 255, 3 );
else memset( bits, 0, 3 );
bits++;
}
}
ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );
wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
_frames++; _frameTime = getTime() - now;
if( _frameTime > 1.0f ) _frameTime = 1.0f;
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
float getTime()
{
LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );
return liTime.QuadPart / ( float )_frequency.QuadPart;
}
myBitmap _bmp;
HWND _hwnd;
float _start, _fps, _frameTime;
unsigned int _frames;
LARGE_INTEGER _frequency;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst )
{
_hInst = hInst; _hwnd = InitAll();
_noise.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
_noise.mainLoop();
}
}
return UnregisterClass( "_MY_NOISE_", _hInst );
}
private:
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY: PostQuitMessage( 0 ); break;
default:
return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll()
{
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_MY_NOISE_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_WID, BMP_HEI };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst;
HINSTANCE _hInst;
HWND _hwnd;
bmpNoise _noise;
};
wnd* wnd::_inst = 0;
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
srand( GetTickCount() ); wnd myWnd;
return myWnd.Run( hInstance );
}
| package main
import (
"code.google.com/p/x-go-binding/ui/x11"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"os"
"time"
)
var randcol = genrandcol()
func genrandcol() <-chan color.Color {
c := make(chan color.Color)
go func() {
for {
select {
case c <- image.Black:
case c <- image.White:
}
}
}()
return c
}
func gennoise(screen draw.Image) {
for y := 0; y < 240; y++ {
for x := 0; x < 320; x++ {
screen.Set(x, y, <-randcol)
}
}
}
func fps() chan<- bool {
up := make(chan bool)
go func() {
var frames int64
var lasttime time.Time
var totaltime time.Duration
for {
<-up
frames++
now := time.Now()
totaltime += now.Sub(lasttime)
if totaltime > time.Second {
fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
frames = 0
totaltime = 0
}
lasttime = now
}
}()
return up
}
func main() {
win, err := x11.NewWindow()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer win.Close()
go func() {
upfps := fps()
screen := win.Screen()
for {
gennoise(screen)
win.FlushImage()
upfps <- true
}
}()
for _ = range win.EventChan() {
}
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <conio.h>
#include <iostream>
using namespace std;
int main()
{
char ch;
_cputs( "Yes or no?" );
do
{
ch = _getch();
ch = toupper( ch );
} while(ch!='Y'&&ch!='N');
if(ch=='N')
{
cout << "You said no" << endl;
}
else
{
cout << "You said yes" << endl;
}
return 0;
}
| package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
|
Write the same code in Go as shown below in C++. | #include <conio.h>
#include <iostream>
using namespace std;
int main()
{
char ch;
_cputs( "Yes or no?" );
do
{
ch = _getch();
ch = toupper( ch );
} while(ch!='Y'&&ch!='N');
if(ch=='N')
{
cout << "You said no" << endl;
}
else
{
cout << "You said yes" << endl;
}
return 0;
}
| package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
using namespace std ;
int divisor_sum( int number ) {
int sum = 0 ;
for ( int i = 1 ; i < number ; i++ )
if ( number % i == 0 )
sum += i ;
return sum;
}
int main( ) {
cout << "Perfect numbers from 1 to 33550337:\n" ;
for ( int num = 1 ; num < 33550337 ; num++ ) {
if (divisor_sum(num) == num)
cout << num << '\n' ;
}
return 0 ;
}
| package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
func isPerfect(n int64) bool {
switch n {
case 6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128:
return true
}
return false
}
func main() {
for n := int64(1); ; n++ {
if isPerfect(n) != computePerfect(n) {
panic("bug")
}
if n%1e3 == 0 {
fmt.Println("tested", n)
}
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <cassert>
#include <cmath>
#include <complex>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
template <typename scalar_type> class complex_matrix {
public:
using element_type = std::complex<scalar_type>;
complex_matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
complex_matrix(size_t rows, size_t columns, element_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
complex_matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<element_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const element_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
element_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
friend bool operator==(const complex_matrix& a, const complex_matrix& b) {
return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&
a.elements_ == b.elements_;
}
private:
size_t rows_;
size_t columns_;
std::vector<element_type> elements_;
};
template <typename scalar_type>
complex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,
const complex_matrix<scalar_type>& b) {
assert(a.columns() == b.rows());
size_t arows = a.rows();
size_t bcolumns = b.columns();
size_t n = a.columns();
complex_matrix<scalar_type> c(arows, bcolumns);
for (size_t i = 0; i < arows; ++i) {
for (size_t j = 0; j < n; ++j) {
for (size_t k = 0; k < bcolumns; ++k)
c(i, k) += a(i, j) * b(j, k);
}
}
return c;
}
template <typename scalar_type>
complex_matrix<scalar_type>
conjugate_transpose(const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
complex_matrix<scalar_type> b(columns, rows);
for (size_t i = 0; i < columns; i++) {
for (size_t j = 0; j < rows; j++) {
b(i, j) = std::conj(a(j, i));
}
}
return b;
}
template <typename scalar_type>
std::string to_string(const std::complex<scalar_type>& c) {
std::ostringstream out;
const int precision = 6;
out << std::fixed << std::setprecision(precision);
out << std::setw(precision + 3) << c.real();
if (c.imag() > 0)
out << " + " << std::setw(precision + 2) << c.imag() << 'i';
else if (c.imag() == 0)
out << " + " << std::setw(precision + 2) << 0.0 << 'i';
else
out << " - " << std::setw(precision + 2) << -c.imag() << 'i';
return out.str();
}
template <typename scalar_type>
void print(std::ostream& out, const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << to_string(a(row, column));
}
out << '\n';
}
}
template <typename scalar_type>
bool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
return matrix == conjugate_transpose(matrix);
}
template <typename scalar_type>
bool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
return product(c, matrix) == product(matrix, c);
}
bool is_equal(const std::complex<double>& a, double b) {
constexpr double e = 1e-15;
return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;
}
template <typename scalar_type>
bool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
size_t rows = matrix.rows();
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < rows; ++j) {
if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))
return false;
}
}
return true;
}
template <typename scalar_type>
bool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
auto p = product(c, matrix);
return is_identity_matrix(p) && p == product(matrix, c);
}
template <typename scalar_type>
void test(const complex_matrix<scalar_type>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Conjugate transpose:\n";
print(std::cout, conjugate_transpose(matrix));
std::cout << std::boolalpha;
std::cout << "Hermitian: " << is_hermitian_matrix(matrix) << '\n';
std::cout << "Normal: " << is_normal_matrix(matrix) << '\n';
std::cout << "Unitary: " << is_unitary_matrix(matrix) << '\n';
}
int main() {
using matrix = complex_matrix<double>;
matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},
{{2, -1}, {3, 0}, {0, 1}},
{{4, 0}, {0, -1}, {1, 0}}});
double n = std::sqrt(0.5);
matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},
{{0, -n}, {0, n}, {0, 0}},
{{0, 0}, {0, 0}, {0, 1}}});
matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},
{{2, -1}, {4, 1}, {0, 0}},
{{7, -5}, {1, -4}, {1, 0}}});
test(matrix1);
std::cout << '\n';
test(matrix2);
std::cout << '\n';
test(matrix3);
return 0;
}
| package main
import (
"fmt"
"math"
"math/cmplx"
)
type matrix struct {
ele []complex128
cols int
}
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
}
|
Change the following C++ code into Go without altering its purpose. | #include <cassert>
#include <cmath>
#include <complex>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
template <typename scalar_type> class complex_matrix {
public:
using element_type = std::complex<scalar_type>;
complex_matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
complex_matrix(size_t rows, size_t columns, element_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
complex_matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<element_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const element_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
element_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
friend bool operator==(const complex_matrix& a, const complex_matrix& b) {
return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&
a.elements_ == b.elements_;
}
private:
size_t rows_;
size_t columns_;
std::vector<element_type> elements_;
};
template <typename scalar_type>
complex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,
const complex_matrix<scalar_type>& b) {
assert(a.columns() == b.rows());
size_t arows = a.rows();
size_t bcolumns = b.columns();
size_t n = a.columns();
complex_matrix<scalar_type> c(arows, bcolumns);
for (size_t i = 0; i < arows; ++i) {
for (size_t j = 0; j < n; ++j) {
for (size_t k = 0; k < bcolumns; ++k)
c(i, k) += a(i, j) * b(j, k);
}
}
return c;
}
template <typename scalar_type>
complex_matrix<scalar_type>
conjugate_transpose(const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
complex_matrix<scalar_type> b(columns, rows);
for (size_t i = 0; i < columns; i++) {
for (size_t j = 0; j < rows; j++) {
b(i, j) = std::conj(a(j, i));
}
}
return b;
}
template <typename scalar_type>
std::string to_string(const std::complex<scalar_type>& c) {
std::ostringstream out;
const int precision = 6;
out << std::fixed << std::setprecision(precision);
out << std::setw(precision + 3) << c.real();
if (c.imag() > 0)
out << " + " << std::setw(precision + 2) << c.imag() << 'i';
else if (c.imag() == 0)
out << " + " << std::setw(precision + 2) << 0.0 << 'i';
else
out << " - " << std::setw(precision + 2) << -c.imag() << 'i';
return out.str();
}
template <typename scalar_type>
void print(std::ostream& out, const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << to_string(a(row, column));
}
out << '\n';
}
}
template <typename scalar_type>
bool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
return matrix == conjugate_transpose(matrix);
}
template <typename scalar_type>
bool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
return product(c, matrix) == product(matrix, c);
}
bool is_equal(const std::complex<double>& a, double b) {
constexpr double e = 1e-15;
return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;
}
template <typename scalar_type>
bool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
size_t rows = matrix.rows();
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < rows; ++j) {
if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))
return false;
}
}
return true;
}
template <typename scalar_type>
bool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
auto p = product(c, matrix);
return is_identity_matrix(p) && p == product(matrix, c);
}
template <typename scalar_type>
void test(const complex_matrix<scalar_type>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Conjugate transpose:\n";
print(std::cout, conjugate_transpose(matrix));
std::cout << std::boolalpha;
std::cout << "Hermitian: " << is_hermitian_matrix(matrix) << '\n';
std::cout << "Normal: " << is_normal_matrix(matrix) << '\n';
std::cout << "Unitary: " << is_unitary_matrix(matrix) << '\n';
}
int main() {
using matrix = complex_matrix<double>;
matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},
{{2, -1}, {3, 0}, {0, 1}},
{{4, 0}, {0, -1}, {1, 0}}});
double n = std::sqrt(0.5);
matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},
{{0, -n}, {0, n}, {0, 0}},
{{0, 0}, {0, 0}, {0, 1}}});
matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},
{{2, -1}, {4, 1}, {0, 0}},
{{7, -5}, {1, -4}, {1, 0}}});
test(matrix1);
std::cout << '\n';
test(matrix2);
std::cout << '\n';
test(matrix3);
return 0;
}
| package main
import (
"fmt"
"math"
"math/cmplx"
)
type matrix struct {
ele []complex128
cols int
}
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas_number(unsigned int n) {
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}
big_int jacobsthal_oblong_number(unsigned int n) {
return jacobsthal_number(n) * jacobsthal_number(n + 1);
}
int main() {
std::cout << "First 30 Jacobsthal Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
for (unsigned int n = 0; n < 20; ++n) {
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal primes:\n";
for (unsigned int n = 0, count = 0; count < 20; ++n) {
auto jn = jacobsthal_number(n);
if (is_probably_prime(jn)) {
++count;
std::cout << jn << '\n';
}
}
}
| package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas_number(unsigned int n) {
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}
big_int jacobsthal_oblong_number(unsigned int n) {
return jacobsthal_number(n) * jacobsthal_number(n + 1);
}
int main() {
std::cout << "First 30 Jacobsthal Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
for (unsigned int n = 0; n < 20; ++n) {
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal primes:\n";
for (unsigned int n = 0, count = 0; count < 20; ++n) {
auto jn = jacobsthal_number(n);
if (is_probably_prime(jn)) {
++count;
std::cout << jn << '\n';
}
}
}
| package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
|
Generate an equivalent Go version of this C++ code. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas_number(unsigned int n) {
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}
big_int jacobsthal_oblong_number(unsigned int n) {
return jacobsthal_number(n) * jacobsthal_number(n + 1);
}
int main() {
std::cout << "First 30 Jacobsthal Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
for (unsigned int n = 0; n < 20; ++n) {
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal primes:\n";
for (unsigned int n = 0, count = 0; count < 20; ++n) {
auto jn = jacobsthal_number(n);
if (is_probably_prime(jn)) {
++count;
std::cout << jn << '\n';
}
}
}
| package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
|
Write the same algorithm in Go as shown in this C++ implementation. |
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
void distribute(int dist, vector<int> &List) {
if (dist > List.size() )
List.resize(dist);
for (int i=0; i < dist; i++)
List[i]++;
}
vector<int> beadSort(int *myints, int n) {
vector<int> list, list2, fifth (myints, myints + n);
cout << "#1 Beads falling down: ";
for (int i=0; i < fifth.size(); i++)
distribute (fifth[i], list);
cout << '\n';
cout << "\nBeads on their sides: ";
for (int i=0; i < list.size(); i++)
cout << " " << list[i];
cout << '\n';
cout << "#2 Beads right side up: ";
for (int i=0; i < list.size(); i++)
distribute (list[i], list2);
cout << '\n';
return list2;
}
int main() {
int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
cout << "Sorted list/array: ";
for(unsigned int i=0; i<sorted.size(); i++)
cout << sorted[i] << ' ';
}
| package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, aMax)
for pole, space := 0, all; pole < aMax; pole++ {
abacus[pole] = space[:len(a)]
space = space[len(a):]
}
var wg sync.WaitGroup
wg.Add(len(a))
for row, n := range a {
go func(row, n int) {
for pole := 0; pole < n; pole++ {
abacus[pole][row] = bead
}
wg.Done()
}(row, n)
}
wg.Wait()
wg.Add(aMax)
for _, pole := range abacus {
go func(pole []byte) {
top := 0
for row, space := range pole {
if space == bead {
pole[row] = 0
pole[top] = bead
top++
}
}
wg.Done()
}(pole)
}
wg.Wait()
for row := range a {
x := 0
for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
x++
}
a[len(a)-1-row] = x
}
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <array>
#include <iostream>
template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;
struct Cistercian {
public:
Cistercian() {
initN();
}
Cistercian(int v) {
initN();
draw(v);
}
Cistercian &operator=(int v) {
initN();
draw(v);
}
friend std::ostream &operator<<(std::ostream &, const Cistercian &);
private:
FixedSquareGrid<char, 15> canvas;
void initN() {
for (auto &row : canvas) {
row.fill(' ');
row[5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
for (size_t r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
};
std::ostream &operator<<(std::ostream &os, const Cistercian &c) {
for (auto &row : c.canvas) {
for (auto cell : row) {
os << cell;
}
os << '\n';
}
return os;
}
int main() {
for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {
std::cout << number << ":\n";
Cistercian c(number);
std::cout << c << '\n';
}
return 0;
}
| package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func()
func initDraw() {
draw = map[int]func(){
1: func() { horiz(6, 10, 0) },
2: func() { horiz(6, 10, 4) },
3: func() { diagd(6, 10, 0) },
4: func() { diagu(6, 10, 4) },
5: func() { draw[1](); draw[4]() },
6: func() { verti(0, 4, 10) },
7: func() { draw[1](); draw[6]() },
8: func() { draw[2](); draw[6]() },
9: func() { draw[1](); draw[8]() },
10: func() { horiz(0, 4, 0) },
20: func() { horiz(0, 4, 4) },
30: func() { diagu(0, 4, 4) },
40: func() { diagd(0, 4, 0) },
50: func() { draw[10](); draw[40]() },
60: func() { verti(0, 4, 0) },
70: func() { draw[10](); draw[60]() },
80: func() { draw[20](); draw[60]() },
90: func() { draw[10](); draw[80]() },
100: func() { horiz(6, 10, 14) },
200: func() { horiz(6, 10, 10) },
300: func() { diagu(6, 10, 14) },
400: func() { diagd(6, 10, 10) },
500: func() { draw[100](); draw[400]() },
600: func() { verti(10, 14, 10) },
700: func() { draw[100](); draw[600]() },
800: func() { draw[200](); draw[600]() },
900: func() { draw[100](); draw[800]() },
1000: func() { horiz(0, 4, 14) },
2000: func() { horiz(0, 4, 10) },
3000: func() { diagd(0, 4, 10) },
4000: func() { diagu(0, 4, 14) },
5000: func() { draw[1000](); draw[4000]() },
6000: func() { verti(10, 14, 0) },
7000: func() { draw[1000](); draw[6000]() },
8000: func() { draw[2000](); draw[6000]() },
9000: func() { draw[1000](); draw[8000]() },
}
}
func printNumeral() {
for i := 0; i < 15; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("%s ", n[i][j])
}
fmt.Println()
}
fmt.Println()
}
func main() {
initDraw()
numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}
for _, number := range numbers {
initN()
fmt.Printf("%d:\n", number)
thousands := number / 1000
number %= 1000
hundreds := number / 100
number %= 100
tens := number / 10
ones := number % 10
if thousands > 0 {
draw[thousands*1000]()
}
if hundreds > 0 {
draw[hundreds*100]()
}
if tens > 0 {
draw[tens*10]()
}
if ones > 0 {
draw[ones]()
}
printNumeral()
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <array>
#include <iostream>
template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;
struct Cistercian {
public:
Cistercian() {
initN();
}
Cistercian(int v) {
initN();
draw(v);
}
Cistercian &operator=(int v) {
initN();
draw(v);
}
friend std::ostream &operator<<(std::ostream &, const Cistercian &);
private:
FixedSquareGrid<char, 15> canvas;
void initN() {
for (auto &row : canvas) {
row.fill(' ');
row[5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
for (size_t r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
};
std::ostream &operator<<(std::ostream &os, const Cistercian &c) {
for (auto &row : c.canvas) {
for (auto cell : row) {
os << cell;
}
os << '\n';
}
return os;
}
int main() {
for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {
std::cout << number << ":\n";
Cistercian c(number);
std::cout << c << '\n';
}
return 0;
}
| package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func()
func initDraw() {
draw = map[int]func(){
1: func() { horiz(6, 10, 0) },
2: func() { horiz(6, 10, 4) },
3: func() { diagd(6, 10, 0) },
4: func() { diagu(6, 10, 4) },
5: func() { draw[1](); draw[4]() },
6: func() { verti(0, 4, 10) },
7: func() { draw[1](); draw[6]() },
8: func() { draw[2](); draw[6]() },
9: func() { draw[1](); draw[8]() },
10: func() { horiz(0, 4, 0) },
20: func() { horiz(0, 4, 4) },
30: func() { diagu(0, 4, 4) },
40: func() { diagd(0, 4, 0) },
50: func() { draw[10](); draw[40]() },
60: func() { verti(0, 4, 0) },
70: func() { draw[10](); draw[60]() },
80: func() { draw[20](); draw[60]() },
90: func() { draw[10](); draw[80]() },
100: func() { horiz(6, 10, 14) },
200: func() { horiz(6, 10, 10) },
300: func() { diagu(6, 10, 14) },
400: func() { diagd(6, 10, 10) },
500: func() { draw[100](); draw[400]() },
600: func() { verti(10, 14, 10) },
700: func() { draw[100](); draw[600]() },
800: func() { draw[200](); draw[600]() },
900: func() { draw[100](); draw[800]() },
1000: func() { horiz(0, 4, 14) },
2000: func() { horiz(0, 4, 10) },
3000: func() { diagd(0, 4, 10) },
4000: func() { diagu(0, 4, 14) },
5000: func() { draw[1000](); draw[4000]() },
6000: func() { verti(10, 14, 0) },
7000: func() { draw[1000](); draw[6000]() },
8000: func() { draw[2000](); draw[6000]() },
9000: func() { draw[1000](); draw[8000]() },
}
}
func printNumeral() {
for i := 0; i < 15; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("%s ", n[i][j])
}
fmt.Println()
}
fmt.Println()
}
func main() {
initDraw()
numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}
for _, number := range numbers {
initN()
fmt.Printf("%d:\n", number)
thousands := number / 1000
number %= 1000
hundreds := number / 100
number %= 100
tens := number / 10
ones := number % 10
if thousands > 0 {
draw[thousands*1000]()
}
if hundreds > 0 {
draw[hundreds*100]()
}
if tens > 0 {
draw[tens*10]()
}
if ones > 0 {
draw[ones]()
}
printNumeral()
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <array>
#include <iostream>
template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;
struct Cistercian {
public:
Cistercian() {
initN();
}
Cistercian(int v) {
initN();
draw(v);
}
Cistercian &operator=(int v) {
initN();
draw(v);
}
friend std::ostream &operator<<(std::ostream &, const Cistercian &);
private:
FixedSquareGrid<char, 15> canvas;
void initN() {
for (auto &row : canvas) {
row.fill(' ');
row[5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
for (size_t r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
};
std::ostream &operator<<(std::ostream &os, const Cistercian &c) {
for (auto &row : c.canvas) {
for (auto cell : row) {
os << cell;
}
os << '\n';
}
return os;
}
int main() {
for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {
std::cout << number << ":\n";
Cistercian c(number);
std::cout << c << '\n';
}
return 0;
}
| package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func()
func initDraw() {
draw = map[int]func(){
1: func() { horiz(6, 10, 0) },
2: func() { horiz(6, 10, 4) },
3: func() { diagd(6, 10, 0) },
4: func() { diagu(6, 10, 4) },
5: func() { draw[1](); draw[4]() },
6: func() { verti(0, 4, 10) },
7: func() { draw[1](); draw[6]() },
8: func() { draw[2](); draw[6]() },
9: func() { draw[1](); draw[8]() },
10: func() { horiz(0, 4, 0) },
20: func() { horiz(0, 4, 4) },
30: func() { diagu(0, 4, 4) },
40: func() { diagd(0, 4, 0) },
50: func() { draw[10](); draw[40]() },
60: func() { verti(0, 4, 0) },
70: func() { draw[10](); draw[60]() },
80: func() { draw[20](); draw[60]() },
90: func() { draw[10](); draw[80]() },
100: func() { horiz(6, 10, 14) },
200: func() { horiz(6, 10, 10) },
300: func() { diagu(6, 10, 14) },
400: func() { diagd(6, 10, 10) },
500: func() { draw[100](); draw[400]() },
600: func() { verti(10, 14, 10) },
700: func() { draw[100](); draw[600]() },
800: func() { draw[200](); draw[600]() },
900: func() { draw[100](); draw[800]() },
1000: func() { horiz(0, 4, 14) },
2000: func() { horiz(0, 4, 10) },
3000: func() { diagd(0, 4, 10) },
4000: func() { diagu(0, 4, 14) },
5000: func() { draw[1000](); draw[4000]() },
6000: func() { verti(10, 14, 0) },
7000: func() { draw[1000](); draw[6000]() },
8000: func() { draw[2000](); draw[6000]() },
9000: func() { draw[1000](); draw[8000]() },
}
}
func printNumeral() {
for i := 0; i < 15; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("%s ", n[i][j])
}
fmt.Println()
}
fmt.Println()
}
func main() {
initDraw()
numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}
for _, number := range numbers {
initN()
fmt.Printf("%d:\n", number)
thousands := number / 1000
number %= 1000
hundreds := number / 100
number %= 100
tens := number / 10
ones := number % 10
if thousands > 0 {
draw[thousands*1000]()
}
if hundreds > 0 {
draw[hundreds*100]()
}
if tens > 0 {
draw[tens*10]()
}
if ones > 0 {
draw[ones]()
}
printNumeral()
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <iostream>
#include <boost/multiprecision/gmp.hpp>
#include <string>
namespace mp = boost::multiprecision;
int main(int argc, char const *argv[])
{
uint64_t tmpres = mp::pow(mp::mpz_int(4)
, mp::pow(mp::mpz_int(3)
, 2).convert_to<uint64_t>()
).convert_to<uint64_t>();
mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);
std::string s = res.str();
std::cout << s.substr(0, 20)
<< "..."
<< s.substr(s.length() - 20, 20) << std::endl;
return 0;
}
| package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. |
#include <QImage>
#include <QPainter>
int main() {
const QColor black(0, 0, 0);
const QColor white(255, 255, 255);
const int size = 300;
const double diameter = 0.6 * size;
QImage image(size, size, QImage::Format_RGB32);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
QLinearGradient linearGradient(0, 0, 0, size);
linearGradient.setColorAt(0, white);
linearGradient.setColorAt(1, black);
QBrush brush(linearGradient);
painter.fillRect(QRect(0, 0, size, size), brush);
QPointF point1(0.4 * size, 0.4 * size);
QPointF point2(0.45 * size, 0.4 * size);
QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
radialGradient.setColorAt(0, white);
radialGradient.setColorAt(1, black);
QBrush brush2(radialGradient);
painter.setPen(Qt::NoPen);
painter.setBrush(brush2);
painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));
image.save("sphere.png");
return 0;
}
| package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. |
#include <QImage>
#include <QPainter>
int main() {
const QColor black(0, 0, 0);
const QColor white(255, 255, 255);
const int size = 300;
const double diameter = 0.6 * size;
QImage image(size, size, QImage::Format_RGB32);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
QLinearGradient linearGradient(0, 0, 0, size);
linearGradient.setColorAt(0, white);
linearGradient.setColorAt(1, black);
QBrush brush(linearGradient);
painter.fillRect(QRect(0, 0, size, size), brush);
QPointF point1(0.4 * size, 0.4 * size);
QPointF point2(0.45 * size, 0.4 * size);
QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
radialGradient.setColorAt(0, white);
radialGradient.setColorAt(1, black);
QBrush brush2(radialGradient);
painter.setPen(Qt::NoPen);
painter.setBrush(brush2);
painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));
image.save("sphere.png");
return 0;
}
| package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Write the same code in Go as shown below in C++. |
#include <QImage>
#include <QPainter>
int main() {
const QColor black(0, 0, 0);
const QColor white(255, 255, 255);
const int size = 300;
const double diameter = 0.6 * size;
QImage image(size, size, QImage::Format_RGB32);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
QLinearGradient linearGradient(0, 0, 0, size);
linearGradient.setColorAt(0, white);
linearGradient.setColorAt(1, black);
QBrush brush(linearGradient);
painter.fillRect(QRect(0, 0, size, size), brush);
QPointF point1(0.4 * size, 0.4 * size);
QPointF point2(0.45 * size, 0.4 * size);
QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
radialGradient.setColorAt(0, white);
radialGradient.setColorAt(1, black);
QBrush brush2(radialGradient);
painter.setPen(Qt::NoPen);
painter.setBrush(brush2);
painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));
image.save("sphere.png");
return 0;
}
| package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/";
const size_t MAX_NODES = 41;
class node
{
public:
node() { clear(); }
node( char z ) { clear(); }
~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }
void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }
bool isWord;
std::vector<std::string> files;
node* next[MAX_NODES];
};
class index {
public:
void add( std::string s, std::string fileName ) {
std::transform( s.begin(), s.end(), s.begin(), tolower );
std::string h;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
if( *i == 32 ) {
pushFileName( addWord( h ), fileName );
h.clear();
continue;
}
h.append( 1, *i );
}
if( h.length() )
pushFileName( addWord( h ), fileName );
}
void findWord( std::string s ) {
std::vector<std::string> v = find( s );
if( !v.size() ) {
std::cout << s + " was not found!\n";
return;
}
std::cout << s << " found in:\n";
for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {
std::cout << *i << "\n";
}
std::cout << "\n";
}
private:
void pushFileName( node* n, std::string fn ) {
std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );
if( i == n->files.end() ) n->files.push_back( fn );
}
const std::vector<std::string>& find( std::string s ) {
size_t idx;
std::transform( s.begin(), s.end(), s.begin(), tolower );
node* rt = &root;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
idx = _CHARS.find( *i );
if( idx < MAX_NODES ) {
if( !rt->next[idx] ) return std::vector<std::string>();
rt = rt->next[idx];
}
}
if( rt->isWord ) return rt->files;
return std::vector<std::string>();
}
node* addWord( std::string s ) {
size_t idx;
node* rt = &root, *n;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
idx = _CHARS.find( *i );
if( idx < MAX_NODES ) {
n = rt->next[idx];
if( n ){
rt = n;
continue;
}
n = new node( *i );
rt->next[idx] = n;
rt = n;
}
}
rt->isWord = true;
return rt;
}
node root;
};
int main( int argc, char* argv[] ) {
index t;
std::string s;
std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" };
for( int x = 0; x < 3; x++ ) {
std::ifstream f;
f.open( files[x].c_str(), std::ios::in );
if( f.good() ) {
while( !f.eof() ) {
f >> s;
t.add( s, files[x] );
s.clear();
}
f.close();
}
}
while( true ) {
std::cout << "Enter one word to search for, return to exit: ";
std::getline( std::cin, s );
if( !s.length() ) break;
t.findWord( s );
}
return 0;
}
| package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
)
var index map[string][]int
var indexed []doc
type doc struct {
file string
title string
}
func main() {
index = make(map[string][]int)
if err := indexDir("docs"); err != nil {
fmt.Println(err)
return
}
ui()
}
func indexDir(dir string) error {
df, err := os.Open(dir)
if err != nil {
return err
}
fis, err := df.Readdir(-1)
if err != nil {
return err
}
if len(fis) == 0 {
return errors.New(fmt.Sprintf("no files in %s", dir))
}
indexed := 0
for _, fi := range fis {
if !fi.IsDir() {
if indexFile(dir + "/" + fi.Name()) {
indexed++
}
}
}
return nil
}
func indexFile(fn string) bool {
f, err := os.Open(fn)
if err != nil {
fmt.Println(err)
return false
}
x := len(indexed)
indexed = append(indexed, doc{fn, fn})
pdoc := &indexed[x]
r := bufio.NewReader(f)
lines := 0
for {
b, isPrefix, err := r.ReadLine()
switch {
case err == io.EOF:
return true
case err != nil:
fmt.Println(err)
return true
case isPrefix:
fmt.Printf("%s: unexpected long line\n", fn)
return true
case lines < 20 && bytes.HasPrefix(b, []byte("Title:")):
pdoc.title = string(b[7:])
}
wordLoop:
for _, bword := range bytes.Fields(b) {
bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@")
if len(bword) > 0 {
word := string(bword)
dl := index[word]
for _, d := range dl {
if d == x {
continue wordLoop
}
}
index[word] = append(dl, x)
}
}
}
return true
}
func ui() {
fmt.Println(len(index), "words indexed in", len(indexed), "files")
fmt.Println("enter single words to search for")
fmt.Println("enter a blank line when done")
var word string
for {
fmt.Print("search word: ")
wc, _ := fmt.Scanln(&word)
if wc == 0 {
return
}
switch dl := index[word]; len(dl) {
case 0:
fmt.Println("no match")
case 1:
fmt.Println("one match:")
fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title)
default:
fmt.Println(len(dl), "matches:")
for _, d := range dl {
fmt.Println(" ", indexed[d].file, indexed[d].title)
}
}
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <boost/math/common_factor.hpp>
#include <iostream>
int main( ) {
std::cout << "The least common multiple of 12 and 18 is " <<
boost::math::lcm( 12 , 18 ) << " ,\n"
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 0 ;
}
| package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <boost/math/common_factor.hpp>
#include <iostream>
int main( ) {
std::cout << "The least common multiple of 12 and 18 is " <<
boost::math::lcm( 12 , 18 ) << " ,\n"
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 0 ;
}
| package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <iostream>
#include <ctime>
#include <cstdlib>
int main(){
srand(time(NULL));
while(true){
const int a = rand() % 20;
std::cout << a << std::endl;
if(a == 10)
break;
const int b = rand() % 20;
std::cout << b << std::endl;
}
return 0;
}
| package main
import "fmt"
import "math/rand"
import "time"
func main() {
rand.Seed(time.Now().UnixNano())
for {
a := rand.Intn(20)
fmt.Println(a)
if a == 10 {
break
}
b := rand.Intn(20)
fmt.Println(b)
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
| package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
| package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <iostream>
#include <vector>
#include <algorithm>
enum { EMPTY, WALL, WATER };
auto fill(const std::vector<int> b) {
auto water = 0;
const auto rows = *std::max_element(std::begin(b), std::end(b));
const auto cols = std::size(b);
std::vector<std::vector<int>> g(rows);
for (auto& r : g) {
for (auto i = 0; i < cols; ++i) {
r.push_back(EMPTY);
}
}
for (auto c = 0; c < cols; ++c) {
for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {
g[r][c] = WALL;
}
}
for (auto c = 0; c < cols - 1; ++c) {
auto start_row = rows - b[c];
while (start_row < rows) {
if (g[start_row][c] == EMPTY) break;
auto c2 = c + 1;
bool hitWall = false;
while (c2 < cols) {
if (g[start_row][c2] == WALL) {
hitWall = true;
break;
}
++c2;
}
if (hitWall) {
for (auto i = c + 1; i < c2; ++i) {
g[start_row][i] = WATER;
++water;
}
}
++start_row;
}
}
return water;
}
int main() {
std::vector<std::vector<int>> b = {
{ 1, 5, 3, 7, 2 },
{ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
{ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
{ 5, 5, 5, 5 },
{ 5, 6, 7, 8 },
{ 8, 7, 7, 6 },
{ 6, 7, 10, 7, 6 }
};
for (const auto v : b) {
auto water = fill(v);
std::cout << water << " water drops." << std::endl;
}
std::cin.ignore();
std::cin.get();
return 0;
}
| package main
import "fmt"
func maxl(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := 0; i < len(hm);i++{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func maxr(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := len(hm) - 1 ; i >= 0;i--{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func min(a,b []int) []int {
res := make([]int,len(a))
for i := 0; i < len(a);i++{
if a[i] >= b[i]{
res[i] = b[i]
}else {
res[i] = a[i]
}
}
return res
}
func diff(hm, min []int) []int {
res := make([]int,len(hm))
for i := 0; i < len(hm);i++{
if min[i] > hm[i]{
res[i] = min[i] - hm[i]
}
}
return res
}
func sum(a []int) int {
res := 0
for i := 0; i < len(a);i++{
res += a[i]
}
return res
}
func waterCollected(hm []int) int {
maxr := maxr(hm)
maxl := maxl(hm)
min := min(maxr,maxl)
diff := diff(hm,min)
sum := sum(diff)
return sum
}
func main() {
fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
fmt.Println(waterCollected([]int{5, 5, 5, 5}))
fmt.Println(waterCollected([]int{5, 6, 7, 8}))
fmt.Println(waterCollected([]int{8, 7, 7, 6}))
fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <vector>
#include <algorithm>
enum { EMPTY, WALL, WATER };
auto fill(const std::vector<int> b) {
auto water = 0;
const auto rows = *std::max_element(std::begin(b), std::end(b));
const auto cols = std::size(b);
std::vector<std::vector<int>> g(rows);
for (auto& r : g) {
for (auto i = 0; i < cols; ++i) {
r.push_back(EMPTY);
}
}
for (auto c = 0; c < cols; ++c) {
for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {
g[r][c] = WALL;
}
}
for (auto c = 0; c < cols - 1; ++c) {
auto start_row = rows - b[c];
while (start_row < rows) {
if (g[start_row][c] == EMPTY) break;
auto c2 = c + 1;
bool hitWall = false;
while (c2 < cols) {
if (g[start_row][c2] == WALL) {
hitWall = true;
break;
}
++c2;
}
if (hitWall) {
for (auto i = c + 1; i < c2; ++i) {
g[start_row][i] = WATER;
++water;
}
}
++start_row;
}
}
return water;
}
int main() {
std::vector<std::vector<int>> b = {
{ 1, 5, 3, 7, 2 },
{ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
{ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
{ 5, 5, 5, 5 },
{ 5, 6, 7, 8 },
{ 8, 7, 7, 6 },
{ 6, 7, 10, 7, 6 }
};
for (const auto v : b) {
auto water = fill(v);
std::cout << water << " water drops." << std::endl;
}
std::cin.ignore();
std::cin.get();
return 0;
}
| package main
import "fmt"
func maxl(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := 0; i < len(hm);i++{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func maxr(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := len(hm) - 1 ; i >= 0;i--{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func min(a,b []int) []int {
res := make([]int,len(a))
for i := 0; i < len(a);i++{
if a[i] >= b[i]{
res[i] = b[i]
}else {
res[i] = a[i]
}
}
return res
}
func diff(hm, min []int) []int {
res := make([]int,len(hm))
for i := 0; i < len(hm);i++{
if min[i] > hm[i]{
res[i] = min[i] - hm[i]
}
}
return res
}
func sum(a []int) int {
res := 0
for i := 0; i < len(a);i++{
res += a[i]
}
return res
}
func waterCollected(hm []int) int {
maxr := maxr(hm)
maxl := maxl(hm)
min := min(maxr,maxl)
diff := diff(hm,min)
sum := sum(diff)
return sum
}
func main() {
fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
fmt.Println(waterCollected([]int{5, 5, 5, 5}))
fmt.Println(waterCollected([]int{5, 6, 7, 8}))
fmt.Println(waterCollected([]int{8, 7, 7, 6}))
fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <iostream>
bool ispr(unsigned int n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (unsigned int j = 3; j * j <= n; j += 2)
if (n % j == 0) return false; return true; }
int main() {
unsigned int c = 0, nc, pc = 9, i, a, b, l,
ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];
while (true) {
nc = 0;
for (i = 0; i < pc; i++) {
if (ispr(a = ps[i]))
printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
for (b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
else break;
}
printf("\n%d descending primes found", c);
}
| package main
import (
"fmt"
"rcu"
"sort"
"strconv"
)
func combinations(a []int, k int) [][]int {
n := len(a)
c := make([]int, k)
var combs [][]int
var combine func(start, end, index int)
combine = func(start, end, index int) {
if index == k {
t := make([]int, len(c))
copy(t, c)
combs = append(combs, t)
return
}
for i := start; i <= end && end-i+1 >= k-index; i++ {
c[index] = a[i]
combine(i+1, end, index+1)
}
}
combine(0, n-1, 0)
return combs
}
func powerset(a []int) (res [][]int) {
if len(a) == 0 {
return
}
for i := 1; i <= len(a); i++ {
res = append(res, combinations(a, i)...)
}
return
}
func main() {
ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
var descPrimes []int
for i := 1; i < len(ps); i++ {
s := ""
for _, e := range ps[i] {
s += string(e + '0')
}
p, _ := strconv.Atoi(s)
if rcu.IsPrime(p) {
descPrimes = append(descPrimes, p)
}
}
sort.Ints(descPrimes)
fmt.Println("There are", len(descPrimes), "descending primes, namely:")
for i := 0; i < len(descPrimes); i++ {
fmt.Printf("%8d ", descPrimes[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <iostream>
bool ispr(unsigned int n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (unsigned int j = 3; j * j <= n; j += 2)
if (n % j == 0) return false; return true; }
int main() {
unsigned int c = 0, nc, pc = 9, i, a, b, l,
ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];
while (true) {
nc = 0;
for (i = 0; i < pc; i++) {
if (ispr(a = ps[i]))
printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
for (b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
else break;
}
printf("\n%d descending primes found", c);
}
| package main
import (
"fmt"
"rcu"
"sort"
"strconv"
)
func combinations(a []int, k int) [][]int {
n := len(a)
c := make([]int, k)
var combs [][]int
var combine func(start, end, index int)
combine = func(start, end, index int) {
if index == k {
t := make([]int, len(c))
copy(t, c)
combs = append(combs, t)
return
}
for i := start; i <= end && end-i+1 >= k-index; i++ {
c[index] = a[i]
combine(i+1, end, index+1)
}
}
combine(0, n-1, 0)
return combs
}
func powerset(a []int) (res [][]int) {
if len(a) == 0 {
return
}
for i := 1; i <= len(a); i++ {
res = append(res, combinations(a, i)...)
}
return
}
func main() {
ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
var descPrimes []int
for i := 1; i < len(ps); i++ {
s := ""
for _, e := range ps[i] {
s += string(e + '0')
}
p, _ := strconv.Atoi(s)
if rcu.IsPrime(p) {
descPrimes = append(descPrimes, p)
}
}
sort.Ints(descPrimes)
fmt.Println("There are", len(descPrimes), "descending primes, namely:")
for i := 0; i < len(descPrimes); i++ {
fmt.Printf("%8d ", descPrimes[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
bool square_free(integer n) {
if (n % 4 == 0)
return false;
for (integer p = 3; p * p <= n; p += 2) {
integer count = 0;
for (; n % p == 0; n /= p) {
if (++count > 1)
return false;
}
}
return true;
}
void print_square_free_numbers(integer from, integer to) {
std::cout << "Square-free numbers between " << from
<< " and " << to << ":\n";
std::string line;
for (integer i = from; i <= to; ++i) {
if (square_free(i)) {
if (!line.empty())
line += ' ';
line += std::to_string(i);
if (line.size() >= 80) {
std::cout << line << '\n';
line.clear();
}
}
}
if (!line.empty())
std::cout << line << '\n';
}
void print_square_free_count(integer from, integer to) {
integer count = 0;
for (integer i = from; i <= to; ++i) {
if (square_free(i))
++count;
}
std::cout << "Number of square-free numbers between "
<< from << " and " << to << ": " << count << '\n';
}
int main() {
print_square_free_numbers(1, 145);
print_square_free_numbers(1000000000000LL, 1000000000145LL);
print_square_free_count(1, 100);
print_square_free_count(1, 1000);
print_square_free_count(1, 10000);
print_square_free_count(1, 100000);
print_square_free_count(1, 1000000);
return 0;
}
| package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1)
p := uint64(3)
for {
p2 := p * p
if p2 > limit {
break
}
for i := p2; i <= limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
for i := uint64(3); i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
func squareFree(from, to uint64) (results []uint64) {
limit := uint64(math.Sqrt(float64(to)))
primes := sieve(limit)
outer:
for i := from; i <= to; i++ {
for _, p := range primes {
p2 := p * p
if p2 > i {
break
}
if i%p2 == 0 {
continue outer
}
}
results = append(results, i)
}
return
}
const trillion uint64 = 1000000000000
func main() {
fmt.Println("Square-free integers from 1 to 145:")
sf := squareFree(1, 145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%20 == 0 {
fmt.Println()
}
fmt.Printf("%4d", sf[i])
}
fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
sf = squareFree(trillion, trillion+145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%5 == 0 {
fmt.Println()
}
fmt.Printf("%14d", sf[i])
}
fmt.Println("\n\nNumber of square-free integers:\n")
a := [...]uint64{100, 1000, 10000, 100000, 1000000}
for _, n := range a {
fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <algorithm>
#include <iostream>
#include <string>
double jaro(const std::string s1, const std::string s2) {
const uint l1 = s1.length(), l2 = s2.length();
if (l1 == 0)
return l2 == 0 ? 1.0 : 0.0;
const uint match_distance = std::max(l1, l2) / 2 - 1;
bool s1_matches[l1];
bool s2_matches[l2];
std::fill(s1_matches, s1_matches + l1, false);
std::fill(s2_matches, s2_matches + l2, false);
uint matches = 0;
for (uint i = 0; i < l1; i++)
{
const int end = std::min(i + match_distance + 1, l2);
for (int k = std::max(0u, i - match_distance); k < end; k++)
if (!s2_matches[k] && s1[i] == s2[k])
{
s1_matches[i] = true;
s2_matches[k] = true;
matches++;
break;
}
}
if (matches == 0)
return 0.0;
double t = 0.0;
uint k = 0;
for (uint i = 0; i < l1; i++)
if (s1_matches[i])
{
while (!s2_matches[k]) k++;
if (s1[i] != s2[k]) t += 0.5;
k++;
}
const double m = matches;
return (m / l1 + m / l2 + (m - t) / m) / 3.0;
}
int main() {
using namespace std;
cout << jaro("MARTHA", "MARHTA") << endl;
cout << jaro("DIXON", "DICKSONX") << endl;
cout << jaro("JELLYFISH", "SMELLYFISH") << endl;
return 0;
}
| package main
import "fmt"
func jaro(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_distance = match_distance/2 - 1
str1_matches := make([]bool, len(str1))
str2_matches := make([]bool, len(str2))
matches := 0.
transpositions := 0.
for i := range str1 {
start := i - match_distance
if start < 0 {
start = 0
}
end := i + match_distance + 1
if end > len(str2) {
end = len(str2)
}
for k := start; k < end; k++ {
if str2_matches[k] {
continue
}
if str1[i] != str2[k] {
continue
}
str1_matches[i] = true
str2_matches[k] = true
matches++
break
}
}
if matches == 0 {
return 0
}
k := 0
for i := range str1 {
if !str1_matches[i] {
continue
}
for !str2_matches[k] {
k++
}
if str1[i] != str2[k] {
transpositions++
}
k++
}
transpositions /= 2
return (matches/float64(len(str1)) +
matches/float64(len(str2)) +
(matches-transpositions)/matches) / 3
}
func main() {
fmt.Printf("%f\n", jaro("MARTHA", "MARHTA"))
fmt.Printf("%f\n", jaro("DIXON", "DICKSONX"))
fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"))
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <iostream>
#include <map>
#include <vector>
std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {
for (auto &p : v) {
auto sum = p.first + p.second;
auto prod = p.first * p.second;
os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod;
}
return os << '\n';
}
void print_count(const std::vector<std::pair<int, int>> &candidates) {
auto c = candidates.size();
if (c == 0) {
std::cout << "no candidates\n";
} else if (c == 1) {
std::cout << "one candidate\n";
} else {
std::cout << c << " candidates\n";
}
}
auto setup() {
std::vector<std::pair<int, int>> candidates;
for (int x = 2; x <= 98; x++) {
for (int y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
candidates.push_back(std::make_pair(x, y));
}
}
}
return candidates;
}
void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[sum](const std::pair<int, int> &pair) {
auto s = pair.first + pair.second;
return s == sum;
}
), candidates.end());
}
void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[prod](const std::pair<int, int> &pair) {
auto p = pair.first * pair.second;
return p == prod;
}
), candidates.end());
}
void statement1(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] == 1) {
auto sum = pair.first + pair.second;
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
void statement2(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] > 1) {
remove_by_prod(candidates, prod);
loop = true;
break;
}
}
} while (loop);
}
void statement3(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto sum = pair.first + pair.second;
uniqueMap[sum]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto sum = pair.first + pair.second;
if (uniqueMap[sum] > 1) {
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
int main() {
auto candidates = setup();
print_count(candidates);
statement1(candidates);
print_count(candidates);
statement2(candidates);
print_count(candidates);
statement3(candidates);
print_count(candidates);
std::cout << candidates;
return 0;
}
| package main
import "fmt"
type pair struct{ x, y int }
func main() {
const max = 1685
var all []pair
for a := 2; a < max; a++ {
for b := a + 1; b < max-a; b++ {
all = append(all, pair{a, b})
}
}
fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
products := countProducts(all)
var sPairs []pair
pairs:
for _, p := range all {
s := p.x + p.y
for a := 2; a < s/2+s&1; a++ {
b := s - a
if products[a*b] == 1 {
continue pairs
}
}
sPairs = append(sPairs, p)
}
fmt.Println("S starts with", len(sPairs), "possible pairs.")
sProducts := countProducts(sPairs)
var pPairs []pair
for _, p := range sPairs {
if sProducts[p.x*p.y] == 1 {
pPairs = append(pPairs, p)
}
}
fmt.Println("P then has", len(pPairs), "possible pairs.")
pSums := countSums(pPairs)
var final []pair
for _, p := range pPairs {
if pSums[p.x+p.y] == 1 {
final = append(final, p)
}
}
switch len(final) {
case 1:
fmt.Println("Answer:", final[0].x, "and", final[0].y)
case 0:
fmt.Println("No possible answer.")
default:
fmt.Println(len(final), "possible answers:", final)
}
}
func countProducts(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x*p.y]++
}
return m
}
func countSums(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x+p.y]++
}
return m
}
func decomposeSum(s int) []pair {
pairs := make([]pair, 0, s/2)
for a := 2; a < s/2+s&1; a++ {
pairs = append(pairs, pair{a, s - a})
}
return pairs
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <algorithm>
#include <iostream>
#include <map>
#include <vector>
std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {
for (auto &p : v) {
auto sum = p.first + p.second;
auto prod = p.first * p.second;
os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod;
}
return os << '\n';
}
void print_count(const std::vector<std::pair<int, int>> &candidates) {
auto c = candidates.size();
if (c == 0) {
std::cout << "no candidates\n";
} else if (c == 1) {
std::cout << "one candidate\n";
} else {
std::cout << c << " candidates\n";
}
}
auto setup() {
std::vector<std::pair<int, int>> candidates;
for (int x = 2; x <= 98; x++) {
for (int y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
candidates.push_back(std::make_pair(x, y));
}
}
}
return candidates;
}
void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[sum](const std::pair<int, int> &pair) {
auto s = pair.first + pair.second;
return s == sum;
}
), candidates.end());
}
void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[prod](const std::pair<int, int> &pair) {
auto p = pair.first * pair.second;
return p == prod;
}
), candidates.end());
}
void statement1(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] == 1) {
auto sum = pair.first + pair.second;
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
void statement2(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] > 1) {
remove_by_prod(candidates, prod);
loop = true;
break;
}
}
} while (loop);
}
void statement3(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto sum = pair.first + pair.second;
uniqueMap[sum]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto sum = pair.first + pair.second;
if (uniqueMap[sum] > 1) {
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
int main() {
auto candidates = setup();
print_count(candidates);
statement1(candidates);
print_count(candidates);
statement2(candidates);
print_count(candidates);
statement3(candidates);
print_count(candidates);
std::cout << candidates;
return 0;
}
| package main
import "fmt"
type pair struct{ x, y int }
func main() {
const max = 1685
var all []pair
for a := 2; a < max; a++ {
for b := a + 1; b < max-a; b++ {
all = append(all, pair{a, b})
}
}
fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
products := countProducts(all)
var sPairs []pair
pairs:
for _, p := range all {
s := p.x + p.y
for a := 2; a < s/2+s&1; a++ {
b := s - a
if products[a*b] == 1 {
continue pairs
}
}
sPairs = append(sPairs, p)
}
fmt.Println("S starts with", len(sPairs), "possible pairs.")
sProducts := countProducts(sPairs)
var pPairs []pair
for _, p := range sPairs {
if sProducts[p.x*p.y] == 1 {
pPairs = append(pPairs, p)
}
}
fmt.Println("P then has", len(pPairs), "possible pairs.")
pSums := countSums(pPairs)
var final []pair
for _, p := range pPairs {
if pSums[p.x+p.y] == 1 {
final = append(final, p)
}
}
switch len(final) {
case 1:
fmt.Println("Answer:", final[0].x, "and", final[0].y)
case 0:
fmt.Println("No possible answer.")
default:
fmt.Println(len(final), "possible answers:", final)
}
}
func countProducts(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x*p.y]++
}
return m
}
func countSums(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x+p.y]++
}
return m
}
func decomposeSum(s int) []pair {
pairs := make([]pair, 0, s/2)
for a := 2; a < s/2+s&1; a++ {
pairs = append(pairs, pair{a, s - a})
}
return pairs
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <iostream>
#include <vector>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
printf("Base %2d:", base);
for (int i = 0; i < count; i++) {
int t = turn(base, i);
printf(" %2d", t);
}
printf("\n");
}
void turnCount(int base, int count) {
std::vector<int> cnt(base, 0);
for (int i = 0; i < count; i++) {
int t = turn(base, i);
cnt[t]++;
}
int minTurn = INT_MAX;
int maxTurn = INT_MIN;
int portion = 0;
for (int i = 0; i < base; i++) {
if (cnt[i] > 0) {
portion++;
}
if (cnt[i] < minTurn) {
minTurn = cnt[i];
}
if (cnt[i] > maxTurn) {
maxTurn = cnt[i];
}
}
printf(" With %d people: ", base);
if (0 == minTurn) {
printf("Only %d have a turn\n", portion);
} else if (minTurn == maxTurn) {
printf("%d\n", minTurn);
} else {
printf("%d or %d\n", minTurn, maxTurn);
}
}
int main() {
fairshare(2, 25);
fairshare(3, 25);
fairshare(5, 25);
fairshare(11, 25);
printf("How many times does each get a turn in 50000 iterations?\n");
turnCount(191, 50000);
turnCount(1377, 50000);
turnCount(49999, 50000);
turnCount(50000, 50000);
turnCount(50001, 50000);
return 0;
}
| package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func fairshare(n, base int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
j := i
sum := 0
for j > 0 {
sum += j % base
j /= base
}
res[i] = sum % base
}
return res
}
func turns(n int, fss []int) string {
m := make(map[int]int)
for _, fs := range fss {
m[fs]++
}
m2 := make(map[int]int)
for _, v := range m {
m2[v]++
}
res := []int{}
sum := 0
for k, v := range m2 {
sum += v
res = append(res, k)
}
if sum != n {
return fmt.Sprintf("only %d have a turn", sum)
}
sort.Ints(res)
res2 := make([]string, len(res))
for i := range res {
res2[i] = strconv.Itoa(res[i])
}
return strings.Join(res2, " or ")
}
func main() {
for _, base := range []int{2, 3, 5, 11} {
fmt.Printf("%2d : %2d\n", base, fairshare(25, base))
}
fmt.Println("\nHow many times does each get a turn in 50000 iterations?")
for _, base := range []int{191, 1377, 49999, 50000, 50001} {
t := turns(base, fairshare(50000, base))
fmt.Printf(" With %d people: %s\n", base, t)
}
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <array>
#include <iomanip>
#include <iostream>
#include <random>
#include <sstream>
class Roulette {
private:
std::array<bool, 6> cylinder;
std::mt19937 gen;
std::uniform_int_distribution<> distrib;
int next_int() {
return distrib(gen);
}
void rshift() {
std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());
}
void unload() {
std::fill(cylinder.begin(), cylinder.end(), false);
}
void load() {
while (cylinder[0]) {
rshift();
}
cylinder[0] = true;
rshift();
}
void spin() {
int lim = next_int();
for (int i = 1; i < lim; i++) {
rshift();
}
}
bool fire() {
auto shot = cylinder[0];
rshift();
return shot;
}
public:
Roulette() {
std::random_device rd;
gen = std::mt19937(rd());
distrib = std::uniform_int_distribution<>(1, 6);
unload();
}
int method(const std::string &s) {
unload();
for (auto c : s) {
switch (c) {
case 'L':
load();
break;
case 'S':
spin();
break;
case 'F':
if (fire()) {
return 1;
}
break;
}
}
return 0;
}
};
std::string mstring(const std::string &s) {
std::stringstream ss;
bool first = true;
auto append = [&ss, &first](const std::string s) {
if (first) {
first = false;
} else {
ss << ", ";
}
ss << s;
};
for (auto c : s) {
switch (c) {
case 'L':
append("load");
break;
case 'S':
append("spin");
break;
case 'F':
append("fire");
break;
}
}
return ss.str();
}
void test(const std::string &src) {
const int tests = 100000;
int sum = 0;
Roulette r;
for (int t = 0; t < tests; t++) {
sum += r.method(src);
}
double pc = 100.0 * sum / tests;
std::cout << std::left << std::setw(40) << mstring(src) << " produces " << pc << "% deaths.\n";
}
int main() {
test("LSLSFSF");
test("LSLSFF");
test("LLSFSF");
test("LLSFF");
return 0;
}
| package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
var cylinder = [6]bool{}
func rshift() {
t := cylinder[5]
for i := 4; i >= 0; i-- {
cylinder[i+1] = cylinder[i]
}
cylinder[0] = t
}
func unload() {
for i := 0; i < 6; i++ {
cylinder[i] = false
}
}
func load() {
for cylinder[0] {
rshift()
}
cylinder[0] = true
rshift()
}
func spin() {
var lim = 1 + rand.Intn(6)
for i := 1; i < lim; i++ {
rshift()
}
}
func fire() bool {
shot := cylinder[0]
rshift()
return shot
}
func method(s string) int {
unload()
for _, c := range s {
switch c {
case 'L':
load()
case 'S':
spin()
case 'F':
if fire() {
return 1
}
}
}
return 0
}
func mstring(s string) string {
var l []string
for _, c := range s {
switch c {
case 'L':
l = append(l, "load")
case 'S':
l = append(l, "spin")
case 'F':
l = append(l, "fire")
}
}
return strings.Join(l, ", ")
}
func main() {
rand.Seed(time.Now().UnixNano())
tests := 100000
for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} {
sum := 0
for t := 1; t <= tests; t++ {
sum += method(m)
}
pc := float64(sum) * 100 / float64(tests)
fmt.Printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <ciso646>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
using std::vector;
using std::string;
#include <exception>
#include <stdexcept>
template <typename...Args> std::runtime_error error( Args...args )
{
return std::runtime_error( (std::ostringstream{} << ... << args).str() );
};
template <typename T> struct stack : public std::vector <T>
{
using base_type = std::vector <T> ;
T push ( const T& x ) { base_type::push_back( x ); return x; }
const T& top () { return base_type::back(); }
T pop () { T x = std::move( top() ); base_type::pop_back(); return x; }
bool empty() { return base_type::empty(); }
};
using Number = double;
using Operator_Name = string;
using Precedence = int;
enum class Associates { none, left_to_right, right_to_left };
struct Operator_Info { Precedence precedence; Associates associativity; };
std::unordered_map <Operator_Name, Operator_Info> Operators =
{
{ "^", { 4, Associates::right_to_left } },
{ "*", { 3, Associates::left_to_right } },
{ "/", { 3, Associates::left_to_right } },
{ "+", { 2, Associates::left_to_right } },
{ "-", { 2, Associates::left_to_right } },
};
Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; }
Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }
using Token = string;
bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); }
bool is_operator ( const Token& t ) { return Operators.count( t ); }
bool is_open_parenthesis ( const Token& t ) { return t == "("; }
bool is_close_parenthesis( const Token& t ) { return t == ")"; }
bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }
template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )
{
std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs;
}
#include <iomanip>
struct Progressive_Display
{
string token_name;
string token_type;
Progressive_Display()
{
std::cout << "\n"
" INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n"
"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n";
}
Progressive_Display& operator () ( const Token& token )
{
token_name = token;
token_type = is_operator ( token ) ? "op"
: is_parenthesis( token ) ? "()"
: is_number ( token ) ? "num"
: "";
return *this;
}
Progressive_Display& operator () (
const string & description,
const stack <Token> & stack,
const vector <Token> & output )
{
std::cout << std::right
<< std::setw( 7 ) << token_name << " │ " << std::left
<< std::setw( 4 ) << token_type << " │ "
<< std::setw( 16 ) << description << " │ "
<< std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ "
<< output << "\n";
return operator () ( "" );
}
};
vector <Token> parse( const vector <Token> & tokens )
{
vector <Token> output;
stack <Token> stack;
Progressive_Display display;
for (auto token : tokens)
if (is_number( token ))
{
output.push_back( token );
display( token )( "num --> output", stack, output );
}
else if (is_operator( token ) or is_parenthesis( token ))
{
display( token );
if (!is_open_parenthesis( token ))
{
while (!stack.empty()
and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))
or (precedence( stack.top() ) > precedence( token ))
or ( (precedence( stack.top() ) == precedence( token ))
and (associativity( token ) == Associates::left_to_right))))
{
output.push_back( stack.pop() );
display( "pop --> output", stack, output );
}
if (is_close_parenthesis( token ))
{
stack.pop();
display( "pop", stack, output );
}
}
if (!is_close_parenthesis( token ))
{
stack.push( token );
display( "push op", stack, output );
}
}
else throw error( "unexpected token: ", token );
display( "END" );
while (!stack.empty())
{
output.push_back( stack.pop() );
display( "pop --> output", stack, output );
}
return output;
}
int main( int argc, char** argv )
try
{
auto tokens = vector <Token> ( argv+1, argv+argc );
auto rpn_expr = parse( tokens );
std::cout
<< "\nInfix = " << tokens
<< "\nRPN = " << rpn_expr
<< "\n";
}
catch (std::exception e)
{
std::cerr << "error: " << e.what() << "\n";
return 1;
}
| package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
fmt.Println("postfix:", parseInfix(input))
}
func parseInfix(e string) (rpn string) {
var stack []string
for _, tok := range strings.Fields(e) {
switch tok {
case "(":
stack = append(stack, tok)
case ")":
var op string
for {
op, stack = stack[len(stack)-1], stack[:len(stack)-1]
if op == "(" {
break
}
rpn += " " + op
}
default:
if o1, isOp := opa[tok]; isOp {
for len(stack) > 0 {
op := stack[len(stack)-1]
if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||
o1.prec == o2.prec && o1.rAssoc {
break
}
stack = stack[:len(stack)-1]
rpn += " " + op
}
stack = append(stack, tok)
} else {
if rpn > "" {
rpn += " "
}
rpn += tok
}
}
}
for len(stack) > 0 {
rpn += " " + stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
return
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <cassert>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
bool is_prime(unsigned int n) {
assert(n > 0 && n < 64);
return (1ULL << n) & 0x28208a20a08a28ac;
}
template <typename Iterator>
bool prime_triangle_row(Iterator begin, Iterator end) {
if (std::distance(begin, end) == 2)
return is_prime(*begin + *(begin + 1));
for (auto i = begin + 1; i + 1 != end; ++i) {
if (is_prime(*begin + *i)) {
std::iter_swap(i, begin + 1);
if (prime_triangle_row(begin + 1, end))
return true;
std::iter_swap(i, begin + 1);
}
}
return false;
}
template <typename Iterator>
void prime_triangle_count(Iterator begin, Iterator end, int& count) {
if (std::distance(begin, end) == 2) {
if (is_prime(*begin + *(begin + 1)))
++count;
return;
}
for (auto i = begin + 1; i + 1 != end; ++i) {
if (is_prime(*begin + *i)) {
std::iter_swap(i, begin + 1);
prime_triangle_count(begin + 1, end, count);
std::iter_swap(i, begin + 1);
}
}
}
template <typename Iterator>
void print(Iterator begin, Iterator end) {
if (begin == end)
return;
auto i = begin;
std::cout << std::setw(2) << *i++;
for (; i != end; ++i)
std::cout << ' ' << std::setw(2) << *i;
std::cout << '\n';
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int n = 2; n < 21; ++n) {
std::vector<unsigned int> v(n);
std::iota(v.begin(), v.end(), 1);
if (prime_triangle_row(v.begin(), v.end()))
print(v.begin(), v.end());
}
std::cout << '\n';
for (unsigned int n = 2; n < 21; ++n) {
std::vector<unsigned int> v(n);
std::iota(v.begin(), v.end(), 1);
int count = 0;
prime_triangle_count(v.begin(), v.end(), count);
if (n > 2)
std::cout << ' ';
std::cout << count;
}
std::cout << '\n';
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| package main
import "fmt"
var canFollow [][]bool
var arrang []int
var bFirst = true
var pmap = make(map[int]bool)
func init() {
for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {
pmap[i] = true
}
}
func ptrs(res, n, done int) int {
ad := arrang[done-1]
if n-done <= 1 {
if canFollow[ad-1][n-1] {
if bFirst {
for _, e := range arrang {
fmt.Printf("%2d ", e)
}
fmt.Println()
bFirst = false
}
res++
}
} else {
done++
for i := done - 1; i <= n-2; i += 2 {
ai := arrang[i]
if canFollow[ad-1][ai-1] {
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
res = ptrs(res, n, done)
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
}
}
}
return res
}
func primeTriangle(n int) int {
canFollow = make([][]bool, n)
for i := 0; i < n; i++ {
canFollow[i] = make([]bool, n)
for j := 0; j < n; j++ {
_, ok := pmap[i+j+2]
canFollow[i][j] = ok
}
}
bFirst = true
arrang = make([]int, n)
for i := 0; i < n; i++ {
arrang[i] = i + 1
}
return ptrs(0, n, 1)
}
func main() {
counts := make([]int, 19)
for i := 2; i <= 20; i++ {
counts[i-2] = primeTriangle(i)
}
fmt.Println()
for i := 0; i < 19; i++ {
fmt.Printf("%d ", counts[i])
}
fmt.Println()
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
[ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
for ( int i = 10 ; i > -1 ; i-- ) {
std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ;
if ( results[ i ] > 400 )
std::cout << "too large!" ;
else
std::cout << results[ i ] << " !" ;
std::cout << std::endl ;
}
return 0 ;
}
| package main
import (
"fmt"
"log"
"math"
)
func main() {
fmt.Print("Enter 11 numbers: ")
var s [11]float64
for i := 0; i < 11; {
if n, _ := fmt.Scan(&s[i]); n > 0 {
i++
}
}
for i, item := range s[:5] {
s[i], s[10-i] = s[10-i], item
}
for _, item := range s {
if result, overflow := f(item); overflow {
log.Printf("f(%g) overflow", item)
} else {
fmt.Printf("f(%g) = %g\n", item, result)
}
}
}
func f(x float64) (float64, bool) {
result := math.Sqrt(math.Abs(x)) + 5*x*x*x
return result, result > 400
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <iostream>
std::string middleThreeDigits(int n)
{
auto number = std::to_string(std::abs(n));
auto length = number.size();
if (length < 3) {
return "less than three digits";
} else if (length % 2 == 0) {
return "even number of digits";
} else {
return number.substr(length / 2 - 1, 3);
}
}
int main()
{
auto values {123, 12345, 1234567, 987654321, 10001,
-10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0};
for (auto&& v : values) {
std::cout << "middleThreeDigits(" << v << "): " <<
middleThreeDigits(v) << "\n";
}
}
| package m3
import (
"errors"
"strconv"
)
var (
ErrorLT3 = errors.New("N of at least three digits required.")
ErrorEven = errors.New("N with odd number of digits required.")
)
func Digits(i int) (string, error) {
if i < 0 {
i = -i
}
if i < 100 {
return "", ErrorLT3
}
s := strconv.Itoa(i)
if len(s)%2 == 0 {
return "", ErrorEven
}
m := len(s) / 2
return s[m-1 : m+2], nil
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <iostream>
#include <vector>
std::vector<int> smallPrimes;
bool is_prime(size_t test) {
if (test < 2) {
return false;
}
if (test % 2 == 0) {
return test == 2;
}
for (size_t d = 3; d * d <= test; d += 2) {
if (test % d == 0) {
return false;
}
}
return true;
}
void init_small_primes(size_t numPrimes) {
smallPrimes.push_back(2);
int count = 0;
for (size_t n = 3; count < numPrimes; n += 2) {
if (is_prime(n)) {
smallPrimes.push_back(n);
count++;
}
}
}
size_t divisor_count(size_t n) {
size_t count = 1;
while (n % 2 == 0) {
n /= 2;
count++;
}
for (size_t d = 3; d * d <= n; d += 2) {
size_t q = n / d;
size_t r = n % d;
size_t dc = 0;
while (r == 0) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if (n != 1) {
count *= 2;
}
return count;
}
uint64_t OEISA073916(size_t n) {
if (is_prime(n)) {
return (uint64_t) pow(smallPrimes[n - 1], n - 1);
}
size_t count = 0;
uint64_t result = 0;
for (size_t i = 1; count < n; i++) {
if (n % 2 == 1) {
size_t root = (size_t) sqrt(i);
if (root * root != i) {
continue;
}
}
if (divisor_count(i) == n) {
count++;
result = i;
}
}
return result;
}
int main() {
const int MAX = 15;
init_small_primes(MAX);
for (size_t n = 1; n <= MAX; n++) {
if (n == 13) {
std::cout << "A073916(" << n << ") = One more bit needed to represent result.\n";
} else {
std::cout << "A073916(" << n << ") = " << OEISA073916(n) << '\n';
}
}
return 0;
}
| package main
import (
"fmt"
"math"
"math/big"
)
var bi = new(big.Int)
func isPrime(n int) bool {
bi.SetUint64(uint64(n))
return bi.ProbablyPrime(0)
}
func generateSmallPrimes(n int) []int {
primes := make([]int, n)
primes[0] = 2
for i, count := 3, 1; count < n; i += 2 {
if isPrime(i) {
primes[count] = i
count++
}
}
return primes
}
func countDivisors(n int) int {
count := 1
for n%2 == 0 {
n >>= 1
count++
}
for d := 3; d*d <= n; d += 2 {
q, r := n/d, n%d
if r == 0 {
dc := 0
for r == 0 {
dc += count
n = q
q, r = n/d, n%d
}
count += dc
}
}
if n != 1 {
count *= 2
}
return count
}
func main() {
const max = 33
primes := generateSmallPrimes(max)
z := new(big.Int)
p := new(big.Int)
fmt.Println("The first", max, "terms in the sequence are:")
for i := 1; i <= max; i++ {
if isPrime(i) {
z.SetUint64(uint64(primes[i-1]))
p.SetUint64(uint64(i - 1))
z.Exp(z, p, nil)
fmt.Printf("%2d : %d\n", i, z)
} else {
count := 0
for j := 1; ; j++ {
if i%2 == 1 {
sq := int(math.Sqrt(float64(j)))
if sq*sq != j {
continue
}
}
if countDivisors(j) == i {
count++
if count == i {
fmt.Printf("%2d : %d\n", i, j)
break
}
}
}
}
}
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <iostream>
#define MAX 15
using namespace std;
int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
int i, k, n, seq[MAX];
for (i = 0; i < MAX; ++i) seq[i] = 0;
cout << "The first " << MAX << " terms of the sequence are:" << endl;
for (i = 1, n = 0; n < MAX; ++i) {
k = count_divisors(i);
if (k <= MAX && seq[k - 1] == 0) {
seq[k - 1] = i;
++n;
}
}
for (i = 0; i < MAX; ++i) cout << seq[i] << " ";
cout << endl;
return 0;
}
| package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
seq := make([]int, max)
fmt.Println("The first", max, "terms of the sequence are:")
for i, n := 1, 0; n < max; i++ {
if k := countDivisors(i); k <= max && seq[k-1] == 0 {
seq[k-1] = i
n++
}
}
fmt.Println(seq)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iomanip>
#include <iostream>
int pancake(int n) {
int gap = 2, sum = 2, adj = -1;
while (sum < n) {
adj++;
gap = gap * 2 - 1;
sum += gap;
}
return n + adj;
}
int main() {
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 6; j++) {
int n = i * 5 + j;
std::cout << "p(" << std::setw(2) << n << ") = " << std::setw(2) << pancake(n) << " ";
}
std::cout << '\n';
}
return 0;
}
| package main
import "fmt"
func pancake(n int) int {
gap, sum, adj := 2, 2, -1
for sum < n {
adj++
gap = gap*2 - 1
sum += gap
}
return n + adj
}
func main() {
for i := 0; i < 4; i++ {
for j := 1; j < 6; j++ {
n := i*5 + j
fmt.Printf("p(%2d) = %2d ", n, pancake(n))
}
fmt.Println()
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <ctime>
#include <iostream>
#include <string>
#include <algorithm>
class chessBoard {
public:
void generateRNDBoard( int brds ) {
int a, b, i; char c;
for( int cc = 0; cc < brds; cc++ ) {
memset( brd, 0, 64 );
std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";
random_shuffle( pieces.begin(), pieces.end() );
while( pieces.length() ) {
i = rand() % pieces.length(); c = pieces.at( i );
while( true ) {
a = rand() % 8; b = rand() % 8;
if( brd[a][b] == 0 ) {
if( c == 'P' && !b || c == 'p' && b == 7 ||
( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;
break;
}
}
brd[a][b] = c;
pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );
}
print();
}
}
private:
bool search( char c, int a, int b ) {
for( int y = -1; y < 2; y++ ) {
for( int x = -1; x < 2; x++ ) {
if( !x && !y ) continue;
if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {
if( brd[a + x][b + y] == c ) return true;
}
}
}
return false;
}
void print() {
int e = 0;
for( int y = 0; y < 8; y++ ) {
for( int x = 0; x < 8; x++ ) {
if( brd[x][y] == 0 ) e++;
else {
if( e > 0 ) { std::cout << e; e = 0; }
std::cout << brd[x][y];
}
}
if( e > 0 ) { std::cout << e; e = 0; }
if( y < 7 ) std::cout << "/";
}
std::cout << " w - - 0 1\n\n";
for( int y = 0; y < 8; y++ ) {
for( int x = 0; x < 8; x++ ) {
if( brd[x][y] == 0 ) std::cout << ".";
else std::cout << brd[x][y];
}
std::cout << "\n";
}
std::cout << "\n\n";
}
char brd[8][8];
};
int main( int argc, char* argv[] ) {
srand( ( unsigned )time( 0 ) );
chessBoard c;
c.generateRNDBoard( 2 );
return 0;
}
| package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var grid [8][8]byte
func abs(i int) int {
if i >= 0 {
return i
} else {
return -i
}
}
func createFen() string {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
return toFen()
}
func placeKings() {
for {
r1 := rand.Intn(8)
c1 := rand.Intn(8)
r2 := rand.Intn(8)
c2 := rand.Intn(8)
if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {
grid[r1][c1] = 'K'
grid[r2][c2] = 'k'
return
}
}
}
func placePieces(pieces string, isPawn bool) {
numToPlace := rand.Intn(len(pieces))
for n := 0; n < numToPlace; n++ {
var r, c int
for {
r = rand.Intn(8)
c = rand.Intn(8)
if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) {
break
}
}
grid[r][c] = pieces[n]
}
}
func toFen() string {
var fen strings.Builder
countEmpty := 0
for r := 0; r < 8; r++ {
for c := 0; c < 8; c++ {
ch := grid[r][c]
if ch == '\000' {
ch = '.'
}
fmt.Printf("%2c ", ch)
if ch == '.' {
countEmpty++
} else {
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteByte(ch)
}
}
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteString("/")
fmt.Println()
}
fen.WriteString(" w - - 0 1")
return fen.String()
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(createFen())
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <functional>
#include <iostream>
#include <sstream>
#include <vector>
std::string to(int n, int b) {
static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::stringstream ss;
while (n > 0) {
auto rem = n % b;
n = n / b;
ss << BASE[rem];
}
auto fwd = ss.str();
return std::string(fwd.rbegin(), fwd.rend());
}
uint64_t uabs(uint64_t a, uint64_t b) {
if (a < b) {
return b - a;
}
return a - b;
}
bool isEsthetic(uint64_t n, uint64_t b) {
if (n == 0) {
return false;
}
auto i = n % b;
n /= b;
while (n > 0) {
auto j = n % b;
if (uabs(i, j) != 1) {
return false;
}
n /= b;
i = j;
}
return true;
}
void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {
std::vector<uint64_t> esths;
const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {
auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {
if (i >= n && i <= m) {
esths.push_back(i);
}
if (i == 0 || i > m) {
return;
}
auto d = i % 10;
auto i1 = i * 10 + d - 1;
auto i2 = i1 + 2;
if (d == 0) {
dfs_ref(n, m, i2, dfs_ref);
} else if (d == 9) {
dfs_ref(n, m, i1, dfs_ref);
} else {
dfs_ref(n, m, i1, dfs_ref);
dfs_ref(n, m, i2, dfs_ref);
}
};
dfs_impl(n, m, i, dfs_impl);
};
for (int i = 0; i < 10; i++) {
dfs(n2, m2, i);
}
auto le = esths.size();
printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m);
if (all) {
for (size_t c = 0; c < esths.size(); c++) {
auto esth = esths[c];
printf("%llu ", esth);
if ((c + 1) % perLine == 0) {
printf("\n");
}
}
printf("\n");
} else {
for (int c = 0; c < perLine; c++) {
auto esth = esths[c];
printf("%llu ", esth);
}
printf("\n............\n");
for (size_t i = le - perLine; i < le; i++) {
auto esth = esths[i];
printf("%llu ", esth);
}
printf("\n");
}
printf("\n");
}
int main() {
for (int b = 2; b <= 16; b++) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b);
for (int n = 1, c = 0; c < 6 * b; n++) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
std::cout << to(n, b) << ' ';
}
}
}
printf("\n");
}
printf("\n");
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);
listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);
listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);
listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);
return 0;
}
| package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
int topswops(int n) {
std::vector<int> list(n);
std::iota(std::begin(list), std::end(list), 1);
int max_steps = 0;
do {
auto temp_list = list;
for (int steps = 1; temp_list[0] != 1; ++steps) {
std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);
if (steps > max_steps) max_steps = steps;
}
} while (std::next_permutation(std::begin(list), std::end(list)));
return max_steps;
}
int main() {
for (int i = 1; i <= 10; ++i) {
std::cout << i << ": " << topswops(i) << std::endl;
}
return 0;
}
|
package main
import "fmt"
const (
maxn = 10
maxl = 50
)
func main() {
for i := 1; i <= maxn; i++ {
fmt.Printf("%d: %d\n", i, steps(i))
}
}
func steps(n int) int {
var a, b [maxl][maxn + 1]int
var x [maxl]int
a[0][0] = 1
var m int
for l := 0; ; {
x[l]++
k := int(x[l])
if k >= n {
if l <= 0 {
break
}
l--
continue
}
if a[l][k] == 0 {
if b[l][k+1] != 0 {
continue
}
} else if a[l][k] != k+1 {
continue
}
a[l+1] = a[l]
for j := 1; j <= k; j++ {
a[l+1][j] = a[l][k-j]
}
b[l+1] = b[l]
a[l+1][0] = k + 1
b[l+1][k+1] = 1
if l > m-1 {
m = l + 1
}
l++
x[l] = 0
}
return m
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <iostream>
#include <iomanip>
using namespace std;
class ormConverter
{
public:
ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),
MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}
void convert( char c, float l )
{
system( "cls" );
cout << endl << l;
switch( c )
{
case 'A': cout << " Arshin to:"; l *= AR; break;
case 'C': cout << " Centimeter to:"; l *= CE; break;
case 'D': cout << " Diuym to:"; l *= DI; break;
case 'F': cout << " Fut to:"; l *= FU; break;
case 'K': cout << " Kilometer to:"; l *= KI; break;
case 'L': cout << " Liniya to:"; l *= LI; break;
case 'M': cout << " Meter to:"; l *= ME; break;
case 'I': cout << " Milia to:"; l *= MI; break;
case 'P': cout << " Piad to:"; l *= PI; break;
case 'S': cout << " Sazhen to:"; l *= SA; break;
case 'T': cout << " Tochka to:"; l *= TO; break;
case 'V': cout << " Vershok to:"; l *= VE; break;
case 'E': cout << " Versta to:"; l *= VR;
}
float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,
mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;
cout << left << endl << "=================" << endl
<< setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl
<< setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl
<< setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl
<< setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl
<< setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl
<< setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl
<< setw( 12 ) << "Versta:" << vr << endl << endl << endl;
}
private:
const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;
};
int _tmain(int argc, _TCHAR* argv[])
{
ormConverter c;
char s; float l;
while( true )
{
cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n";
cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;
cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0;
c.convert( s, l ); system( "pause" ); system( "cls" );
}
return 0;
}
| package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
units := []string{
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer",
}
convs := []float32{
0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668, 74676,
1, 100, 10000,
}
scanner := bufio.NewScanner(os.Stdin)
for {
for i, u := range units {
fmt.Printf("%2d %s\n", i+1, u)
}
fmt.Println()
var unit int
var err error
for {
fmt.Print("Please choose a unit 1 to 13 : ")
scanner.Scan()
unit, err = strconv.Atoi(scanner.Text())
if err == nil && unit >= 1 && unit <= 13 {
break
}
}
unit--
var value float64
for {
fmt.Print("Now enter a value in that unit : ")
scanner.Scan()
value, err = strconv.ParseFloat(scanner.Text(), 32)
if err == nil && value >= 0 {
break
}
}
fmt.Println("\nThe equivalent in the remaining units is:\n")
for i, u := range units {
if i == unit {
continue
}
fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i])
}
fmt.Println()
yn := ""
for yn != "y" && yn != "n" {
fmt.Print("Do another one y/n : ")
scanner.Scan()
yn = strings.ToLower(scanner.Text())
}
if yn == "n" {
return
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <ctime>
class CRateState
{
protected:
time_t m_lastFlush;
time_t m_period;
size_t m_tickCount;
public:
CRateState(time_t period);
void Tick();
};
CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),
m_period(period),
m_tickCount(0)
{ }
void CRateState::Tick()
{
m_tickCount++;
time_t now = std::time(NULL);
if((now - m_lastFlush) >= m_period)
{
size_t tps = 0.0;
if(m_tickCount > 0)
tps = m_tickCount / (now - m_lastFlush);
std::cout << tps << " tics per second" << std::endl;
m_tickCount = 0;
m_lastFlush = now;
}
}
void something_we_do()
{
volatile size_t anchor = 0;
for(size_t x = 0; x < 0xffff; ++x)
{
anchor = x;
}
}
int main()
{
time_t start = std::time(NULL);
CRateState rateWatch(5);
for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))
{
something_we_do();
rateWatch.Tick();
}
return 0;
}
| package main
import (
"fmt"
"math/rand"
"time"
)
type rateStateS struct {
lastFlush time.Time
period time.Duration
tickCount int
}
func ticRate(pRate *rateStateS) {
pRate.tickCount++
now := time.Now()
if now.Sub(pRate.lastFlush) >= pRate.period {
tps := 0.
if pRate.tickCount > 0 {
tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()
}
fmt.Println(tps, "tics per second.")
pRate.tickCount = 0
pRate.lastFlush = now
}
}
func somethingWeDo() {
time.Sleep(time.Duration(9e7 + rand.Int63n(2e7)))
}
func main() {
start := time.Now()
rateWatch := rateStateS{
lastFlush: start,
period: 5 * time.Second,
}
latest := start
for latest.Sub(start) < 20*time.Second {
somethingWeDo()
ticRate(&rateWatch)
latest = time.Now()
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
#define MAX 15
using namespace std;
int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
cout << "The first " << MAX << " terms of the sequence are:" << endl;
for (int i = 1, next = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
cout << i << " ";
next++;
}
}
cout << endl;
return 0;
}
| package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
fmt.Println("The first", max, "terms of the sequence are:")
for i, next := 1, 1; next <= max; i++ {
if next == countDivisors(i) {
fmt.Printf("%d ", i)
next++
}
}
fmt.Println()
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <iostream>
#include <map>
#include <cmath>
int pRec(int n) {
static std::map<int,int> memo;
auto it = memo.find(n);
if (it != memo.end()) return it->second;
if (n <= 2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
return memo[n];
}
int pFloor(int n) {
long const double p = 1.324717957244746025960908854;
long const double s = 1.0453567932525329623;
return std::pow(p, n-1)/s + 0.5;
}
std::string& lSystem(int n) {
static std::map<int,std::string> memo;
auto it = memo.find(n);
if (it != memo.end()) return it->second;
if (n == 0) memo[n] = "A";
else {
memo[n] = "";
for (char ch : memo[n-1]) {
switch(ch) {
case 'A': memo[n].push_back('B'); break;
case 'B': memo[n].push_back('C'); break;
case 'C': memo[n].append("AB"); break;
}
}
}
return memo[n];
}
using pFn = int(*)(int);
void compare(pFn f1, pFn f2, const char* descr, int stop) {
std::cout << "The " << descr << " functions ";
int i;
for (i=0; i<stop; i++) {
int n1 = f1(i);
int n2 = f2(i);
if (n1 != n2) {
std::cout << "do not match at " << i
<< ": " << n1 << " != " << n2 << ".\n";
break;
}
}
if (i == stop) {
std::cout << "match from P_0 to P_" << stop << ".\n";
}
}
int main() {
std::cout << "P_0 .. P_19: ";
for (int i=0; i<20; i++) std::cout << pRec(i) << " ";
std::cout << "\n";
compare(pFloor, pRec, "floor- and recurrence-based", 64);
std::cout << "\nThe first 10 L-system strings are:\n";
for (int i=0; i<10; i++) std::cout << lSystem(i) << "\n";
std::cout << "\n";
compare(pFloor, [](int n){return (int)lSystem(n).length();},
"floor- and L-system-based", 32);
return 0;
}
| package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)
p, _ = p.SetString("1.324717957244746025960908854")
s, _ = s.SetString("1.0453567932525329623")
f := make([]int, n)
pow := new(big.Rat).SetInt64(1)
u = u.SetFrac64(1, 2)
t.Quo(pow, p)
t.Quo(t, s)
t.Add(t, u)
v, _ := t.Float64()
f[0] = int(math.Floor(v))
for i := 1; i < n; i++ {
t.Quo(pow, s)
t.Add(t, u)
v, _ = t.Float64()
f[i] = int(math.Floor(v))
pow.Mul(pow, p)
}
return f
}
type LSystem struct {
rules map[string]string
init, current string
}
func step(lsys *LSystem) string {
var sb strings.Builder
if lsys.current == "" {
lsys.current = lsys.init
} else {
for _, c := range lsys.current {
sb.WriteString(lsys.rules[string(c)])
}
lsys.current = sb.String()
}
return lsys.current
}
func padovanLSys(n int) []string {
rules := map[string]string{"A": "B", "B": "C", "C": "AB"}
lsys := &LSystem{rules, "A", ""}
p := make([]string, n)
for i := 0; i < n; i++ {
p[i] = step(lsys)
}
return p
}
func areSame(l1, l2 []int) bool {
for i := 0; i < len(l1); i++ {
if l1[i] != l2[i] {
return false
}
}
return true
}
func main() {
fmt.Println("First 20 members of the Padovan sequence:")
fmt.Println(padovanRecur(20))
recur := padovanRecur(64)
floor := padovanFloor(64)
same := areSame(recur, floor)
s := "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.")
p := padovanLSys(32)
lsyst := make([]int, 32)
for i := 0; i < 32; i++ {
lsyst[i] = len(p[i])
}
fmt.Println("\nFirst 10 members of the Padovan L-System:")
fmt.Println(p[:10])
fmt.Println("\nand their lengths:")
fmt.Println(lsyst[:10])
same = areSame(recur[:32], lsyst)
s = "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class tree {
public:
tree() {
bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();
clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 );
clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );
clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 );
}
void draw( int it, POINT a, POINT b ) {
if( !it ) return;
bmp.setPenColor( clr[it % 6] );
POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x };
POINT d = { a.x - df.y, a.y - df.x };
POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};
drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );
}
void save( std::string p ) { bmp.saveBitmap( p ); }
private:
void drawSqr( POINT a, POINT b, POINT c, POINT d ) {
HDC dc = bmp.getDC();
MoveToEx( dc, a.x, a.y, NULL );
LineTo( dc, b.x, b.y );
LineTo( dc, c.x, c.y );
LineTo( dc, d.x, d.y );
LineTo( dc, a.x, a.y );
}
myBitmap bmp;
DWORD clr[6];
};
int main( int argc, char* argv[] ) {
POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },
ptB = { ptA.x + LINE_LEN, ptA.y };
tree t; t.draw( 12, ptA, ptB );
t.save( "?:/pt.bmp" );
return 0;
}
| package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
)
const (
width, height = 800, 600
maxDepth = 11
colFactor = uint8(255 / maxDepth)
fileName = "pythagorasTree.png"
)
func main() {
img := image.NewNRGBA(image.Rect(0, 0, width, height))
bg := image.NewUniform(color.RGBA{255, 255, 255, 255})
draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)
drawSquares(340, 550, 460, 550, img, 0)
imgFile, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer imgFile.Close()
if err := png.Encode(imgFile, img); err != nil {
imgFile.Close()
log.Fatal(err)
}
}
func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {
if depth > maxDepth {
return
}
dx, dy := bx-ax, ay-by
x3, y3 := bx-dy, by-dx
x4, y4 := ax-dy, ay-dx
x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2
col := color.RGBA{0, uint8(depth) * colFactor, 0, 255}
drawLine(ax, ay, bx, by, img, col)
drawLine(bx, by, x3, y3, img, col)
drawLine(x3, y3, x4, y4, img, col)
drawLine(x4, y4, ax, ay, img, col)
drawSquares(x4, y4, x5, y5, img, depth+1)
drawSquares(x5, y5, x3, y3, img, depth+1)
}
func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {
dx := abs(x1 - x0)
dy := abs(y1 - y0)
var sx, sy int = -1, -1
if x0 < x1 {
sx = 1
}
if y0 < y1 {
sy = 1
}
err := dx - dy
for {
img.Set(x0, y0, col)
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 > -dy {
err -= dy
x0 += sx
}
if e2 < dx {
err += dx
y0 += sy
}
}
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
while(true) {
int c;
cout.put(c = cin.get());
if (!isalpha(c)) return c != '.';
}
}
int main()
{
bool e = false;
while( e ? odd() : even() ) e = !e;
return 0;
}
| package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader) {
byte_in := func () byte {
bs := make([]byte, 1)
src.Read(bs)
return bs[0]
}
byte_out := func (b byte) { dst.Write([]byte{b}) }
var odd func() byte
odd = func() byte {
s := byte_in()
if unicode.IsPunct(rune(s)) {
return s
}
b := odd()
byte_out(s)
return b
}
for {
for {
b := byte_in()
byte_out(b)
if b == '.' {
return
}
if unicode.IsPunct(rune(b)) {
break
}
}
b := odd()
byte_out(b)
if b == '.' {
return
}
}
}
|
Write a version of this C++ function in Go with identical behavior. | #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
while(true) {
int c;
cout.put(c = cin.get());
if (!isalpha(c)) return c != '.';
}
}
int main()
{
bool e = false;
while( e ? odd() : even() ) e = !e;
return 0;
}
| package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader) {
byte_in := func () byte {
bs := make([]byte, 1)
src.Read(bs)
return bs[0]
}
byte_out := func (b byte) { dst.Write([]byte{b}) }
var odd func() byte
odd = func() byte {
s := byte_in()
if unicode.IsPunct(rune(s)) {
return s
}
b := odd()
byte_out(s)
return b
}
for {
for {
b := byte_in()
byte_out(b)
if b == '.' {
return
}
if unicode.IsPunct(rune(b)) {
break
}
}
b := odd()
byte_out(b)
if b == '.' {
return
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <array>
#include <iostream>
int64_t mod(int64_t x, int64_t y) {
int64_t m = x % y;
if (m < 0) {
if (y < 0) {
return m - y;
} else {
return m + y;
}
}
return m;
}
class RNG {
private:
const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };
const int64_t m1 = (1LL << 32) - 209;
std::array<int64_t, 3> x1;
const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };
const int64_t m2 = (1LL << 32) - 22853;
std::array<int64_t, 3> x2;
const int64_t d = (1LL << 32) - 209 + 1;
public:
void seed(int64_t state) {
x1 = { state, 0, 0 };
x2 = { state, 0, 0 };
}
int64_t next_int() {
int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);
int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);
int64_t z = mod(x1i - x2i, m1);
x1 = { x1i, x1[0], x1[1] };
x2 = { x2i, x2[0], x2[1] };
return z + 1;
}
double next_float() {
return static_cast<double>(next_int()) / d;
}
};
int main() {
RNG rng;
rng.seed(1234567);
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << '\n';
std::array<int, 5> counts{ 0, 0, 0, 0, 0 };
rng.seed(987654321);
for (size_t i = 0; i < 100000; i++) {
auto value = floor(rng.next_float() * 5.0);
counts[value]++;
}
for (size_t i = 0; i < counts.size(); i++) {
std::cout << i << ": " << counts[i] << '\n';
}
return 0;
}
| package main
import (
"fmt"
"log"
"math"
)
var a1 = []int64{0, 1403580, -810728}
var a2 = []int64{527612, 0, -1370589}
const m1 = int64((1 << 32) - 209)
const m2 = int64((1 << 32) - 22853)
const d = m1 + 1
func mod(x, y int64) int64 {
m := x % y
if m < 0 {
if y < 0 {
return m - y
} else {
return m + y
}
}
return m
}
type MRG32k3a struct{ x1, x2 [3]int64 }
func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }
func (mrg *MRG32k3a) seed(seedState int64) {
if seedState <= 0 || seedState >= d {
log.Fatalf("Argument must be in the range [0, %d].\n", d)
}
mrg.x1 = [3]int64{seedState, 0, 0}
mrg.x2 = [3]int64{seedState, 0, 0}
}
func (mrg *MRG32k3a) nextInt() int64 {
x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)
x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)
mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]}
mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]}
return mod(x1i-x2i, m1) + 1
}
func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }
func main() {
randomGen := MRG32k3aNew()
randomGen.seed(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.