Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_curzon(uint64_t n, uint64_t k) {
const uint64_t r = k * n;
return modpow(k, n, r + 1) == r;
}
int main() {
for (uint64_t k = 2; k <= 10; k += 2) {
std::cout << "Curzon numbers with base " << k << ":\n";
uint64_t count = 0, n = 1;
for (; count < 50; ++n) {
if (is_curzon(n, k)) {
std::cout << std::setw(4) << n
<< (++count % 10 == 0 ? '\n' : ' ');
}
}
for (;;) {
if (is_curzon(n, k))
++count;
if (count == 1000)
break;
++n;
}
std::cout << "1000th Curzon number with base " << k << ": " << n
<< "\n\n";
}
return 0;
}
| package main
import (
"fmt"
"math/big"
)
func main() {
zero := big.NewInt(0)
one := big.NewInt(1)
for k := int64(2); k <= 10; k += 2 {
bk := big.NewInt(k)
fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
count := 0
n := int64(1)
pow := big.NewInt(k)
z := new(big.Int)
var curzon50 []int64
for {
z.Add(pow, one)
d := k*n + 1
bd := big.NewInt(d)
if z.Rem(z, bd).Cmp(zero) == 0 {
if count < 50 {
curzon50 = append(curzon50, n)
}
count++
if count == 50 {
for i := 0; i < len(curzon50); i++ {
fmt.Printf("%4d ", curzon50[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Print("\nOne thousandth: ")
}
if count == 1000 {
fmt.Println(n)
break
}
}
n++
pow.Mul(pow, bk)
}
fmt.Println()
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
| package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
| package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) * pi);
}
int main() {
std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
<< std::setprecision(80) << f(163) << '\n';
std::cout << "\nResult with last four Heegner numbers:\n";
std::cout << std::setprecision(30);
for (unsigned int n : {19, 43, 67, 163}) {
auto x = f(n);
auto c = ceil(x);
auto pc = 100.0 * (x/c);
std::cout << "f(" << n << ") = " << x << " = "
<< pc << "% of " << c << '\n';
}
return 0;
}
| package main
import (
"fmt"
"github.com/ALTree/bigfloat"
"math/big"
)
const (
prec = 256
ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164"
)
func q(d int64) *big.Float {
pi, _ := new(big.Float).SetPrec(prec).SetString(ps)
t := new(big.Float).SetPrec(prec).SetInt64(d)
t.Sqrt(t)
t.Mul(pi, t)
return bigfloat.Exp(t)
}
func main() {
fmt.Println("Ramanujan's constant to 32 decimal places is:")
fmt.Printf("%.32f\n", q(163))
heegners := [4][2]int64{
{19, 96},
{43, 960},
{67, 5280},
{163, 640320},
}
fmt.Println("\nHeegner numbers yielding 'almost' integers:")
t := new(big.Float).SetPrec(prec)
for _, h := range heegners {
qh := q(h[0])
c := h[1]*h[1]*h[1] + 744
t.SetInt64(c)
t.Sub(t, qh)
fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t)
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. | class animal {
public:
virtual void bark()
{
throw "implement me: do not know how to bark";
}
};
class elephant : public animal
{
};
int main()
{
elephant e;
e.bark();
}
| package main
import (
"fmt"
"reflect"
)
type example struct{}
func (example) Foo() int {
return 42
}
func (e example) CallMethod(n string) int {
if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {
return int(m.Call(nil)[0].Int())
}
fmt.Println("Unknown method:", n)
return 0
}
func main() {
var e example
fmt.Println(e.CallMethod("Foo"))
fmt.Println(e.CallMethod("Bar"))
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
struct string_comparator {
using is_transparent = void;
bool operator()(const std::string& lhs, const std::string& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string& lhs, const std::string_view& rhs) const {
return lhs < rhs;
}
bool operator()(const std::string_view& lhs, const std::string& rhs) const {
return lhs < rhs;
}
};
using dictionary = std::set<std::string, string_comparator>;
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
auto create_string(const std::string_view& s,
const std::vector<std::optional<size_t>>& v) {
auto idx = s.size();
std::vector<std::string_view> sv;
while (v[idx].has_value()) {
size_t prev = v[idx].value();
sv.push_back(s.substr(prev, idx - prev));
idx = prev;
}
std::reverse(sv.begin(), sv.end());
return join(sv.begin(), sv.end(), ' ');
}
std::optional<std::string> word_break(const std::string_view& str,
const dictionary& dict) {
auto size = str.size() + 1;
std::vector<std::optional<size_t>> possible(size);
auto check_word = [&dict, &str](size_t i, size_t j)
-> std::optional<size_t> {
if (dict.find(str.substr(i, j - i)) != dict.end())
return i;
return std::nullopt;
};
for (size_t i = 1; i < size; ++i) {
if (!possible[i].has_value())
possible[i] = check_word(0, i);
if (possible[i].has_value()) {
for (size_t j = i + 1; j < size; ++j) {
if (!possible[j].has_value())
possible[j] = check_word(i, j);
}
if (possible[str.size()].has_value())
return create_string(str, possible);
}
}
return std::nullopt;
}
int main(int argc, char** argv) {
dictionary dict;
dict.insert("a");
dict.insert("bc");
dict.insert("abc");
dict.insert("cd");
dict.insert("b");
auto result = word_break("abcd", dict);
if (result.has_value())
std::cout << result.value() << '\n';
return 0;
}
| package main
import (
"fmt"
"strings"
)
type dict map[string]bool
func newDict(words ...string) dict {
d := dict{}
for _, w := range words {
d[w] = true
}
return d
}
func (d dict) wordBreak(s string) (broken []string, ok bool) {
if s == "" {
return nil, true
}
type prefix struct {
length int
broken []string
}
bp := []prefix{{0, nil}}
for end := 1; end <= len(s); end++ {
for i := len(bp) - 1; i >= 0; i-- {
w := s[bp[i].length:end]
if d[w] {
b := append(bp[i].broken, w)
if end == len(s) {
return b, true
}
bp = append(bp, prefix{end, b})
break
}
}
}
return nil, false
}
func main() {
d := newDict("a", "bc", "abc", "cd", "b")
for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} {
if b, ok := d.wordBreak(s); ok {
fmt.Printf("%s: %s\n", s, strings.Join(b, " "))
} else {
fmt.Println("can't break")
}
}
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
var primes = rcu.Primes(1e8 - 1)
type res struct {
bc interface{}
next int
}
func getBrilliant(digits, limit int, countOnly bool) res {
var brilliant []int
count := 0
pow := 1
next := math.MaxInt
for k := 1; k <= digits; k++ {
var s []int
for _, p := range primes {
if p >= pow*10 {
break
}
if p > pow {
s = append(s, p)
}
}
for i := 0; i < len(s); i++ {
for j := i; j < len(s); j++ {
prod := s[i] * s[j]
if prod < limit {
if countOnly {
count++
} else {
brilliant = append(brilliant, prod)
}
} else {
if next > prod {
next = prod
}
break
}
}
}
pow *= 10
}
if countOnly {
return res{count, next}
}
return res{brilliant, next}
}
func main() {
fmt.Println("First 100 brilliant numbers:")
brilliant := getBrilliant(2, 10000, false).bc.([]int)
sort.Ints(brilliant)
brilliant = brilliant[0:100]
for i := 0; i < len(brilliant); i++ {
fmt.Printf("%4d ", brilliant[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
for k := 1; k <= 13; k++ {
limit := int(math.Pow(10, float64(k)))
r := getBrilliant(k, limit, true)
total := r.bc.(int)
next := r.next
climit := rcu.Commatize(limit)
ctotal := rcu.Commatize(total + 1)
cnext := rcu.Commatize(next)
fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
}
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
#include <vector>
#include <primesieve.hpp>
auto get_primes_by_digits(uint64_t limit) {
primesieve::iterator pi;
std::vector<std::vector<uint64_t>> primes_by_digits;
std::vector<uint64_t> primes;
for (uint64_t p = 10; p <= limit;) {
uint64_t prime = pi.next_prime();
if (prime > p) {
primes_by_digits.push_back(std::move(primes));
p *= 10;
}
primes.push_back(prime);
}
return primes_by_digits;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
auto primes_by_digits = get_primes_by_digits(1000000000);
std::cout << "First 100 brilliant numbers:\n";
std::vector<uint64_t> brilliant_numbers;
for (const auto& primes : primes_by_digits) {
for (auto i = primes.begin(); i != primes.end(); ++i)
for (auto j = i; j != primes.end(); ++j)
brilliant_numbers.push_back(*i * *j);
if (brilliant_numbers.size() >= 100)
break;
}
std::sort(brilliant_numbers.begin(), brilliant_numbers.end());
for (size_t i = 0; i < 100; ++i) {
std::cout << std::setw(5) << brilliant_numbers[i]
<< ((i + 1) % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
uint64_t power = 10;
size_t count = 0;
for (size_t p = 1; p < 2 * primes_by_digits.size(); ++p) {
const auto& primes = primes_by_digits[p / 2];
size_t position = count + 1;
uint64_t min_product = 0;
for (auto i = primes.begin(); i != primes.end(); ++i) {
uint64_t p1 = *i;
auto j = std::lower_bound(i, primes.end(), (power + p1 - 1) / p1);
if (j != primes.end()) {
uint64_t p2 = *j;
uint64_t product = p1 * p2;
if (min_product == 0 || product < min_product)
min_product = product;
position += std::distance(i, j);
if (p1 >= p2)
break;
}
}
std::cout << "First brilliant number >= 10^" << p << " is "
<< min_product << " at position " << position << '\n';
power *= 10;
if (p % 2 == 1) {
size_t size = primes.size();
count += size * (size + 1) / 2;
}
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
var primes = rcu.Primes(1e8 - 1)
type res struct {
bc interface{}
next int
}
func getBrilliant(digits, limit int, countOnly bool) res {
var brilliant []int
count := 0
pow := 1
next := math.MaxInt
for k := 1; k <= digits; k++ {
var s []int
for _, p := range primes {
if p >= pow*10 {
break
}
if p > pow {
s = append(s, p)
}
}
for i := 0; i < len(s); i++ {
for j := i; j < len(s); j++ {
prod := s[i] * s[j]
if prod < limit {
if countOnly {
count++
} else {
brilliant = append(brilliant, prod)
}
} else {
if next > prod {
next = prod
}
break
}
}
}
pow *= 10
}
if countOnly {
return res{count, next}
}
return res{brilliant, next}
}
func main() {
fmt.Println("First 100 brilliant numbers:")
brilliant := getBrilliant(2, 10000, false).bc.([]int)
sort.Ints(brilliant)
brilliant = brilliant[0:100]
for i := 0; i < len(brilliant); i++ {
fmt.Printf("%4d ", brilliant[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
for k := 1; k <= 13; k++ {
limit := int(math.Pow(10, float64(k)))
r := getBrilliant(k, limit, true)
total := r.bc.(int)
next := r.next
climit := rcu.Commatize(limit)
ctotal := rcu.Commatize(total + 1)
cnext := rcu.Commatize(next)
fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
}
}
|
Please provide an equivalent version of this C++ code in Go. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() != s2.size())
return false;
bool result = false;
for (size_t i = 0, n = s1.size(); i != n; ++i) {
if (s1[i] != s2[i]) {
if (result)
return false;
result = true;
}
}
return result;
}
template <typename iterator_type, typename separator_type>
std::string join(iterator_type begin, iterator_type end,
separator_type separator) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += separator;
result += *begin;
}
}
return result;
}
bool word_ladder(const word_map& words, const std::string& from,
const std::string& to) {
auto w = words.find(from.size());
if (w != words.end()) {
auto poss = w->second;
std::vector<std::vector<std::string>> queue{{from}};
while (!queue.empty()) {
auto curr = queue.front();
queue.erase(queue.begin());
for (auto i = poss.begin(); i != poss.end();) {
if (!one_away(*i, curr.back())) {
++i;
continue;
}
if (to == *i) {
curr.push_back(to);
std::cout << join(curr.begin(), curr.end(), " -> ") << '\n';
return true;
}
std::vector<std::string> temp(curr);
temp.push_back(*i);
queue.push_back(std::move(temp));
i = poss.erase(i);
}
}
}
std::cout << from << " into " << to << " cannot be done.\n";
return false;
}
int main() {
word_map words;
std::ifstream in("unixdict.txt");
if (!in) {
std::cerr << "Cannot open file unixdict.txt.\n";
return EXIT_FAILURE;
}
std::string word;
while (getline(in, word))
words[word.size()].push_back(word);
word_ladder(words, "boy", "man");
word_ladder(words, "girl", "lady");
word_ladder(words, "john", "jane");
word_ladder(words, "child", "adult");
word_ladder(words, "cat", "dog");
word_ladder(words, "lead", "gold");
word_ladder(words, "white", "black");
word_ladder(words, "bubble", "tickle");
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func contains(a []string, s string) bool {
for _, e := range a {
if e == s {
return true
}
}
return false
}
func oneAway(a, b string) bool {
sum := 0
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
sum++
}
}
return sum == 1
}
func wordLadder(words []string, a, b string) {
l := len(a)
var poss []string
for _, word := range words {
if len(word) == l {
poss = append(poss, word)
}
}
todo := [][]string{{a}}
for len(todo) > 0 {
curr := todo[0]
todo = todo[1:]
var next []string
for _, word := range poss {
if oneAway(word, curr[len(curr)-1]) {
next = append(next, word)
}
}
if contains(next, b) {
curr = append(curr, b)
fmt.Println(strings.Join(curr, " -> "))
return
}
for i := len(poss) - 1; i >= 0; i-- {
if contains(next, poss[i]) {
copy(poss[i:], poss[i+1:])
poss[len(poss)-1] = ""
poss = poss[:len(poss)-1]
}
}
for _, s := range next {
temp := make([]string, len(curr))
copy(temp, curr)
temp = append(temp, s)
todo = append(todo, temp)
}
}
fmt.Println(a, "into", b, "cannot be done.")
}
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
pairs := [][]string{
{"boy", "man"},
{"girl", "lady"},
{"john", "jane"},
{"child", "adult"},
}
for _, pair := range pairs {
wordLadder(words, pair[0], pair[1])
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <primesieve.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
class composite_iterator {
public:
composite_iterator();
uint64_t next_composite();
private:
uint64_t composite;
uint64_t prime;
primesieve::iterator pi;
};
composite_iterator::composite_iterator() {
composite = prime = pi.next_prime();
for (; composite == prime; ++composite)
prime = pi.next_prime();
}
uint64_t composite_iterator::next_composite() {
uint64_t result = composite;
while (++composite == prime)
prime = pi.next_prime();
return result;
}
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
composite_iterator ci;
primesieve::iterator pi;
uint64_t prime_sum = pi.next_prime();
uint64_t composite_sum = ci.next_composite();
uint64_t prime_index = 1, composite_index = 1;
std::cout << "Sum | Prime Index | Composite Index\n";
std::cout << "------------------------------------------------------\n";
for (int count = 0; count < 11;) {
if (prime_sum == composite_sum) {
std::cout << std::right << std::setw(21) << prime_sum << " | "
<< std::setw(12) << prime_index << " | " << std::setw(15)
<< composite_index << '\n';
composite_sum += ci.next_composite();
prime_sum += pi.next_prime();
++prime_index;
++composite_index;
++count;
} else if (prime_sum < composite_sum) {
prime_sum += pi.next_prime();
++prime_index;
} else {
composite_sum += ci.next_composite();
++composite_index;
}
}
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"
"log"
"rcu"
"sort"
)
func ord(n int) string {
if n < 0 {
log.Fatal("Argument must be a non-negative integer.")
}
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%sth", rcu.Commatize(n))
}
m %= 10
suffix := "th"
if m == 1 {
suffix = "st"
} else if m == 2 {
suffix = "nd"
} else if m == 3 {
suffix = "rd"
}
return fmt.Sprintf("%s%s", rcu.Commatize(n), suffix)
}
func main() {
limit := int(4 * 1e8)
c := rcu.PrimeSieve(limit-1, true)
var compSums []int
var primeSums []int
csum := 0
psum := 0
for i := 2; i < limit; i++ {
if c[i] {
csum += i
compSums = append(compSums, csum)
} else {
psum += i
primeSums = append(primeSums, psum)
}
}
for i := 0; i < len(primeSums); i++ {
ix := sort.SearchInts(compSums, primeSums[i])
if ix < len(compSums) && compSums[ix] == primeSums[i] {
cps := rcu.Commatize(primeSums[i])
fmt.Printf("%21s - %12s prime sum, %12s composite sum\n", cps, ord(i+1), ord(ix+1))
}
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <stdio.h>
#include <stdlib.h>
void clear() {
for(int n = 0;n < 10; n++) {
printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n");
}
}
#define UP "00^00\r\n00|00\r\n00000\r\n"
#define DOWN "00000\r\n00|00\r\n00v00\r\n"
#define LEFT "00000\r\n<--00\r\n00000\r\n"
#define RIGHT "00000\r\n00-->\r\n00000\r\n"
#define HOME "00000\r\n00+00\r\n00000\r\n"
int main() {
clear();
system("stty raw");
printf(HOME);
printf("space to exit; wasd to move\r\n");
char c = 1;
while(c) {
c = getc(stdin);
clear();
switch (c)
{
case 'a':
printf(LEFT);
break;
case 'd':
printf(RIGHT);
break;
case 'w':
printf(UP);
break;
case 's':
printf(DOWN);
break;
case ' ':
c = 0;
break;
default:
printf(HOME);
};
printf("space to exit; wasd key to move\r\n");
}
system("stty cooked");
system("clear");
return 1;
}
| package main
import (
"fmt"
"github.com/nsf/termbox-go"
"github.com/simulatedsimian/joystick"
"log"
"os"
"strconv"
"time"
)
func printAt(x, y int, s string) {
for _, r := range s {
termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)
x++
}
}
func readJoystick(js joystick.Joystick, hidden bool) {
jinfo, err := js.Read()
check(err)
w, h := termbox.Size()
tbcd := termbox.ColorDefault
termbox.Clear(tbcd, tbcd)
printAt(1, h-1, "q - quit")
if hidden {
printAt(11, h-1, "s - show buttons:")
} else {
bs := ""
printAt(11, h-1, "h - hide buttons:")
for button := 0; button < js.ButtonCount(); button++ {
if jinfo.Buttons&(1<<uint32(button)) != 0 {
bs += fmt.Sprintf(" %X", button+1)
}
}
printAt(28, h-1, bs)
}
x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)
y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)
printAt(x, y, "+")
termbox.Flush()
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
jsid := 0
if len(os.Args) > 1 {
i, err := strconv.Atoi(os.Args[1])
check(err)
jsid = i
}
js, jserr := joystick.Open(jsid)
check(jserr)
err := termbox.Init()
check(err)
defer termbox.Close()
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
ticker := time.NewTicker(time.Millisecond * 40)
hidden := false
for doQuit := false; !doQuit; {
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Ch == 'q' {
doQuit = true
} else if ev.Ch == 'h' {
hidden = true
} else if ev.Ch == 's' {
hidden = false
}
}
if ev.Type == termbox.EventResize {
termbox.Flush()
}
case <-ticker.C:
readJoystick(js, hidden)
}
}
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
#include <locale>
#include <unordered_map>
#include <primesieve.hpp>
class prime_gaps {
public:
prime_gaps() { last_prime_ = iterator_.next_prime(); }
uint64_t find_gap_start(uint64_t gap);
private:
primesieve::iterator iterator_;
uint64_t last_prime_;
std::unordered_map<uint64_t, uint64_t> gap_starts_;
};
uint64_t prime_gaps::find_gap_start(uint64_t gap) {
auto i = gap_starts_.find(gap);
if (i != gap_starts_.end())
return i->second;
for (;;) {
uint64_t prev = last_prime_;
last_prime_ = iterator_.next_prime();
uint64_t diff = last_prime_ - prev;
gap_starts_.emplace(diff, prev);
if (gap == diff)
return prev;
}
}
int main() {
std::cout.imbue(std::locale(""));
const uint64_t limit = 100000000000;
prime_gaps pg;
for (uint64_t pm = 10, gap1 = 2;;) {
uint64_t start1 = pg.find_gap_start(gap1);
uint64_t gap2 = gap1 + 2;
uint64_t start2 = pg.find_gap_start(gap2);
uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
std::cout << "Earliest difference > " << pm
<< " between adjacent prime gap starting primes:\n"
<< "Gap " << gap1 << " starts at " << start1 << ", gap "
<< gap2 << " starts at " << start2 << ", difference is "
<< diff << ".\n\n";
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
| package main
import (
"fmt"
"rcu"
)
func main() {
limit := int(1e9)
gapStarts := make(map[int]int)
primes := rcu.Primes(limit * 5)
for i := 1; i < len(primes); i++ {
gap := primes[i] - primes[i-1]
if _, ok := gapStarts[gap]; !ok {
gapStarts[gap] = primes[i-1]
}
}
pm := 10
gap1 := 2
for {
for _, ok := gapStarts[gap1]; !ok; {
gap1 += 2
}
start1 := gapStarts[gap1]
gap2 := gap1 + 2
if _, ok := gapStarts[gap2]; !ok {
gap1 = gap2 + 2
continue
}
start2 := gapStarts[gap2]
diff := start2 - start1
if diff < 0 {
diff = -diff
}
if diff > pm {
cpm := rcu.Commatize(pm)
cst1 := rcu.Commatize(start1)
cst2 := rcu.Commatize(start2)
cd := rcu.Commatize(diff)
fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm)
fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd)
if pm == limit {
break
}
pm *= 10
} else {
gap1 = gap2
}
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
typedef std::vector<std::vector<int>> matrix;
matrix dList(int n, int start) {
start--;
std::vector<int> a(n);
std::iota(a.begin(), a.end(), 0);
a[start] = a[0];
a[0] = start;
std::sort(a.begin() + 1, a.end());
auto first = a[1];
matrix r;
std::function<void(int)> recurse;
recurse = [&](int last) {
if (last == first) {
for (size_t j = 1; j < a.size(); j++) {
auto v = a[j];
if (j == v) {
return;
}
}
std::vector<int> b;
std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });
r.push_back(b);
return;
}
for (int i = last; i >= 1; i--) {
std::swap(a[i], a[last]);
recurse(last - 1);
std::swap(a[i], a[last]);
}
};
recurse(n - 1);
return r;
}
void printSquare(const matrix &latin, int n) {
for (auto &row : latin) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
std::cout << '\n';
}
unsigned long reducedLatinSquares(int n, bool echo) {
if (n <= 0) {
if (echo) {
std::cout << "[]\n";
}
return 0;
} else if (n == 1) {
if (echo) {
std::cout << "[1]\n";
}
return 1;
}
matrix rlatin;
for (int i = 0; i < n; i++) {
rlatin.push_back({});
for (int j = 0; j < n; j++) {
rlatin[i].push_back(j);
}
}
for (int j = 0; j < n; j++) {
rlatin[0][j] = j + 1;
}
unsigned long count = 0;
std::function<void(int)> recurse;
recurse = [&](int i) {
auto rows = dList(n, i);
for (size_t r = 0; r < rows.size(); r++) {
rlatin[i - 1] = rows[r];
for (int k = 0; k < i - 1; k++) {
for (int j = 1; j < n; j++) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.size() - 1) {
goto outer;
}
if (i > 2) {
return;
}
}
}
}
if (i < n) {
recurse(i + 1);
} else {
count++;
if (echo) {
printSquare(rlatin, n);
}
}
outer: {}
}
};
recurse(2);
return count;
}
unsigned long factorial(unsigned long n) {
if (n <= 0) return 1;
unsigned long prod = 1;
for (unsigned long i = 2; i <= n; i++) {
prod *= i;
}
return prod;
}
int main() {
std::cout << "The four reduced lating squares of order 4 are:\n";
reducedLatinSquares(4, true);
std::cout << "The size of the set of reduced latin squares for the following orders\n";
std::cout << "and hence the total number of latin squares of these orders are:\n\n";
for (int n = 1; n < 7; n++) {
auto size = reducedLatinSquares(n, false);
auto f = factorial(n - 1);
f *= f * n * size;
std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n';
}
return 0;
}
| package main
import (
"fmt"
"sort"
)
type matrix [][]int
func dList(n, start int) (r matrix) {
start--
a := make([]int, n)
for i := range a {
a[i] = i
}
a[0], a[start] = start, a[0]
sort.Ints(a[1:])
first := a[1]
var recurse func(last int)
recurse = func(last int) {
if last == first {
for j, v := range a[1:] {
if j+1 == v {
return
}
}
b := make([]int, n)
copy(b, a)
for i := range b {
b[i]++
}
r = append(r, b)
return
}
for i := last; i >= 1; i-- {
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
}
}
recurse(n - 1)
return
}
func reducedLatinSquare(n int, echo bool) uint64 {
if n <= 0 {
if echo {
fmt.Println("[]\n")
}
return 0
} else if n == 1 {
if echo {
fmt.Println("[1]\n")
}
return 1
}
rlatin := make(matrix, n)
for i := 0; i < n; i++ {
rlatin[i] = make([]int, n)
}
for j := 0; j < n; j++ {
rlatin[0][j] = j + 1
}
count := uint64(0)
var recurse func(i int)
recurse = func(i int) {
rows := dList(n, i)
outer:
for r := 0; r < len(rows); r++ {
copy(rlatin[i-1], rows[r])
for k := 0; k < i-1; k++ {
for j := 1; j < n; j++ {
if rlatin[k][j] == rlatin[i-1][j] {
if r < len(rows)-1 {
continue outer
} else if i > 2 {
return
}
}
}
}
if i < n {
recurse(i + 1)
} else {
count++
if echo {
printSquare(rlatin, n)
}
}
}
return
}
recurse(2)
return count
}
func printSquare(latin matrix, n int) {
for i := 0; i < n; i++ {
fmt.Println(latin[i])
}
fmt.Println()
}
func factorial(n uint64) uint64 {
if n == 0 {
return 1
}
prod := uint64(1)
for i := uint64(2); i <= n; i++ {
prod *= i
}
return prod
}
func main() {
fmt.Println("The four reduced latin squares of order 4 are:\n")
reducedLatinSquare(4, true)
fmt.Println("The size of the set of reduced latin squares for the following orders")
fmt.Println("and hence the total number of latin squares of these orders are:\n")
for n := uint64(1); n <= 6; n++ {
size := reducedLatinSquare(int(n), false)
f := factorial(n - 1)
f *= f * n * size
fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f)
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <array>
#include <iomanip>
#include <iostream>
#include <utility>
#include <primesieve.hpp>
class ormiston_pair_generator {
public:
ormiston_pair_generator() { prime_ = pi_.next_prime(); }
std::pair<uint64_t, uint64_t> next_pair() {
for (;;) {
uint64_t prime = prime_;
auto digits = digits_;
prime_ = pi_.next_prime();
digits_ = get_digits(prime_);
if (digits_ == digits)
return std::make_pair(prime, prime_);
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
uint64_t prime_;
std::array<int, 10> digits_;
};
int main() {
ormiston_pair_generator generator;
int count = 0;
std::cout << "First 30 Ormiston pairs:\n";
for (; count < 30; ++count) {
auto [p1, p2] = generator.next_pair();
std::cout << '(' << std::setw(5) << p1 << ", " << std::setw(5) << p2
<< ')' << ((count + 1) % 3 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {
auto [p1, p2] = generator.next_pair();
if (p1 > limit) {
std::cout << "Number of Ormiston pairs < " << limit << ": " << count
<< '\n';
limit *= 10;
}
}
}
| package main
import (
"fmt"
"rcu"
)
func main() {
const limit = 1e9
primes := rcu.Primes(limit)
var orm30 [][2]int
j := int(1e5)
count := 0
var counts []int
for i := 0; i < len(primes)-1; i++ {
p1 := primes[i]
p2 := primes[i+1]
if (p2-p1)%18 != 0 {
continue
}
key1 := 1
for _, dig := range rcu.Digits(p1, 10) {
key1 *= primes[dig]
}
key2 := 1
for _, dig := range rcu.Digits(p2, 10) {
key2 *= primes[dig]
}
if key1 == key2 {
if count < 30 {
orm30 = append(orm30, [2]int{p1, p2})
}
if p1 >= j {
counts = append(counts, count)
j *= 10
}
count++
}
}
counts = append(counts, count)
fmt.Println("First 30 Ormiston pairs:")
for i := 0; i < 30; i++ {
fmt.Printf("%5v ", orm30[i])
if (i+1)%3 == 0 {
fmt.Println()
}
}
fmt.Println()
j = int(1e5)
for i := 0; i < len(counts); i++ {
fmt.Printf("%s Ormiston pairs before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j))
j *= 10
}
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iostream>
#include <locale>
#include <map>
#include <vector>
std::string trim(const std::string &str) {
auto s = str;
auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(it1.base(), s.end());
auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
s.erase(s.begin(), it2);
return s;
}
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
const std::map<std::string, int> LEFT_DIGITS = {
{" ## #", 0},
{" ## #", 1},
{" # ##", 2},
{" #### #", 3},
{" # ##", 4},
{" ## #", 5},
{" # ####", 6},
{" ### ##", 7},
{" ## ###", 8},
{" # ##", 9}
};
const std::map<std::string, int> RIGHT_DIGITS = {
{"### # ", 0},
{"## ## ", 1},
{"## ## ", 2},
{"# # ", 3},
{"# ### ", 4},
{"# ### ", 5},
{"# # ", 6},
{"# # ", 7},
{"# # ", 8},
{"### # ", 9}
};
const std::string END_SENTINEL = "# #";
const std::string MID_SENTINEL = " # # ";
void decodeUPC(const std::string &input) {
auto decode = [](const std::string &candidate) {
using OT = std::vector<int>;
OT output;
size_t pos = 0;
auto part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = LEFT_DIGITS.find(part);
if (e != LEFT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, MID_SENTINEL.length());
if (part == MID_SENTINEL) {
pos += MID_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
for (size_t i = 0; i < 6; i++) {
part = candidate.substr(pos, 7);
pos += 7;
auto e = RIGHT_DIGITS.find(part);
if (e != RIGHT_DIGITS.end()) {
output.push_back(e->second);
} else {
return std::make_pair(false, output);
}
}
part = candidate.substr(pos, END_SENTINEL.length());
if (part == END_SENTINEL) {
pos += END_SENTINEL.length();
} else {
return std::make_pair(false, OT{});
}
int sum = 0;
for (size_t i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output[i];
} else {
sum += output[i];
}
}
return std::make_pair(sum % 10 == 0, output);
};
auto candidate = trim(input);
auto out = decode(candidate);
if (out.first) {
std::cout << out.second << '\n';
} else {
std::reverse(candidate.begin(), candidate.end());
out = decode(candidate);
if (out.first) {
std::cout << out.second << " Upside down\n";
} else if (out.second.size()) {
std::cout << "Invalid checksum\n";
} else {
std::cout << "Invalid digit(s)\n";
}
}
}
int main() {
std::vector<std::string> barcodes = {
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
};
for (auto &barcode : barcodes) {
decodeUPC(barcode);
}
return 0;
}
| package main
import (
"fmt"
"regexp"
)
var bits = []string{
"0 0 0 1 1 0 1 ",
"0 0 1 1 0 0 1 ",
"0 0 1 0 0 1 1 ",
"0 1 1 1 1 0 1 ",
"0 1 0 0 0 1 1 ",
"0 1 1 0 0 0 1 ",
"0 1 0 1 1 1 1 ",
"0 1 1 1 0 1 1 ",
"0 1 1 0 1 1 1 ",
"0 0 0 1 0 1 1 ",
}
var (
lhs = make(map[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
}
expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
rx := regexp.MustCompile(expr)
fmt.Println("UPC-A barcodes:")
for i, bc := range barcodes {
for j := 0; j <= 1; j++ {
if !rx.MatchString(bc) {
fmt.Printf("%2d: Invalid format\n", i+1)
break
}
codes := rx.FindStringSubmatch(bc)
digits := make([]int, 12)
var invalid, ok bool
for i := 1; i <= 6; i++ {
digits[i-1], ok = lhs[codes[i]]
if !ok {
invalid = true
}
digits[i+5], ok = rhs[codes[i+6]]
if !ok {
invalid = true
}
}
if invalid {
if j == 0 {
bc = reverse(bc)
continue
} else {
fmt.Printf("%2d: Invalid digit(s)\n", i+1)
break
}
}
sum := 0
for i, d := range digits {
sum += weights[i] * d
}
if sum%10 != 0 {
fmt.Printf("%2d: Checksum error\n", i+1)
break
} else {
ud := ""
if j == 1 {
ud = "(upside down)"
}
fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
break
}
}
}
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
| package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type playfairOption int
const (
noQ playfairOption = iota
iEqualsJ
)
type playfair struct {
keyword string
pfo playfairOption
table [5][5]byte
}
func (p *playfair) init() {
var used [26]bool
if p.pfo == noQ {
used[16] = true
} else {
used[9] = true
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
plainText = strings.ToUpper(plainText)
var cleanText strings.Builder
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
{
if( getCharPos( *ti++, a, b ) )
if( getCharPos( *ti, c, d ) )
{
if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
}
}
_txt = ntxt;
}
void display()
{
cout << "\n\n OUTPUT:\n=========" << endl;
string::iterator si = _txt.begin(); int cnt = 0;
while( si != _txt.end() )
{
cout << *si; si++; cout << *si << " "; si++;
if( ++cnt >= 26 ) cout << endl, cnt = 0;
}
cout << endl << endl;
}
char getChar( int a, int b )
{
return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
}
bool getCharPos( char l, int &a, int &b )
{
for( int y = 0; y < 5; y++ )
for( int x = 0; x < 5; x++ )
if( _m[y][x] == l )
{ a = x; b = y; return true; }
return false;
}
void getTextReady( string t, bool ij, bool e )
{
for( string::iterator si = t.begin(); si != t.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( *si == 'J' && ij ) *si = 'I';
else if( *si == 'Q' && !ij ) continue;
_txt += *si;
}
if( e )
{
string ntxt = ""; size_t len = _txt.length();
for( size_t x = 0; x < len; x += 2 )
{
ntxt += _txt[x];
if( x + 1 < len )
{
if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
ntxt += _txt[x + 1];
}
}
_txt = ntxt;
}
if( _txt.length() & 1 ) _txt += 'X';
}
void createGrid( string k, bool ij )
{
if( k.length() < 1 ) k = "KEYWORD";
k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
for( string::iterator si = k.begin(); si != k.end(); si++ )
{
*si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
if( nk.find( *si ) == -1 ) nk += *si;
}
copy( nk.begin(), nk.end(), &_m[0][0] );
}
string _txt; char _m[5][5];
};
int main( int argc, char* argv[] )
{
string key, i, txt; bool ij, e;
cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
cout << "Enter a en/decryption key: "; getline( cin, key );
cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}
| package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type playfairOption int
const (
noQ playfairOption = iota
iEqualsJ
)
type playfair struct {
keyword string
pfo playfairOption
table [5][5]byte
}
func (p *playfair) init() {
var used [26]bool
if p.pfo == noQ {
used[16] = true
} else {
used[9] = true
}
alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i, j, k := 0, 0, 0; k < len(alphabet); k++ {
c := alphabet[k]
if c < 'A' || c > 'Z' {
continue
}
d := int(c - 65)
if !used[d] {
p.table[i][j] = c
used[d] = true
j++
if j == 5 {
i++
if i == 5 {
break
}
j = 0
}
}
}
}
func (p *playfair) getCleanText(plainText string) string {
plainText = strings.ToUpper(plainText)
var cleanText strings.Builder
prevByte := byte('\000')
for i := 0; i < len(plainText); i++ {
nextByte := plainText[i]
if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {
continue
}
if nextByte == 'J' && p.pfo == iEqualsJ {
nextByte = 'I'
}
if nextByte != prevByte {
cleanText.WriteByte(nextByte)
} else {
cleanText.WriteByte('X')
cleanText.WriteByte(nextByte)
}
prevByte = nextByte
}
l := cleanText.Len()
if l%2 == 1 {
if cleanText.String()[l-1] != 'X' {
cleanText.WriteByte('X')
} else {
cleanText.WriteByte('Z')
}
}
return cleanText.String()
}
func (p *playfair) findByte(c byte) (int, int) {
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if p.table[i][j] == c {
return i, j
}
}
}
return -1, -1
}
func (p *playfair) encode(plainText string) string {
cleanText := p.getCleanText(plainText)
var cipherText strings.Builder
l := len(cleanText)
for i := 0; i < l; i += 2 {
row1, col1 := p.findByte(cleanText[i])
row2, col2 := p.findByte(cleanText[i+1])
switch {
case row1 == row2:
cipherText.WriteByte(p.table[row1][(col1+1)%5])
cipherText.WriteByte(p.table[row2][(col2+1)%5])
case col1 == col2:
cipherText.WriteByte(p.table[(row1+1)%5][col1])
cipherText.WriteByte(p.table[(row2+1)%5][col2])
default:
cipherText.WriteByte(p.table[row1][col2])
cipherText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
cipherText.WriteByte(' ')
}
}
return cipherText.String()
}
func (p *playfair) decode(cipherText string) string {
var decodedText strings.Builder
l := len(cipherText)
for i := 0; i < l; i += 3 {
row1, col1 := p.findByte(cipherText[i])
row2, col2 := p.findByte(cipherText[i+1])
switch {
case row1 == row2:
temp := 4
if col1 > 0 {
temp = col1 - 1
}
decodedText.WriteByte(p.table[row1][temp])
temp = 4
if col2 > 0 {
temp = col2 - 1
}
decodedText.WriteByte(p.table[row2][temp])
case col1 == col2:
temp := 4
if row1 > 0 {
temp = row1 - 1
}
decodedText.WriteByte(p.table[temp][col1])
temp = 4
if row2 > 0 {
temp = row2 - 1
}
decodedText.WriteByte(p.table[temp][col2])
default:
decodedText.WriteByte(p.table[row1][col2])
decodedText.WriteByte(p.table[row2][col1])
}
if i < l-1 {
decodedText.WriteByte(' ')
}
}
return decodedText.String()
}
func (p *playfair) printTable() {
fmt.Println("The table to be used is :\n")
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
fmt.Printf("%c ", p.table[i][j])
}
fmt.Println()
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Enter Playfair keyword : ")
scanner.Scan()
keyword := scanner.Text()
var ignoreQ string
for ignoreQ != "y" && ignoreQ != "n" {
fmt.Print("Ignore Q when building table y/n : ")
scanner.Scan()
ignoreQ = strings.ToLower(scanner.Text())
}
pfo := noQ
if ignoreQ == "n" {
pfo = iEqualsJ
}
var table [5][5]byte
pf := &playfair{keyword, pfo, table}
pf.init()
pf.printTable()
fmt.Print("\nEnter plain text : ")
scanner.Scan()
plainText := scanner.Text()
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
return
}
encodedText := pf.encode(plainText)
fmt.Println("\nEncoded text is :", encodedText)
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/gmp.hpp>
using integer = boost::multiprecision::mpz_int;
using rational = boost::rational<integer>;
class harmonic_generator {
public:
rational next() {
rational result = term_;
term_ += rational(1, ++n_);
return result;
}
void reset() {
n_ = 1;
term_ = 1;
}
private:
integer n_ = 1;
rational term_ = 1;
};
int main() {
std::cout << "First 20 harmonic numbers:\n";
harmonic_generator hgen;
for (int i = 1; i <= 20; ++i)
std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';
rational h;
for (int i = 1; i <= 80; ++i)
h = hgen.next();
std::cout << "\n100th harmonic number: " << h << "\n\n";
int n = 1;
hgen.reset();
for (int i = 1; n <= 10; ++i) {
if (hgen.next() > n)
std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
}
}
| package main
import (
"fmt"
"math/big"
)
func harmonic(n int) *big.Rat {
sum := new(big.Rat)
for i := int64(1); i <= int64(n); i++ {
r := big.NewRat(1, i)
sum.Add(sum, r)
}
return sum
}
func main() {
fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
numbers := make([]int, 21)
for i := 1; i <= 20; i++ {
numbers[i-1] = i
}
numbers[20] = 100
for _, i := range numbers {
fmt.Printf("%3d : %s\n", i, harmonic(i))
}
fmt.Println("\nThe first harmonic number to exceed the following integers is:")
const limit = 10
for i, n, h := 1, 1, 0.0; i <= limit; n++ {
h += 1.0 / float64(n)
if h > float64(i) {
fmt.Printf("integer = %2d -> n = %6d -> harmonic number = %9.6f (to 6dp)\n", i, n, h)
i++
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
int main(int argc, char* argv[]);
void write_vals(int* const, const size_t, const size_t);
std::string mergeFiles(size_t);
struct Compare
{
bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 )
{
return p1.first >= p2.first;
}
};
using ipair = std::pair<int,int>;
using pairvector = std::vector<ipair>;
using MinHeap = std::priority_queue< ipair, pairvector, Compare >;
const size_t memsize = 32;
const size_t chunksize = memsize / sizeof(int);
const std::string tmp_prefix{"tmp_out_"};
const std::string tmp_suffix{".txt"};
const std::string merged_file{"merged.txt"};
void write_vals( int* const values, const size_t size, const size_t chunk )
{
std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);
std::ofstream ofs(output_file.c_str());
for (int i=0; i<size; i++)
ofs << values[i] << '\t';
ofs << '\n';
ofs.close();
}
std::string mergeFiles(size_t chunks, const std::string& merge_file )
{
std::ofstream ofs( merge_file.c_str() );
MinHeap minHeap;
std::ifstream* ifs_tempfiles = new std::ifstream[chunks];
for (size_t i = 1; i<=chunks; i++)
{
int topval = 0;
std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);
ifs_tempfiles[i-1].open( sorted_file.c_str() );
if (ifs_tempfiles[i-1].is_open())
{
ifs_tempfiles[i-1] >> topval;
ipair top(topval, (i-1));
minHeap.push( top );
}
}
while (minHeap.size() > 0)
{
int next_val = 0;
ipair min_pair = minHeap.top();
minHeap.pop();
ofs << min_pair.first << ' ';
std::flush(ofs);
if ( ifs_tempfiles[min_pair.second] >> next_val)
{
ipair np( next_val, min_pair.second );
minHeap.push( np );
}
}
for (int i = 1; i <= chunks; i++)
{
ifs_tempfiles[i-1].close();
}
ofs << '\n';
ofs.close();
delete[] ifs_tempfiles;
return merged_file;
}
int main(int argc, char* argv[] )
{
if (argc < 2)
{
std::cerr << "usage: ExternalSort <filename> \n";
return 1;
}
std::ifstream ifs( argv[1] );
if ( ifs.fail() )
{
std::cerr << "error opening " << argv[1] << "\n";
return 2;
}
int* inputValues = new int[chunksize];
int chunk = 1;
int val = 0;
int count = 0;
bool done = false;
std::cout << "internal buffer is " << memsize << " bytes" << "\n";
while (ifs >> val)
{
done = false;
inputValues[count] = val;
count++;
if (count == chunksize)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
chunk ++;
count = 0;
done = true;
}
}
if (! done)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
}
else
{
chunk --;
}
ifs.close();
delete[] inputValues;
if ( chunk == 0 )
std::cout << "no data found\n";
else
std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n";
return EXIT_SUCCESS;
}
| package main
import (
"fmt"
"io"
"log"
"math"
"math/rand"
"os"
"time"
)
type MinHeapNode struct{ element, index int }
type MinHeap struct{ nodes []MinHeapNode }
func left(i int) int {
return (2*i + 1)
}
func right(i int) int {
return (2*i + 2)
}
func newMinHeap(nodes []MinHeapNode) *MinHeap {
mh := new(MinHeap)
mh.nodes = nodes
for i := (len(nodes) - 1) / 2; i >= 0; i-- {
mh.minHeapify(i)
}
return mh
}
func (mh *MinHeap) getMin() MinHeapNode {
return mh.nodes[0]
}
func (mh *MinHeap) replaceMin(x MinHeapNode) {
mh.nodes[0] = x
mh.minHeapify(0)
}
func (mh *MinHeap) minHeapify(i int) {
l, r := left(i), right(i)
smallest := i
heapSize := len(mh.nodes)
if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {
smallest = l
}
if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {
smallest = r
}
if smallest != i {
mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]
mh.minHeapify(smallest)
}
}
func merge(arr []int, l, m, r int) {
n1, n2 := m-l+1, r-m
tl := make([]int, n1)
tr := make([]int, n2)
copy(tl, arr[l:])
copy(tr, arr[m+1:])
i, j, k := 0, 0, l
for i < n1 && j < n2 {
if tl[i] <= tr[j] {
arr[k] = tl[i]
k++
i++
} else {
arr[k] = tr[j]
k++
j++
}
}
for i < n1 {
arr[k] = tl[i]
k++
i++
}
for j < n2 {
arr[k] = tr[j]
k++
j++
}
}
func mergeSort(arr []int, l, r int) {
if l < r {
m := l + (r-l)/2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
}
}
func mergeFiles(outputFile string, n, k int) {
in := make([]*os.File, k)
var err error
for i := 0; i < k; i++ {
fileName := fmt.Sprintf("es%d", i)
in[i], err = os.Open(fileName)
check(err)
}
out, err := os.Create(outputFile)
check(err)
nodes := make([]MinHeapNode, k)
i := 0
for ; i < k; i++ {
_, err = fmt.Fscanf(in[i], "%d", &nodes[i].element)
if err == io.EOF {
break
}
check(err)
nodes[i].index = i
}
hp := newMinHeap(nodes[:i])
count := 0
for count != i {
root := hp.getMin()
fmt.Fprintf(out, "%d ", root.element)
_, err = fmt.Fscanf(in[root.index], "%d", &root.element)
if err == io.EOF {
root.element = math.MaxInt32
count++
} else {
check(err)
}
hp.replaceMin(root)
}
for j := 0; j < k; j++ {
in[j].Close()
}
out.Close()
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func createInitialRuns(inputFile string, runSize, numWays int) {
in, err := os.Open(inputFile)
out := make([]*os.File, numWays)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
out[i], err = os.Create(fileName)
check(err)
}
arr := make([]int, runSize)
moreInput := true
nextOutputFile := 0
var i int
for moreInput {
for i = 0; i < runSize; i++ {
_, err := fmt.Fscanf(in, "%d", &arr[i])
if err == io.EOF {
moreInput = false
break
}
check(err)
}
mergeSort(arr, 0, i-1)
for j := 0; j < i; j++ {
fmt.Fprintf(out[nextOutputFile], "%d ", arr[j])
}
nextOutputFile++
}
for j := 0; j < numWays; j++ {
out[j].Close()
}
in.Close()
}
func externalSort(inputFile, outputFile string, numWays, runSize int) {
createInitialRuns(inputFile, runSize, numWays)
mergeFiles(outputFile, runSize, numWays)
}
func main() {
numWays := 4
runSize := 10
inputFile := "input.txt"
outputFile := "output.txt"
in, err := os.Create(inputFile)
check(err)
rand.Seed(time.Now().UnixNano())
for i := 0; i < numWays*runSize; i++ {
fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32))
}
in.Close()
externalSort(inputFile, outputFile, numWays, runSize)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
err = os.Remove(fileName)
check(err)
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. |
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#include <algorithm>
#include <cstdio>
int main(int argc, char* argv[]);
void write_vals(int* const, const size_t, const size_t);
std::string mergeFiles(size_t);
struct Compare
{
bool operator() ( std::pair<int, int>& p1, std::pair<int, int>& p2 )
{
return p1.first >= p2.first;
}
};
using ipair = std::pair<int,int>;
using pairvector = std::vector<ipair>;
using MinHeap = std::priority_queue< ipair, pairvector, Compare >;
const size_t memsize = 32;
const size_t chunksize = memsize / sizeof(int);
const std::string tmp_prefix{"tmp_out_"};
const std::string tmp_suffix{".txt"};
const std::string merged_file{"merged.txt"};
void write_vals( int* const values, const size_t size, const size_t chunk )
{
std::string output_file = (tmp_prefix + std::to_string(chunk) + tmp_suffix);
std::ofstream ofs(output_file.c_str());
for (int i=0; i<size; i++)
ofs << values[i] << '\t';
ofs << '\n';
ofs.close();
}
std::string mergeFiles(size_t chunks, const std::string& merge_file )
{
std::ofstream ofs( merge_file.c_str() );
MinHeap minHeap;
std::ifstream* ifs_tempfiles = new std::ifstream[chunks];
for (size_t i = 1; i<=chunks; i++)
{
int topval = 0;
std::string sorted_file = (tmp_prefix + std::to_string(i) + tmp_suffix);
ifs_tempfiles[i-1].open( sorted_file.c_str() );
if (ifs_tempfiles[i-1].is_open())
{
ifs_tempfiles[i-1] >> topval;
ipair top(topval, (i-1));
minHeap.push( top );
}
}
while (minHeap.size() > 0)
{
int next_val = 0;
ipair min_pair = minHeap.top();
minHeap.pop();
ofs << min_pair.first << ' ';
std::flush(ofs);
if ( ifs_tempfiles[min_pair.second] >> next_val)
{
ipair np( next_val, min_pair.second );
minHeap.push( np );
}
}
for (int i = 1; i <= chunks; i++)
{
ifs_tempfiles[i-1].close();
}
ofs << '\n';
ofs.close();
delete[] ifs_tempfiles;
return merged_file;
}
int main(int argc, char* argv[] )
{
if (argc < 2)
{
std::cerr << "usage: ExternalSort <filename> \n";
return 1;
}
std::ifstream ifs( argv[1] );
if ( ifs.fail() )
{
std::cerr << "error opening " << argv[1] << "\n";
return 2;
}
int* inputValues = new int[chunksize];
int chunk = 1;
int val = 0;
int count = 0;
bool done = false;
std::cout << "internal buffer is " << memsize << " bytes" << "\n";
while (ifs >> val)
{
done = false;
inputValues[count] = val;
count++;
if (count == chunksize)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
chunk ++;
count = 0;
done = true;
}
}
if (! done)
{
std::sort(inputValues, inputValues + count);
write_vals(inputValues, count, chunk);
}
else
{
chunk --;
}
ifs.close();
delete[] inputValues;
if ( chunk == 0 )
std::cout << "no data found\n";
else
std::cout << "Sorted output is in file: " << mergeFiles(chunk, merged_file ) << "\n";
return EXIT_SUCCESS;
}
| package main
import (
"fmt"
"io"
"log"
"math"
"math/rand"
"os"
"time"
)
type MinHeapNode struct{ element, index int }
type MinHeap struct{ nodes []MinHeapNode }
func left(i int) int {
return (2*i + 1)
}
func right(i int) int {
return (2*i + 2)
}
func newMinHeap(nodes []MinHeapNode) *MinHeap {
mh := new(MinHeap)
mh.nodes = nodes
for i := (len(nodes) - 1) / 2; i >= 0; i-- {
mh.minHeapify(i)
}
return mh
}
func (mh *MinHeap) getMin() MinHeapNode {
return mh.nodes[0]
}
func (mh *MinHeap) replaceMin(x MinHeapNode) {
mh.nodes[0] = x
mh.minHeapify(0)
}
func (mh *MinHeap) minHeapify(i int) {
l, r := left(i), right(i)
smallest := i
heapSize := len(mh.nodes)
if l < heapSize && mh.nodes[l].element < mh.nodes[i].element {
smallest = l
}
if r < heapSize && mh.nodes[r].element < mh.nodes[smallest].element {
smallest = r
}
if smallest != i {
mh.nodes[i], mh.nodes[smallest] = mh.nodes[smallest], mh.nodes[i]
mh.minHeapify(smallest)
}
}
func merge(arr []int, l, m, r int) {
n1, n2 := m-l+1, r-m
tl := make([]int, n1)
tr := make([]int, n2)
copy(tl, arr[l:])
copy(tr, arr[m+1:])
i, j, k := 0, 0, l
for i < n1 && j < n2 {
if tl[i] <= tr[j] {
arr[k] = tl[i]
k++
i++
} else {
arr[k] = tr[j]
k++
j++
}
}
for i < n1 {
arr[k] = tl[i]
k++
i++
}
for j < n2 {
arr[k] = tr[j]
k++
j++
}
}
func mergeSort(arr []int, l, r int) {
if l < r {
m := l + (r-l)/2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
}
}
func mergeFiles(outputFile string, n, k int) {
in := make([]*os.File, k)
var err error
for i := 0; i < k; i++ {
fileName := fmt.Sprintf("es%d", i)
in[i], err = os.Open(fileName)
check(err)
}
out, err := os.Create(outputFile)
check(err)
nodes := make([]MinHeapNode, k)
i := 0
for ; i < k; i++ {
_, err = fmt.Fscanf(in[i], "%d", &nodes[i].element)
if err == io.EOF {
break
}
check(err)
nodes[i].index = i
}
hp := newMinHeap(nodes[:i])
count := 0
for count != i {
root := hp.getMin()
fmt.Fprintf(out, "%d ", root.element)
_, err = fmt.Fscanf(in[root.index], "%d", &root.element)
if err == io.EOF {
root.element = math.MaxInt32
count++
} else {
check(err)
}
hp.replaceMin(root)
}
for j := 0; j < k; j++ {
in[j].Close()
}
out.Close()
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func createInitialRuns(inputFile string, runSize, numWays int) {
in, err := os.Open(inputFile)
out := make([]*os.File, numWays)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
out[i], err = os.Create(fileName)
check(err)
}
arr := make([]int, runSize)
moreInput := true
nextOutputFile := 0
var i int
for moreInput {
for i = 0; i < runSize; i++ {
_, err := fmt.Fscanf(in, "%d", &arr[i])
if err == io.EOF {
moreInput = false
break
}
check(err)
}
mergeSort(arr, 0, i-1)
for j := 0; j < i; j++ {
fmt.Fprintf(out[nextOutputFile], "%d ", arr[j])
}
nextOutputFile++
}
for j := 0; j < numWays; j++ {
out[j].Close()
}
in.Close()
}
func externalSort(inputFile, outputFile string, numWays, runSize int) {
createInitialRuns(inputFile, runSize, numWays)
mergeFiles(outputFile, runSize, numWays)
}
func main() {
numWays := 4
runSize := 10
inputFile := "input.txt"
outputFile := "output.txt"
in, err := os.Create(inputFile)
check(err)
rand.Seed(time.Now().UnixNano())
for i := 0; i < numWays*runSize; i++ {
fmt.Fprintf(in, "%d ", rand.Intn(math.MaxInt32))
}
in.Close()
externalSort(inputFile, outputFile, numWays, runSize)
for i := 0; i < numWays; i++ {
fileName := fmt.Sprintf("es%d", i)
err = os.Remove(fileName)
check(err)
}
}
|
Change the following C++ code into Go without altering its purpose. |
class matrixNG {
private:
virtual void consumeTerm(){}
virtual void consumeTerm(int n){}
virtual const bool needTerm(){}
protected: int cfn = 0, thisTerm;
bool haveTerm = false;
friend class NG;
};
class NG_4 : public matrixNG {
private: int a1, a, b1, b, t;
const bool needTerm() {
if (b1==0 and b==0) return false;
if (b1==0 or b==0) return true; else thisTerm = a/b;
if (thisTerm==(int)(a1/b1)){
t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;
haveTerm=true; return false;
}
return true;
}
void consumeTerm(){a=a1; b=b1;}
void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}
public:
NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}
};
class NG : public ContinuedFraction {
private:
matrixNG* ng;
ContinuedFraction* n[2];
public:
NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}
NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}
const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}
const bool moreTerms(){
while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();
return ng->haveTerm;
}
};
| package cf
type NG4 struct {
A1, A int64
B1, B int64
}
func (ng NG4) needsIngest() bool {
if ng.isDone() {
panic("b₁==b==0")
}
return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}
func (ng NG4) isDone() bool {
return ng.B1 == 0 && ng.B == 0
}
func (ng *NG4) ingest(t int64) {
ng.A1, ng.A, ng.B1, ng.B =
ng.A+ng.A1*t, ng.A1,
ng.B+ng.B1*t, ng.B1
}
func (ng *NG4) ingestInfinite() {
ng.A, ng.B = ng.A1, ng.B1
}
func (ng *NG4) egest(t int64) {
ng.A1, ng.A, ng.B1, ng.B =
ng.B1, ng.B,
ng.A1-ng.B1*t, ng.A-ng.B*t
}
func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {
return func() NextFn {
next := cf()
done := false
return func() (int64, bool) {
if done {
return 0, false
}
for ng.needsIngest() {
if t, ok := next(); ok {
ng.ingest(t)
} else {
ng.ingestInfinite()
}
}
t := ng.A1 / ng.B1
ng.egest(t)
done = ng.isDone()
return t, true
}
}
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <iostream>
#include <vector>
#include <boost/rational.hpp>
using rational = boost::rational<unsigned long>;
unsigned long floor(const rational& r) {
return r.numerator()/r.denominator();
}
rational calkin_wilf_next(const rational& term) {
return 1UL/(2UL * floor(term) + 1UL - term);
}
std::vector<unsigned long> continued_fraction(const rational& r) {
unsigned long a = r.numerator();
unsigned long b = r.denominator();
std::vector<unsigned long> result;
do {
result.push_back(a/b);
unsigned long c = a;
a = b;
b = c % b;
} while (a != 1);
if (result.size() > 0 && result.size() % 2 == 0) {
--result.back();
result.push_back(1);
}
return result;
}
unsigned long term_number(const rational& r) {
unsigned long result = 0;
unsigned long d = 1;
unsigned long p = 0;
for (unsigned long n : continued_fraction(r)) {
for (unsigned long i = 0; i < n; ++i, ++p)
result |= (d << p);
d = !d;
}
return result;
}
int main() {
rational term = 1;
std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n";
for (int i = 1; i <= 20; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
term = calkin_wilf_next(term);
}
rational r(83116, 51639);
std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n";
}
| package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
func calkinWilf(n int) []*big.Rat {
cw := make([]*big.Rat, n+1)
cw[0] = big.NewRat(1, 1)
one := big.NewRat(1, 1)
two := big.NewRat(2, 1)
for i := 1; i < n; i++ {
t := new(big.Rat).Set(cw[i-1])
f, _ := t.Float64()
f = math.Floor(f)
t.SetFloat64(f)
t.Mul(t, two)
t.Sub(t, cw[i-1])
t.Add(t, one)
t.Inv(t)
cw[i] = new(big.Rat).Set(t)
}
return cw
}
func toContinued(r *big.Rat) []int {
a := r.Num().Int64()
b := r.Denom().Int64()
var res []int
for {
res = append(res, int(a/b))
t := a % b
a, b = b, t
if a == 1 {
break
}
}
le := len(res)
if le%2 == 0 {
res[le-1]--
res = append(res, 1)
}
return res
}
func getTermNumber(cf []int) int {
b := ""
d := "1"
for _, n := range cf {
b = strings.Repeat(d, n) + b
if d == "1" {
d = "0"
} else {
d = "1"
}
}
i, _ := strconv.ParseInt(b, 2, 64)
return int(i)
}
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() {
cw := calkinWilf(20)
fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:")
for i := 1; i <= 20; i++ {
fmt.Printf("%2d: %s\n", i, cw[i-1].RatString())
}
fmt.Println()
r := big.NewRat(83116, 51639)
cf := toContinued(r)
tn := getTermNumber(cf)
fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn))
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <iostream>
#include <vector>
#include <boost/rational.hpp>
using rational = boost::rational<unsigned long>;
unsigned long floor(const rational& r) {
return r.numerator()/r.denominator();
}
rational calkin_wilf_next(const rational& term) {
return 1UL/(2UL * floor(term) + 1UL - term);
}
std::vector<unsigned long> continued_fraction(const rational& r) {
unsigned long a = r.numerator();
unsigned long b = r.denominator();
std::vector<unsigned long> result;
do {
result.push_back(a/b);
unsigned long c = a;
a = b;
b = c % b;
} while (a != 1);
if (result.size() > 0 && result.size() % 2 == 0) {
--result.back();
result.push_back(1);
}
return result;
}
unsigned long term_number(const rational& r) {
unsigned long result = 0;
unsigned long d = 1;
unsigned long p = 0;
for (unsigned long n : continued_fraction(r)) {
for (unsigned long i = 0; i < n; ++i, ++p)
result |= (d << p);
d = !d;
}
return result;
}
int main() {
rational term = 1;
std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n";
for (int i = 1; i <= 20; ++i) {
std::cout << std::setw(2) << i << ": " << term << '\n';
term = calkin_wilf_next(term);
}
rational r(83116, 51639);
std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n";
}
| package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
func calkinWilf(n int) []*big.Rat {
cw := make([]*big.Rat, n+1)
cw[0] = big.NewRat(1, 1)
one := big.NewRat(1, 1)
two := big.NewRat(2, 1)
for i := 1; i < n; i++ {
t := new(big.Rat).Set(cw[i-1])
f, _ := t.Float64()
f = math.Floor(f)
t.SetFloat64(f)
t.Mul(t, two)
t.Sub(t, cw[i-1])
t.Add(t, one)
t.Inv(t)
cw[i] = new(big.Rat).Set(t)
}
return cw
}
func toContinued(r *big.Rat) []int {
a := r.Num().Int64()
b := r.Denom().Int64()
var res []int
for {
res = append(res, int(a/b))
t := a % b
a, b = b, t
if a == 1 {
break
}
}
le := len(res)
if le%2 == 0 {
res[le-1]--
res = append(res, 1)
}
return res
}
func getTermNumber(cf []int) int {
b := ""
d := "1"
for _, n := range cf {
b = strings.Repeat(d, n) + b
if d == "1" {
d = "0"
} else {
d = "1"
}
}
i, _ := strconv.ParseInt(b, 2, 64)
return int(i)
}
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() {
cw := calkinWilf(20)
fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:")
for i := 1; i <= 20; i++ {
fmt.Printf("%2d: %s\n", i, cw[i-1].RatString())
}
fmt.Println()
r := big.NewRat(83116, 51639)
cf := toContinued(r)
tn := getTermNumber(cf)
fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn))
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <array>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
auto init_zc() {
std::array<int, 1000> zc;
zc.fill(0);
zc[0] = 3;
for (int x = 1; x <= 9; ++x) {
zc[x] = 2;
zc[10 * x] = 2;
zc[100 * x] = 2;
for (int y = 10; y <= 90; y += 10) {
zc[y + x] = 1;
zc[10 * y + x] = 1;
zc[10 * (y + x)] = 1;
}
}
return zc;
}
template <typename clock_type>
auto elapsed(const std::chrono::time_point<clock_type>& t0) {
auto t1 = clock_type::now();
auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);
return duration.count();
}
int main() {
auto zc = init_zc();
auto t0 = std::chrono::high_resolution_clock::now();
int trail = 1, first = 0;
double total = 0;
std::vector<int> rfs{1};
std::cout << std::fixed << std::setprecision(10);
for (int f = 2; f <= 50000; ++f) {
int carry = 0, d999, zeroes = (trail - 1) * 3, len = rfs.size();
for (int j = trail - 1; j < len || carry != 0; ++j) {
if (j < len)
carry += rfs[j] * f;
d999 = carry % 1000;
if (j < len)
rfs[j] = d999;
else
rfs.push_back(d999);
zeroes += zc[d999];
carry /= 1000;
}
while (rfs[trail - 1] == 0)
++trail;
d999 = rfs.back();
d999 = d999 < 100 ? (d999 < 10 ? 2 : 1) : 0;
zeroes -= d999;
int digits = rfs.size() * 3 - d999;
total += double(zeroes) / digits;
double ratio = total / f;
if (ratio >= 0.16)
first = 0;
else if (first == 0)
first = f;
if (f == 100 || f == 1000 || f == 10000) {
std::cout << "Mean proportion of zero digits in factorials to " << f
<< " is " << ratio << ". (" << elapsed(t0) << "ms)\n";
}
}
std::cout << "The mean proportion dips permanently below 0.16 at " << first
<< ". (" << elapsed(t0) << "ms)\n";
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
func main() {
fact := big.NewInt(1)
sum := 0.0
first := int64(0)
firstRatio := 0.0
fmt.Println("The mean proportion of zero digits in factorials up to the following are:")
for n := int64(1); n <= 50000; n++ {
fact.Mul(fact, big.NewInt(n))
bytes := []byte(fact.String())
digits := len(bytes)
zeros := 0
for _, b := range bytes {
if b == '0' {
zeros++
}
}
sum += float64(zeros)/float64(digits)
ratio := sum / float64(n)
if n == 100 || n == 1000 || n == 10000 {
fmt.Printf("%6s = %12.10f\n", rcu.Commatize(int(n)), ratio)
}
if first > 0 && ratio >= 0.16 {
first = 0
firstRatio = 0.0
} else if first == 0 && ratio < 0.16 {
first = n
firstRatio = ratio
}
}
fmt.Printf("%6s = %12.10f", rcu.Commatize(int(first)), firstRatio)
fmt.Println(" (stays below 0.16 after this)")
fmt.Printf("%6s = %12.10f\n", "50,000", sum / 50000)
}
|
Convert this C++ block to Go, preserving its control flow and logic. |
#include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>
typedef std::pair<double, double> point_t;
typedef std::pair<point_t, point_t> points_t;
double distance_between(const point_t& a, const point_t& b) {
return std::sqrt(std::pow(b.first - a.first, 2)
+ std::pow(b.second - a.second, 2));
}
std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {
if (points.size() < 2) {
return { -1, { { 0, 0 }, { 0, 0 } } };
}
auto minDistance = std::abs(distance_between(points.at(0), points.at(1)));
points_t minPoints = { points.at(0), points.at(1) };
for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {
for (auto j = i + 1; j < std::end(points); ++j) {
auto newDistance = std::abs(distance_between(*i, *j));
if (newDistance < minDistance) {
minDistance = newDistance;
minPoints.first = *i;
minPoints.second = *j;
}
}
}
return { minDistance, minPoints };
}
std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,
const std::vector<point_t>& yP) {
if (xP.size() <= 3) {
return find_closest_brute(xP);
}
auto N = xP.size();
auto xL = std::vector<point_t>();
auto xR = std::vector<point_t>();
std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));
std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));
auto xM = xP.at((N-1) / 2).first;
auto yL = std::vector<point_t>();
auto yR = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {
return p.first <= xM;
});
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {
return p.first > xM;
});
auto p1 = find_closest_optimized(xL, yL);
auto p2 = find_closest_optimized(xR, yR);
auto minPair = (p1.first <= p2.first) ? p1 : p2;
auto yS = std::vector<point_t>();
std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {
return std::abs(xM - p.first) < minPair.first;
});
auto result = minPair;
for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {
for (auto k = i + 1; k != std::end(yS) &&
((k->second - i->second) < minPair.first); ++k) {
auto newDistance = std::abs(distance_between(*k, *i));
if (newDistance < result.first) {
result = { newDistance, { *k, *i } };
}
}
}
return result;
}
void print_point(const point_t& point) {
std::cout << "(" << point.first
<< ", " << point.second
<< ")";
}
int main(int argc, char * argv[]) {
std::default_random_engine re(std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now()));
std::uniform_real_distribution<double> urd(-500.0, 500.0);
std::vector<point_t> points(100);
std::generate(std::begin(points), std::end(points), [&urd, &re]() {
return point_t { 1000 + urd(re), 1000 + urd(re) };
});
auto answer = find_closest_brute(points);
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.first < b.first;
});
auto xP = points;
std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
return a.second < b.second;
});
auto yP = points;
std::cout << "Min distance (brute): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
answer = find_closest_optimized(xP, yP);
std::cout << "\nMin distance (optimized): " << answer.first << " ";
print_point(answer.second.first);
std::cout << ", ";
print_point(answer.second.second);
return 0;
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type xy struct {
x, y float64
}
const n = 1000
const scale = 100.
func d(p1, p2 xy) float64 {
return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}
func main() {
rand.Seed(time.Now().Unix())
points := make([]xy, n)
for i := range points {
points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
}
p1, p2 := closestPair(points)
fmt.Println(p1, p2)
fmt.Println("distance:", d(p1, p2))
}
func closestPair(points []xy) (p1, p2 xy) {
if len(points) < 2 {
panic("at least two points expected")
}
min := 2 * scale
for i, q1 := range points[:len(points)-1] {
for _, q2 := range points[i+1:] {
if dq := d(q1, q2); dq < min {
p1, p2 = q1, q2
min = dq
}
}
}
return
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | int i;
void* address_of_i = &i;
| package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = int64(uintptr(ptr))
fmt.Printf("Pointer stored in int64: %#016x\n", addr64)
}
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
addr32 = int32(uintptr(ptr))
fmt.Printf("Pointer stored in int32: %#08x\n", addr32)
}
addr := uintptr(ptr)
fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)
fmt.Println("value as float:", myVar)
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *i)
}
|
Write the same code in Go as shown below in C++. | class Animal
{
};
class Dog: public Animal
{
};
class Lab: public Dog
{
};
class Collie: public Dog
{
};
class Cat: public Animal
{
};
| package main
type animal struct {
alive bool
}
type dog struct {
animal
obedienceTrained bool
}
type cat struct {
animal
litterBoxTrained bool
}
type lab struct {
dog
color string
}
type collie struct {
dog
catchesFrisbee bool
}
func main() {
var pet lab
pet.alive = true
pet.obedienceTrained = false
pet.color = "yellow"
}
|
Generate an equivalent Go version of this C++ code. | #include <map>
|
var x map[string]int
x = make(map[string]int)
x = make(map[string]int, 42)
x["foo"] = 3
y1 := x["bar"]
y2, ok := x["bar"]
delete(x, "foo")
x = map[string]int{
"foo": 2, "bar": 42, "baz": -1,
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
std::vector<int> generate_primes(int limit) {
std::vector<bool> sieve(limit >> 1, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
int main() {
using big_int = mpz_class;
const int limit = 11000;
std::vector<big_int> f{1};
f.reserve(limit);
big_int factorial = 1;
for (int i = 1; i < limit; ++i) {
factorial *= i;
f.push_back(factorial);
}
std::vector<int> primes = generate_primes(limit);
std::cout << " n | Wilson primes\n--------------------\n";
for (int n = 1, s = -1; n <= 11; ++n, s = -s) {
std::cout << std::setw(2) << n << " |";
for (int p : primes) {
if (p >= n && (f[n - 1] * f[p - n] - s) % (p * p) == 0)
std::cout << ' ' << p;
}
std::cout << '\n';
}
}
| package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
const LIMIT = 11000
primes := rcu.Primes(LIMIT)
facts := make([]*big.Int, LIMIT)
facts[0] = big.NewInt(1)
for i := int64(1); i < LIMIT; i++ {
facts[i] = new(big.Int)
facts[i].Mul(facts[i-1], big.NewInt(i))
}
sign := int64(1)
f := new(big.Int)
zero := new(big.Int)
fmt.Println(" n: Wilson primes")
fmt.Println("--------------------")
for n := 1; n < 12; n++ {
fmt.Printf("%2d: ", n)
sign = -sign
for _, p := range primes {
if p < n {
continue
}
f.Mul(facts[n-1], facts[p-n])
f.Sub(f, big.NewInt(sign))
p2 := int64(p * p)
bp2 := big.NewInt(p2)
if f.Rem(f, bp2).Cmp(zero) == 0 {
fmt.Printf("%d ", p)
}
}
fmt.Println()
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <primesieve.hpp>
class prime_sieve {
public:
explicit prime_sieve(uint64_t limit);
bool is_prime(uint64_t n) const {
return n == 2 || ((n & 1) == 1 && sieve[n >> 1]);
}
private:
std::vector<bool> sieve;
};
prime_sieve::prime_sieve(uint64_t limit) : sieve((limit + 1) / 2, false) {
primesieve::iterator iter;
uint64_t prime = iter.next_prime();
while ((prime = iter.next_prime()) <= limit) {
sieve[prime >> 1] = true;
}
}
template <typename T> void print(std::ostream& out, const std::vector<T>& v) {
if (!v.empty()) {
out << '[';
auto i = v.begin();
out << *i++;
for (; i != v.end(); ++i)
out << ", " << *i;
out << ']';
}
}
std::string to_string(const std::vector<unsigned int>& v) {
static constexpr char digits[] =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (auto i : v)
str += digits[i];
return str;
}
bool increment(std::vector<unsigned int>& digits, unsigned int max_base) {
for (auto i = digits.rbegin(); i != digits.rend(); ++i) {
if (*i + 1 != max_base) {
++*i;
return true;
}
*i = 0;
}
return false;
}
void multi_base_primes(unsigned int max_base, unsigned int max_length) {
prime_sieve sieve(static_cast<uint64_t>(std::pow(max_base, max_length)));
for (unsigned int length = 1; length <= max_length; ++length) {
std::cout << length
<< "-character strings which are prime in most bases: ";
unsigned int most_bases = 0;
std::vector<
std::pair<std::vector<unsigned int>, std::vector<unsigned int>>>
max_strings;
std::vector<unsigned int> digits(length, 0);
digits[0] = 1;
std::vector<unsigned int> bases;
do {
auto max = std::max_element(digits.begin(), digits.end());
unsigned int min_base = 2;
if (max != digits.end())
min_base = std::max(min_base, *max + 1);
if (most_bases > max_base - min_base + 1)
continue;
bases.clear();
for (unsigned int b = min_base; b <= max_base; ++b) {
if (max_base - b + 1 + bases.size() < most_bases)
break;
uint64_t n = 0;
for (auto d : digits)
n = n * b + d;
if (sieve.is_prime(n))
bases.push_back(b);
}
if (bases.size() > most_bases) {
most_bases = bases.size();
max_strings.clear();
}
if (bases.size() == most_bases)
max_strings.emplace_back(digits, bases);
} while (increment(digits, max_base));
std::cout << most_bases << '\n';
for (const auto& m : max_strings) {
std::cout << to_string(m.first) << " -> ";
print(std::cout, m.second);
std::cout << '\n';
}
std::cout << '\n';
}
}
int main(int argc, char** argv) {
unsigned int max_base = 36;
unsigned int max_length = 4;
for (int arg = 1; arg + 1 < argc; ++arg) {
if (strcmp(argv[arg], "-max_base") == 0)
max_base = strtoul(argv[++arg], nullptr, 10);
else if (strcmp(argv[arg], "-max_length") == 0)
max_length = strtoul(argv[++arg], nullptr, 10);
}
if (max_base > 62) {
std::cerr << "Max base cannot be greater than 62.\n";
return EXIT_FAILURE;
}
if (max_base < 2) {
std::cerr << "Max base cannot be less than 2.\n";
return EXIT_FAILURE;
}
multi_base_primes(max_base, max_length);
return EXIT_SUCCESS;
}
| package main
import (
"fmt"
"math"
"rcu"
)
var maxDepth = 6
var maxBase = 36
var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true)
var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var maxStrings [][][]int
var mostBases = -1
func maxSlice(a []int) int {
max := 0
for _, e := range a {
if e > max {
max = e
}
}
return max
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
func process(indices []int) {
minBase := maxInt(2, maxSlice(indices)+1)
if maxBase - minBase + 1 < mostBases {
return
}
var bases []int
for b := minBase; b <= maxBase; b++ {
n := 0
for _, i := range indices {
n = n*b + i
}
if !c[n] {
bases = append(bases, b)
}
}
count := len(bases)
if count > mostBases {
mostBases = count
indices2 := make([]int, len(indices))
copy(indices2, indices)
maxStrings = [][][]int{[][]int{indices2, bases}}
} else if count == mostBases {
indices2 := make([]int, len(indices))
copy(indices2, indices)
maxStrings = append(maxStrings, [][]int{indices2, bases})
}
}
func printResults() {
fmt.Printf("%d\n", len(maxStrings[0][1]))
for _, m := range maxStrings {
s := ""
for _, i := range m[0] {
s = s + string(digits[i])
}
fmt.Printf("%s -> %v\n", s, m[1])
}
}
func nestedFor(indices []int, length, level int) {
if level == len(indices) {
process(indices)
} else {
indices[level] = 0
if level == 0 {
indices[level] = 1
}
for indices[level] < length {
nestedFor(indices, length, level+1)
indices[level]++
}
}
}
func main() {
for depth := 1; depth <= maxDepth; depth++ {
fmt.Print(depth, " character strings which are prime in most bases: ")
maxStrings = maxStrings[:0]
mostBases = -1
indices := make([]int, depth)
nestedFor(indices, maxBase, 0)
printResults()
fmt.Println()
}
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. |
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return QColor(r * 255, g * 255, b * 255);
}
}
ColorWheelWidget::ColorWheelWidget(QWidget *parent)
: QWidget(parent) {
setWindowTitle(tr("Color Wheel"));
resize(400, 400);
}
void ColorWheelWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
const QColor backgroundColor(0, 0, 0);
const QColor white(255, 255, 255);
painter.fillRect(event->rect(), backgroundColor);
const int margin = 10;
const double diameter = std::min(width(), height()) - 2*margin;
QPointF center(width()/2.0, height()/2.0);
QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0,
diameter, diameter);
for (int angle = 0; angle < 360; ++angle) {
QColor color(hsvToRgb(angle, 1.0, 1.0));
QRadialGradient gradient(center, diameter/2.0);
gradient.setColorAt(0, white);
gradient.setColorAt(1, color);
QBrush brush(gradient);
QPen pen(brush, 1.0);
painter.setPen(pen);
painter.setBrush(brush);
painter.drawPie(rect, angle * 16, 16);
}
}
| package main
import (
"github.com/fogleman/gg"
"math"
)
const tau = 2 * math.Pi
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func colorWheel(dc *gg.Context) {
width, height := dc.Width(), dc.Height()
centerX, centerY := width/2, height/2
radius := centerX
if centerY < radius {
radius = centerY
}
for y := 0; y < height; y++ {
dy := float64(y - centerY)
for x := 0; x < width; x++ {
dx := float64(x - centerX)
dist := math.Sqrt(dx*dx + dy*dy)
if dist <= float64(radius) {
theta := math.Atan2(dy, dx)
hue := (theta + math.Pi) / tau
r, g, b := hsb2rgb(hue, 1, 1)
dc.SetRGB255(r, g, b)
dc.SetPixel(x, y)
}
}
}
}
func main() {
const width, height = 480, 480
dc := gg.NewContext(width, height)
dc.SetRGB(1, 1, 1)
dc.Clear()
colorWheel(dc)
dc.SavePNG("color_wheel.png")
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <windows.h>
#include <math.h>
#include <string>
const int BMP_SIZE = 240, MY_TIMER = 987654;
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; }
DWORD* bits() { return ( DWORD* )pBits; }
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 plasma
{
public:
plasma() {
currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;
_bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();
plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
int i, j, dst = 0;
double temp;
for( j = 0; j < BMP_SIZE * 2; j++ ) {
for( i = 0; i < BMP_SIZE * 2; i++ ) {
plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );
plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) +
( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );
dst++;
}
}
}
void update() {
DWORD dst;
BYTE a, c1,c2, c3;
currentTime += ( double )( rand() % 2 + 1 );
int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ),
x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ),
x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),
y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ),
y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ),
y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );
int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;
DWORD* bits = _bmp.bits();
for( int j = 0; j < BMP_SIZE; j++ ) {
dst = j * BMP_SIZE;
for( int i= 0; i < BMP_SIZE; i++ ) {
a = plasma2[src1] + plasma1[src2] + plasma2[src3];
c1 = a << 1; c2 = a << 2; c3 = a << 3;
bits[dst + i] = RGB( c1, c2, c3 );
src1++; src2++; src3++;
}
src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;
}
draw();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
void draw() {
HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
}
myBitmap _bmp; HWND _hwnd; float _ang;
BYTE *plasma1, *plasma2;
double currentTime; int _WD, _WV;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst; _hwnd = InitAll();
SetTimer( _hwnd, MY_TIMER, 15, NULL );
_plasma.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 );
}
}
return UnregisterClass( "_MY_PLASMA_", _hInst );
}
private:
void wnd::doPaint( HDC dc ) { _plasma.update(); }
void wnd::doTimer() { _plasma.update(); }
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_PAINT: {
PAINTSTRUCT ps;
_inst->doPaint( BeginPaint( hWnd, &ps ) );
EndPaint( hWnd, &ps );
return 0;
}
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_TIMER: _inst->doTimer(); 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_PLASMA_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;
};
wnd* wnd::_inst = 0;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
wnd myWnd;
return myWnd.Run( hInstance );
}
| package main
import (
"image"
"image/color"
"image/gif"
"log"
"math"
"os"
)
func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) {
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
img.SetColorIndex(x, y, ci)
}
}
}
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func main() {
const degToRad = math.Pi / 180
const nframes = 100
const delay = 4
w, h := 640, 640
anim := gif.GIF{LoopCount: nframes}
rect := image.Rect(0, 0, w, h)
palette := make([]color.Color, nframes+1)
palette[0] = color.White
for i := 1; i <= nframes; i++ {
r, g, b := hsb2rgb(float64(i)/nframes, 1, 1)
palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255}
}
for f := 1; f <= nframes; f++ {
img := image.NewPaletted(rect, palette)
setBackgroundColor(img, w, h, 0)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
fx, fy := float64(x), float64(y)
value := math.Sin(fx / 16)
value += math.Sin(fy / 8)
value += math.Sin((fx + fy) / 16)
value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8)
value += 4
value /= 8
_, rem := math.Modf(value + float64(f)/float64(nframes))
ci := uint8(nframes*rem) + 1
img.SetColorIndex(x, y, ci)
}
}
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
file, err := os.Create("plasma.gif")
if err != nil {
log.Fatal(err)
}
defer file.Close()
if err2 := gif.EncodeAll(file, &anim); err != nil {
log.Fatal(err2)
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);
public:
abelian_sandpile();
explicit abelian_sandpile(std::initializer_list<int> init);
void stabilize();
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile&);
bool operator==(const abelian_sandpile&);
private:
int& cell_value(size_t row, size_t column) {
return cells_[cell_index(row, column)];
}
static size_t cell_index(size_t row, size_t column) {
return row * sp_columns + column;
}
static size_t row_index(size_t cell_index) {
return cell_index/sp_columns;
}
static size_t column_index(size_t cell_index) {
return cell_index % sp_columns;
}
std::array<int, sp_cells> cells_;
};
abelian_sandpile::abelian_sandpile() {
cells_.fill(0);
}
abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {
assert(init.size() == sp_cells);
std::copy(init.begin(), init.end(), cells_.begin());
}
abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {
for (size_t i = 0; i < sp_cells; ++i)
cells_[i] += other.cells_[i];
stabilize();
return *this;
}
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return cells_ == other.cells_;
}
bool abelian_sandpile::is_stable() const {
return std::none_of(cells_.begin(), cells_.end(),
[](int a) { return a >= sp_limit; });
}
void abelian_sandpile::topple() {
for (size_t i = 0; i < sp_cells; ++i) {
if (cells_[i] >= sp_limit) {
cells_[i] -= sp_limit;
size_t row = row_index(i);
size_t column = column_index(i);
if (row > 0)
++cell_value(row - 1, column);
if (row + 1 < sp_rows)
++cell_value(row + 1, column);
if (column > 0)
++cell_value(row, column - 1);
if (column + 1 < sp_columns)
++cell_value(row, column + 1);
break;
}
}
}
void abelian_sandpile::stabilize() {
while (!is_stable())
topple();
}
abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {
abelian_sandpile c(a);
c += b;
return c;
}
std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
int main() {
std::cout << std::boolalpha;
std::cout << "Avalanche:\n";
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "Commutativity:\n";
abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};
abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};
abelian_sandpile sum1(s1 + s2);
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
std::cout << "\ns2 + s1 = \n" << sum2;
std::cout << '\n';
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};
abelian_sandpile sum3(s3 + s3_id);
abelian_sandpile sum4(s3_id + s3_id);
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
std::cout << "\ns3_id + s3_id = \n" << sum4;
return 0;
}
| package main
import (
"fmt"
"strconv"
"strings"
)
type sandpile struct{ a [9]int }
var neighbors = [][]int{
{1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},
}
func newSandpile(a [9]int) *sandpile { return &sandpile{a} }
func (s *sandpile) plus(other *sandpile) *sandpile {
b := [9]int{}
for i := 0; i < 9; i++ {
b[i] = s.a[i] + other.a[i]
}
return &sandpile{b}
}
func (s *sandpile) isStable() bool {
for _, e := range s.a {
if e > 3 {
return false
}
}
return true
}
func (s *sandpile) topple() {
for i := 0; i < 9; i++ {
if s.a[i] > 3 {
s.a[i] -= 4
for _, j := range neighbors[i] {
s.a[j]++
}
return
}
}
}
func (s *sandpile) String() string {
var sb strings.Builder
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ")
}
sb.WriteString("\n")
}
return sb.String()
}
func main() {
fmt.Println("Avalanche of topplings:\n")
s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})
fmt.Println(s4)
for !s4.isStable() {
s4.topple()
fmt.Println(s4)
}
fmt.Println("Commutative additions:\n")
s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})
s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})
s3_a := s1.plus(s2)
for !s3_a.isStable() {
s3_a.topple()
}
s3_b := s2.plus(s1)
for !s3_b.isStable() {
s3_b.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a)
fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b)
fmt.Println("Addition of identity sandpile:\n")
s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})
s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})
s4 = s3.plus(s3_id)
for !s4.isStable() {
s4.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4)
fmt.Println("Addition of identities:\n")
s5 := s3_id.plus(s3_id)
for !s5.isStable() {
s5.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5)
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);
public:
abelian_sandpile();
explicit abelian_sandpile(std::initializer_list<int> init);
void stabilize();
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile&);
bool operator==(const abelian_sandpile&);
private:
int& cell_value(size_t row, size_t column) {
return cells_[cell_index(row, column)];
}
static size_t cell_index(size_t row, size_t column) {
return row * sp_columns + column;
}
static size_t row_index(size_t cell_index) {
return cell_index/sp_columns;
}
static size_t column_index(size_t cell_index) {
return cell_index % sp_columns;
}
std::array<int, sp_cells> cells_;
};
abelian_sandpile::abelian_sandpile() {
cells_.fill(0);
}
abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {
assert(init.size() == sp_cells);
std::copy(init.begin(), init.end(), cells_.begin());
}
abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {
for (size_t i = 0; i < sp_cells; ++i)
cells_[i] += other.cells_[i];
stabilize();
return *this;
}
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return cells_ == other.cells_;
}
bool abelian_sandpile::is_stable() const {
return std::none_of(cells_.begin(), cells_.end(),
[](int a) { return a >= sp_limit; });
}
void abelian_sandpile::topple() {
for (size_t i = 0; i < sp_cells; ++i) {
if (cells_[i] >= sp_limit) {
cells_[i] -= sp_limit;
size_t row = row_index(i);
size_t column = column_index(i);
if (row > 0)
++cell_value(row - 1, column);
if (row + 1 < sp_rows)
++cell_value(row + 1, column);
if (column > 0)
++cell_value(row, column - 1);
if (column + 1 < sp_columns)
++cell_value(row, column + 1);
break;
}
}
}
void abelian_sandpile::stabilize() {
while (!is_stable())
topple();
}
abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {
abelian_sandpile c(a);
c += b;
return c;
}
std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
int main() {
std::cout << std::boolalpha;
std::cout << "Avalanche:\n";
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "Commutativity:\n";
abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};
abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};
abelian_sandpile sum1(s1 + s2);
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
std::cout << "\ns2 + s1 = \n" << sum2;
std::cout << '\n';
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};
abelian_sandpile sum3(s3 + s3_id);
abelian_sandpile sum4(s3_id + s3_id);
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
std::cout << "\ns3_id + s3_id = \n" << sum4;
return 0;
}
| package main
import (
"fmt"
"strconv"
"strings"
)
type sandpile struct{ a [9]int }
var neighbors = [][]int{
{1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7},
}
func newSandpile(a [9]int) *sandpile { return &sandpile{a} }
func (s *sandpile) plus(other *sandpile) *sandpile {
b := [9]int{}
for i := 0; i < 9; i++ {
b[i] = s.a[i] + other.a[i]
}
return &sandpile{b}
}
func (s *sandpile) isStable() bool {
for _, e := range s.a {
if e > 3 {
return false
}
}
return true
}
func (s *sandpile) topple() {
for i := 0; i < 9; i++ {
if s.a[i] > 3 {
s.a[i] -= 4
for _, j := range neighbors[i] {
s.a[j]++
}
return
}
}
}
func (s *sandpile) String() string {
var sb strings.Builder
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ")
}
sb.WriteString("\n")
}
return sb.String()
}
func main() {
fmt.Println("Avalanche of topplings:\n")
s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3})
fmt.Println(s4)
for !s4.isStable() {
s4.topple()
fmt.Println(s4)
}
fmt.Println("Commutative additions:\n")
s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3})
s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0})
s3_a := s1.plus(s2)
for !s3_a.isStable() {
s3_a.topple()
}
s3_b := s2.plus(s1)
for !s3_b.isStable() {
s3_b.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a)
fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b)
fmt.Println("Addition of identity sandpile:\n")
s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3})
s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2})
s4 = s3.plus(s3_id)
for !s4.isStable() {
s4.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4)
fmt.Println("Addition of identities:\n")
s5 := s3_id.plus(s3_id)
for !s5.isStable() {
s5.topple()
}
fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5)
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int digit_product(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
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;
}
bool is_rhonda(int base, int n) {
return digit_product(base, n) == base * prime_factor_sum(n);
}
std::string to_string(int base, int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
int main() {
const int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (is_prime(base))
continue;
std::cout << "First " << limit << " Rhonda numbers to base " << base
<< ":\n";
int numbers[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (is_rhonda(base, n))
numbers[count++] = n;
}
std::cout << "In base 10:";
for (int i = 0; i < limit; ++i)
std::cout << ' ' << numbers[i];
std::cout << "\nIn base " << base << ':';
for (int i = 0; i < limit; ++i)
std::cout << ' ' << to_string(base, numbers[i]);
std::cout << "\n\n";
}
}
| package main
import (
"fmt"
"rcu"
"strconv"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
func main() {
for b := 2; b <= 36; b++ {
if rcu.IsPrime(b) {
continue
}
count := 0
var rhonda []int
for n := 1; count < 15; n++ {
digits := rcu.Digits(n, b)
if !contains(digits, 0) {
var anyEven = false
for _, d := range digits {
if d%2 == 0 {
anyEven = true
break
}
}
if b != 10 || (contains(digits, 5) && anyEven) {
calc1 := 1
for _, d := range digits {
calc1 *= d
}
calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))
if calc1 == calc2 {
rhonda = append(rhonda, n)
count++
}
}
}
}
if len(rhonda) > 0 {
fmt.Printf("\nFirst 15 Rhonda numbers in base %d:\n", b)
rhonda2 := make([]string, len(rhonda))
counts2 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda2[i] = fmt.Sprintf("%d", r)
counts2[i] = len(rhonda2[i])
}
rhonda3 := make([]string, len(rhonda))
counts3 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda3[i] = strconv.FormatInt(int64(r), b)
counts3[i] = len(rhonda3[i])
}
maxLen2 := rcu.MaxInts(counts2)
maxLen3 := rcu.MaxInts(counts3)
maxLen := maxLen2
if maxLen3 > maxLen {
maxLen = maxLen3
}
maxLen++
fmt.Printf("In base 10: %*s\n", maxLen, rhonda2)
fmt.Printf("In base %-2d: %*s\n", b, maxLen, rhonda3)
}
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include <cstdio>
#include <cstdlib>
class Point {
protected:
int x, y;
public:
Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
Point(const Point &p) : x(p.x), y(p.y) {}
virtual ~Point() {}
const Point& operator=(const Point &p) {
if (this != &p) {
x = p.x;
y = p.y;
}
return *this;
}
int getX() { return x; }
int getY() { return y; }
void setX(int x0) { x = x0; }
void setY(int y0) { y = y0; }
virtual void print() { printf("Point\n"); }
};
class Circle: public Point {
private:
int r;
public:
Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
virtual ~Circle() {}
const Circle& operator=(const Circle &c) {
if (this != &c) {
x = c.x;
y = c.y;
r = c.r;
}
return *this;
}
int getR() { return r; }
void setR(int r0) { r = r0; }
virtual void print() { printf("Circle\n"); }
};
int main() {
Point *p = new Point();
Point *c = new Circle();
p->print();
c->print();
delete p;
delete c;
return EXIT_SUCCESS;
}
| package main
import "fmt"
type point struct {
x, y float64
}
type circle struct {
x, y, r float64
}
type printer interface {
print()
}
func (p *point) print() {
fmt.Println(p.x, p.y)
}
func (c *circle) print() {
fmt.Println(c.x, c.y, c.r)
}
func main() {
var i printer
i = newPoint(3, 4)
i.print()
i = newCircle(5, 12, 13)
i.print()
}
func (p *point) getX() float64 { return p.x }
func (p *point) getY() float64 { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }
func (c *circle) getX() float64 { return c.x }
func (c *circle) getY() float64 { return c.y }
func (c *circle) getR() float64 { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }
func (p *point) clone() *point { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }
func (p *point) set(q *point) { *p = *q }
func (c *circle) set(d *circle) { *c = *d }
func newPoint(x, y float64) *point {
return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
return &circle{x, y, r}
}
|
Change the following C++ code into Go without altering its purpose. | #include <iostream>
#include <map>
#include <utility>
using namespace std;
template<typename T>
class FixedMap : private T
{
T m_defaultValues;
public:
FixedMap(T map)
: T(map), m_defaultValues(move(map)){}
using T::cbegin;
using T::cend;
using T::empty;
using T::find;
using T::size;
using T::at;
using T::begin;
using T::end;
auto& operator[](typename T::key_type&& key)
{
return this->at(forward<typename T::key_type>(key));
}
void erase(typename T::key_type&& key)
{
T::operator[](key) = m_defaultValues.at(key);
}
void clear()
{
T::operator=(m_defaultValues);
}
};
auto PrintMap = [](const auto &map)
{
for(auto &[key, value] : map)
{
cout << "{" << key << " : " << value << "} ";
}
cout << "\n\n";
};
int main(void)
{
cout << "Map intialized with values\n";
FixedMap<map<string, int>> fixedMap ({
{"a", 1},
{"b", 2}});
PrintMap(fixedMap);
cout << "Change the values of the keys\n";
fixedMap["a"] = 55;
fixedMap["b"] = 56;
PrintMap(fixedMap);
cout << "Reset the 'a' key\n";
fixedMap.erase("a");
PrintMap(fixedMap);
cout << "Change the values the again\n";
fixedMap["a"] = 88;
fixedMap["b"] = 99;
PrintMap(fixedMap);
cout << "Reset all keys\n";
fixedMap.clear();
PrintMap(fixedMap);
try
{
cout << "Try to add a new key\n";
fixedMap["newKey"] = 99;
}
catch (exception &ex)
{
cout << "error: " << ex.what();
}
}
| package romap
type Romap struct{ imap map[byte]int }
func New(m map[byte]int) *Romap {
if m == nil {
return nil
}
return &Romap{m}
}
func (rom *Romap) Get(key byte) (int, bool) {
i, ok := rom.imap[key]
return i, ok
}
func (rom *Romap) Reset(key byte) {
_, ok := rom.imap[key]
if ok {
rom.imap[key] = 0
}
}
|
Generate an equivalent Go version of this C++ code. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
if (ch < 'a' || ch > 'z')
continue;
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
bit = ch - 'a';
if (bits.test(bit))
return 0;
bits.set(bit);
break;
}
}
return bits.count();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
std::map<size_t, std::vector<std::string>, std::greater<int>> map;
while (getline(in, word)) {
if (word.size() <= 10)
continue;
size_t count = consonants(word);
if (count != 0)
map[count].push_back(word);
}
const int columns = 4;
for (const auto& p : map) {
std::cout << p.first << " consonants (" << p.second.size() << "):\n";
int n = 0;
for (const auto& word : p.second) {
std::cout << std::left << std::setw(18) << word;
++n;
if (n % columns == 0)
std::cout << '\n';
}
if (n % columns != 0)
std::cout << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func contains(list []int, value int) bool {
for _, v := range list {
if v == value {
return true
}
}
return false
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 10 {
words = append(words, s)
}
}
vowelIndices := []int{0, 4, 8, 14, 20}
wordGroups := make([][]string, 12)
for _, word := range words {
letters := make([]int, 26)
for _, c := range word {
index := c - 97
if index >= 0 && index < 26 {
letters[index]++
}
}
eligible := true
uc := 0
for i := 0; i < 26; i++ {
if !contains(vowelIndices, i) {
if letters[i] > 1 {
eligible = false
break
} else if letters[i] == 1 {
uc++
}
}
}
if eligible {
wordGroups[uc] = append(wordGroups[uc], word)
}
}
for i := 11; i >= 0; i-- {
count := len(wordGroups[i])
if count > 0 {
s := "s"
if count == 1 {
s = ""
}
fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i)
for j := 0; j < count; j++ {
fmt.Printf("%-15s", wordGroups[i][j])
if j > 0 && (j+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
if count%5 != 0 {
fmt.Println()
}
}
}
}
|
Please provide an equivalent version of this C++ code in Go. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
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 main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
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 main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
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 main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
|
Convert this C++ block to Go, preserving its control flow and logic. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
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 main() {
var primeRunes []rune
for i := 33; i < 256; i += 2 {
if isPrime(i) {
primeRunes = append(primeRunes, rune(i))
}
}
primeString := string(primeRunes)
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
fmt.Println("Prime words in", wordList, "are:")
for _, bword := range bwords {
word := string(bword)
ok := true
for _, c := range word {
if !strings.ContainsRune(primeString, c) {
ok = false
break
}
}
if ok {
fmt.Println(word)
}
}
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #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;
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "First 50 numbers which are the cube roots of the products of "
"their proper divisors:\n";
for (unsigned int n = 1, count = 0; count < 50000; ++n) {
if (n == 1 || divisor_count(n) == 8) {
++count;
if (count <= 50)
std::cout << std::setw(3) << n
<< (count % 10 == 0 ? '\n' : ' ');
else if (count == 500 || count == 5000 || count == 50000)
std::cout << std::setw(6) << count << "th: " << n << '\n';
}
}
}
| package main
import (
"fmt"
"math"
"rcu"
)
func divisorCount(n int) int {
k := 1
if n%2 == 1 {
k = 2
}
count := 0
sqrt := int(math.Sqrt(float64(n)))
for i := 1; i <= sqrt; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
}
return count
}
func main() {
var numbers50 []int
count := 0
for n := 1; count < 50000; n++ {
dc := divisorCount(n)
if n == 1 || dc == 8 {
count++
if count <= 50 {
numbers50 = append(numbers50, n)
if count == 50 {
rcu.PrintTable(numbers50, 10, 3, false)
}
} else if count == 500 {
fmt.Printf("\n500th : %s", rcu.Commatize(n))
} else if count == 5000 {
fmt.Printf("\n5,000th : %s", rcu.Commatize(n))
} else if count == 50000 {
fmt.Printf("\n50,000th: %s\n", rcu.Commatize(n))
}
}
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <array>
#include <iostream>
#include <primesieve.hpp>
class ormiston_triple_generator {
public:
ormiston_triple_generator() {
for (int i = 0; i < 2; ++i) {
primes_[i] = pi_.next_prime();
digits_[i] = get_digits(primes_[i]);
}
}
std::array<uint64_t, 3> next_triple() {
for (;;) {
uint64_t prime = pi_.next_prime();
auto digits = get_digits(prime);
bool is_triple = digits == digits_[0] && digits == digits_[1];
uint64_t prime0 = primes_[0];
primes_[0] = primes_[1];
primes_[1] = prime;
digits_[0] = digits_[1];
digits_[1] = digits;
if (is_triple)
return {prime0, primes_[0], primes_[1]};
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
std::array<uint64_t, 2> primes_;
std::array<std::array<int, 10>, 2> digits_;
};
int main() {
ormiston_triple_generator generator;
int count = 0;
std::cout << "Smallest members of first 25 Ormiston triples:\n";
for (; count < 25; ++count) {
auto primes = generator.next_triple();
std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {
auto primes = generator.next_triple();
if (primes[2] > limit) {
std::cout << "Number of Ormiston triples < " << limit << ": "
<< count << '\n';
limit *= 10;
}
}
}
| package main
import (
"fmt"
"rcu"
)
func main() {
const limit = 1e10
primes := rcu.Primes(limit)
var orm25 []int
j := int(1e9)
count := 0
var counts []int
for i := 0; i < len(primes)-2; i++ {
p1 := primes[i]
p2 := primes[i+1]
p3 := primes[i+2]
if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {
continue
}
key1 := 1
for _, dig := range rcu.Digits(p1, 10) {
key1 *= primes[dig]
}
key2 := 1
for _, dig := range rcu.Digits(p2, 10) {
key2 *= primes[dig]
}
if key1 != key2 {
continue
}
key3 := 1
for _, dig := range rcu.Digits(p3, 10) {
key3 *= primes[dig]
}
if key2 == key3 {
if count < 25 {
orm25 = append(orm25, p1)
}
if p1 >= j {
counts = append(counts, count)
j *= 10
}
count++
}
}
counts = append(counts, count)
fmt.Println("Smallest members of first 25 Ormiston triples:")
for i := 0; i < 25; i++ {
fmt.Printf("%8v ", orm25[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
j = int(1e9)
for i := 0; i < len(counts); i++ {
fmt.Printf("%s Ormiston triples before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j))
j *= 10
fmt.Println()
}
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <array>
#include <iostream>
#include <primesieve.hpp>
class ormiston_triple_generator {
public:
ormiston_triple_generator() {
for (int i = 0; i < 2; ++i) {
primes_[i] = pi_.next_prime();
digits_[i] = get_digits(primes_[i]);
}
}
std::array<uint64_t, 3> next_triple() {
for (;;) {
uint64_t prime = pi_.next_prime();
auto digits = get_digits(prime);
bool is_triple = digits == digits_[0] && digits == digits_[1];
uint64_t prime0 = primes_[0];
primes_[0] = primes_[1];
primes_[1] = prime;
digits_[0] = digits_[1];
digits_[1] = digits;
if (is_triple)
return {prime0, primes_[0], primes_[1]};
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
std::array<uint64_t, 2> primes_;
std::array<std::array<int, 10>, 2> digits_;
};
int main() {
ormiston_triple_generator generator;
int count = 0;
std::cout << "Smallest members of first 25 Ormiston triples:\n";
for (; count < 25; ++count) {
auto primes = generator.next_triple();
std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {
auto primes = generator.next_triple();
if (primes[2] > limit) {
std::cout << "Number of Ormiston triples < " << limit << ": "
<< count << '\n';
limit *= 10;
}
}
}
| package main
import (
"fmt"
"rcu"
)
func main() {
const limit = 1e10
primes := rcu.Primes(limit)
var orm25 []int
j := int(1e9)
count := 0
var counts []int
for i := 0; i < len(primes)-2; i++ {
p1 := primes[i]
p2 := primes[i+1]
p3 := primes[i+2]
if (p2-p1)%18 != 0 || (p3-p2)%18 != 0 {
continue
}
key1 := 1
for _, dig := range rcu.Digits(p1, 10) {
key1 *= primes[dig]
}
key2 := 1
for _, dig := range rcu.Digits(p2, 10) {
key2 *= primes[dig]
}
if key1 != key2 {
continue
}
key3 := 1
for _, dig := range rcu.Digits(p3, 10) {
key3 *= primes[dig]
}
if key2 == key3 {
if count < 25 {
orm25 = append(orm25, p1)
}
if p1 >= j {
counts = append(counts, count)
j *= 10
}
count++
}
}
counts = append(counts, count)
fmt.Println("Smallest members of first 25 Ormiston triples:")
for i := 0; i < 25; i++ {
fmt.Printf("%8v ", orm25[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
j = int(1e9)
for i := 0; i < len(counts); i++ {
fmt.Printf("%s Ormiston triples before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j))
j *= 10
fmt.Println()
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <iostream>
#include <iomanip>
#include <string>
class oo {
public:
void evolve( int l, int rule ) {
std::string cells = "O";
std::cout << " Rule #" << rule << ":\n";
for( int x = 0; x < l; x++ ) {
addNoCells( cells );
std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n";
step( cells, rule );
}
}
private:
void step( std::string& cells, int rule ) {
int bin;
std::string newCells;
for( size_t i = 0; i < cells.length() - 2; i++ ) {
bin = 0;
for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {
bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );
}
newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );
}
cells = newCells;
}
void addNoCells( std::string& s ) {
char l = s.at( 0 ) == 'O' ? '.' : 'O',
r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';
s = l + s + r;
s = l + s + r;
}
};
int main( int argc, char* argv[] ) {
oo o;
o.evolve( 35, 90 );
std::cout << "\n";
return 0;
}
| package main
import (
"fmt"
"strings"
)
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func evolve(l, rule int) {
fmt.Printf(" Rule #%d:\n", rule)
cells := "O"
for x := 0; x < l; x++ {
cells = addNoCells(cells)
width := 40 + (len(cells) >> 1)
fmt.Printf("%*s\n", width, cells)
cells = step(cells, rule)
}
}
func step(cells string, rule int) string {
newCells := new(strings.Builder)
for i := 0; i < len(cells)-2; i++ {
bin := 0
b := uint(2)
for n := i; n < i+3; n++ {
bin += btoi(cells[n] == 'O') << b
b >>= 1
}
a := '.'
if rule&(1<<uint(bin)) != 0 {
a = 'O'
}
newCells.WriteRune(a)
}
return newCells.String()
}
func addNoCells(cells string) string {
l, r := "O", "O"
if cells[0] == 'O' {
l = "."
}
if cells[len(cells)-1] == 'O' {
r = "."
}
cells = l + cells + r
cells = l + cells + r
return cells
}
func main() {
for _, r := range []int{90, 30} {
evolve(25, r)
fmt.Println()
}
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <iostream>
#include <iomanip>
#include <string>
class oo {
public:
void evolve( int l, int rule ) {
std::string cells = "O";
std::cout << " Rule #" << rule << ":\n";
for( int x = 0; x < l; x++ ) {
addNoCells( cells );
std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n";
step( cells, rule );
}
}
private:
void step( std::string& cells, int rule ) {
int bin;
std::string newCells;
for( size_t i = 0; i < cells.length() - 2; i++ ) {
bin = 0;
for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {
bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );
}
newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );
}
cells = newCells;
}
void addNoCells( std::string& s ) {
char l = s.at( 0 ) == 'O' ? '.' : 'O',
r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';
s = l + s + r;
s = l + s + r;
}
};
int main( int argc, char* argv[] ) {
oo o;
o.evolve( 35, 90 );
std::cout << "\n";
return 0;
}
| package main
import (
"fmt"
"strings"
)
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func evolve(l, rule int) {
fmt.Printf(" Rule #%d:\n", rule)
cells := "O"
for x := 0; x < l; x++ {
cells = addNoCells(cells)
width := 40 + (len(cells) >> 1)
fmt.Printf("%*s\n", width, cells)
cells = step(cells, rule)
}
}
func step(cells string, rule int) string {
newCells := new(strings.Builder)
for i := 0; i < len(cells)-2; i++ {
bin := 0
b := uint(2)
for n := i; n < i+3; n++ {
bin += btoi(cells[n] == 'O') << b
b >>= 1
}
a := '.'
if rule&(1<<uint(bin)) != 0 {
a = 'O'
}
newCells.WriteRune(a)
}
return newCells.String()
}
func addNoCells(cells string) string {
l, r := "O", "O"
if cells[0] == 'O' {
l = "."
}
if cells[len(cells)-1] == 'O' {
r = "."
}
cells = l + cells + r
cells = l + cells + r
return cells
}
func main() {
for _, r := range []int{90, 30} {
evolve(25, r)
fmt.Println()
}
}
|
Write the same code in Go as shown below in C++. | #include <fstream>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>
#include <stdlib.h>
using namespace std;
void fatal_error(string errtext, char *argv[])
{
cout << "%" << errtext << endl;
cout << "usage: " << argv[0] << " [filename.cp]" << endl;
exit(1);
}
string& ltrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(0, str.find_first_not_of(chars));
return str;
}
string& rtrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(str.find_last_not_of(chars) + 1);
return str;
}
string& trim(string& str, const string& chars = "\t\n\v\f\r ")
{
return ltrim(rtrim(str, chars), chars);
}
int main(int argc, char *argv[])
{
string fname = "";
string source = "";
try
{
fname = argv[1];
ifstream t(fname);
t.seekg(0, ios::end);
source.reserve(t.tellg());
t.seekg(0, ios::beg);
source.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
}
catch(const exception& e)
{
fatal_error("error while trying to read from specified file", argv);
}
string clipboard = "";
int loc = 0;
string remaining = source;
string line = "";
string command = "";
stringstream ss;
while(remaining.find("\n") != string::npos)
{
line = remaining.substr(0, remaining.find("\n"));
command = trim(line);
remaining = remaining.substr(remaining.find("\n") + 1);
try
{
if(line == "Copy")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
clipboard += line;
}
else if(line == "CopyFile")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
if(line == "TheF*ckingCode")
clipboard += source;
else
{
string filetext = "";
ifstream t(line);
t.seekg(0, ios::end);
filetext.reserve(t.tellg());
t.seekg(0, ios::beg);
filetext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
clipboard += filetext;
}
}
else if(line == "Duplicate")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
int amount = stoi(line);
string origClipboard = clipboard;
for(int i = 0; i < amount - 1; i++) {
clipboard += origClipboard;
}
}
else if(line == "Pasta!")
{
cout << clipboard << endl;
return 0;
}
else
{
ss << (loc + 1);
fatal_error("unknown command '" + command + "' encounter on line " + ss.str(), argv);
}
}
catch(const exception& e)
{
ss << (loc + 1);
fatal_error("error while executing command '" + command + "' on line " + ss.str(), argv);
}
loc += 2;
}
return 0;
}
|
package main
import (
"fmt"
"github.com/atotto/clipboard"
"io/ioutil"
"log"
"os"
"runtime"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
clipboard.WriteAll("")
log.Fatal(err)
}
}
func interpret(source string) {
source2 := source
if runtime.GOOS == "windows" {
source2 = strings.ReplaceAll(source, "\r\n", "\n")
}
lines := strings.Split(source2, "\n")
le := len(lines)
for i := 0; i < le; i++ {
lines[i] = strings.TrimSpace(lines[i])
switch lines[i] {
case "Copy":
if i == le-1 {
log.Fatal("There are no lines after the Copy command.")
}
i++
err := clipboard.WriteAll(lines[i])
check(err)
case "CopyFile":
if i == le-1 {
log.Fatal("There are no lines after the CopyFile command.")
}
i++
if lines[i] == "TheF*ckingCode" {
err := clipboard.WriteAll(source)
check(err)
} else {
bytes, err := ioutil.ReadFile(lines[i])
check(err)
err = clipboard.WriteAll(string(bytes))
check(err)
}
case "Duplicate":
if i == le-1 {
log.Fatal("There are no lines after the Duplicate command.")
}
i++
times, err := strconv.Atoi(lines[i])
check(err)
if times < 0 {
log.Fatal("Can't duplicate text a negative number of times.")
}
text, err := clipboard.ReadAll()
check(err)
err = clipboard.WriteAll(strings.Repeat(text, times+1))
check(err)
case "Pasta!":
text, err := clipboard.ReadAll()
check(err)
fmt.Println(text)
return
default:
if lines[i] == "" {
continue
}
log.Fatal("Unknown command, " + lines[i])
}
}
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There should be exactly one command line argument, the CopyPasta file path.")
}
bytes, err := ioutil.ReadFile(os.Args[1])
check(err)
interpret(string(bytes))
err = clipboard.WriteAll("")
check(err)
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
void print_non_twin_prime_sums(const std::vector<bool>& sums) {
int count = 0;
for (size_t i = 2; i < sums.size(); i += 2) {
if (!sums[i]) {
++count;
std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' ');
}
}
std::cout << "\nFound " << count << '\n';
}
int main() {
const int limit = 100001;
std::vector<bool> sieve = prime_sieve(limit + 2);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))
sieve[i] = false;
}
std::vector<bool> twin_prime_sums(limit, false);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i]) {
for (size_t j = i; i + j < limit; ++j) {
if (sieve[j])
twin_prime_sums[i + j] = true;
}
}
}
std::cout << "Non twin prime sums:\n";
print_non_twin_prime_sums(twin_prime_sums);
sieve[1] = true;
for (size_t i = 1; i + 1 < limit; ++i) {
if (sieve[i])
twin_prime_sums[i + 1] = true;
}
std::cout << "\nNon twin prime sums (including 1):\n";
print_non_twin_prime_sums(twin_prime_sums);
}
| package main
import (
"fmt"
"rcu"
)
const limit = 100000
func nonTwinSums(twins []int) []int {
sieve := make([]bool, limit+1)
for i := 0; i < len(twins); i++ {
for j := i; j < len(twins); j++ {
sum := twins[i] + twins[j]
if sum > limit {
break
}
sieve[sum] = true
}
}
var res []int
for i := 2; i < limit; i += 2 {
if !sieve[i] {
res = append(res, i)
}
}
return res
}
func main() {
primes := rcu.Primes(limit)[2:]
twins := []int{3}
for i := 0; i < len(primes)-1; i++ {
if primes[i+1]-primes[i] == 2 {
if twins[len(twins)-1] != primes[i] {
twins = append(twins, primes[i])
}
twins = append(twins, primes[i+1])
}
}
fmt.Println("Non twin prime sums:")
ntps := nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
fmt.Println("\nNon twin prime sums (including 1):")
twins = append([]int{1}, twins...)
ntps = nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
}
|
Write a version of this C++ function in Go with identical behavior. | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
void print_non_twin_prime_sums(const std::vector<bool>& sums) {
int count = 0;
for (size_t i = 2; i < sums.size(); i += 2) {
if (!sums[i]) {
++count;
std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' ');
}
}
std::cout << "\nFound " << count << '\n';
}
int main() {
const int limit = 100001;
std::vector<bool> sieve = prime_sieve(limit + 2);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))
sieve[i] = false;
}
std::vector<bool> twin_prime_sums(limit, false);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i]) {
for (size_t j = i; i + j < limit; ++j) {
if (sieve[j])
twin_prime_sums[i + j] = true;
}
}
}
std::cout << "Non twin prime sums:\n";
print_non_twin_prime_sums(twin_prime_sums);
sieve[1] = true;
for (size_t i = 1; i + 1 < limit; ++i) {
if (sieve[i])
twin_prime_sums[i + 1] = true;
}
std::cout << "\nNon twin prime sums (including 1):\n";
print_non_twin_prime_sums(twin_prime_sums);
}
| package main
import (
"fmt"
"rcu"
)
const limit = 100000
func nonTwinSums(twins []int) []int {
sieve := make([]bool, limit+1)
for i := 0; i < len(twins); i++ {
for j := i; j < len(twins); j++ {
sum := twins[i] + twins[j]
if sum > limit {
break
}
sieve[sum] = true
}
}
var res []int
for i := 2; i < limit; i += 2 {
if !sieve[i] {
res = append(res, i)
}
}
return res
}
func main() {
primes := rcu.Primes(limit)[2:]
twins := []int{3}
for i := 0; i < len(primes)-1; i++ {
if primes[i+1]-primes[i] == 2 {
if twins[len(twins)-1] != primes[i] {
twins = append(twins, primes[i])
}
twins = append(twins, primes[i+1])
}
}
fmt.Println("Non twin prime sums:")
ntps := nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
fmt.Println("\nNon twin prime sums (including 1):")
twins = append([]int{1}, twins...)
ntps = nonTwinSums(twins)
rcu.PrintTable(ntps, 10, 4, false)
fmt.Println("Found", len(ntps))
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << "]";
}
std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
auto size = g.size();
std::vector<bool> vis(size);
std::vector<int> l(size);
auto x = size;
std::vector<std::vector<int>> t(size);
std::function<void(int)> visit;
visit = [&](int u) {
if (!vis[u]) {
vis[u] = true;
for (auto v : g[u]) {
visit(v);
t[v].push_back(u);
}
l[--x] = u;
}
};
for (int i = 0; i < g.size(); ++i) {
visit(i);
}
std::vector<int> c(size);
std::function<void(int, int)> assign;
assign = [&](int u, int root) {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (auto v : t[u]) {
assign(v, root);
}
}
};
for (auto u : l) {
assign(u, u);
}
return c;
}
std::vector<std::vector<int>> g = {
{1},
{2},
{0},
{1, 2, 4},
{3, 5},
{2, 6},
{5},
{4, 6, 7},
};
int main() {
using namespace std;
cout << kosaraju(g) << endl;
return 0;
}
| package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
vis := make([]bool, len(g))
L := make([]int, len(g))
x := len(L)
t := make([][]int, len(g))
var Visit func(int)
Visit = func(u int) {
if !vis[u] {
vis[u] = true
for _, v := range g[u] {
Visit(v)
t[v] = append(t[v], u)
}
x--
L[x] = u
}
}
for u := range g {
Visit(u)
}
c := make([]int, len(g))
var Assign func(int, int)
Assign = func(u, root int) {
if vis[u] {
vis[u] = false
c[u] = root
for _, v := range t[u] {
Assign(v, root)
}
}
}
for _, u := range L {
Assign(u, u)
}
return c
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <cmath>
#include <iostream>
#include <string>
using namespace std;
struct LoggingMonad
{
double Value;
string Log;
};
auto operator>>(const LoggingMonad& monad, auto f)
{
auto result = f(monad.Value);
return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}
auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };
auto MakeWriter = [](auto f, string message)
{
return [=](double x){return LoggingMonad(f(x), message);};
};
auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");
int main()
{
auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
cout << result.Log << "\nResult: " << result.Value;
}
| package main
import (
"fmt"
"math"
)
type mwriter struct {
value float64
log string
}
func (m mwriter) bind(f func(v float64) mwriter) mwriter {
n := f(m.value)
n.log = m.log + n.log
return n
}
func unit(v float64, s string) mwriter {
return mwriter{v, fmt.Sprintf(" %-17s: %g\n", s, v)}
}
func root(v float64) mwriter {
return unit(math.Sqrt(v), "Took square root")
}
func addOne(v float64) mwriter {
return unit(v+1, "Added one")
}
func half(v float64) mwriter {
return unit(v/2, "Divided by two")
}
func main() {
mw1 := unit(5, "Initial value")
mw2 := mw1.bind(root).bind(addOne).bind(half)
fmt.Println("The Golden Ratio is", mw2.value)
fmt.Println("\nThis was derived as follows:-")
fmt.Println(mw2.log)
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
if(index < 0 || index >= (int)size(payloads)) cout << "null";
else cout << "'" << payloads[index] << "'";
if (!isLast) cout << ", ";
}
template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
std::apply
(
[&payloads, isLast](Ts const&... tupleArgs)
{
size_t n{0};
cout << "[";
(PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
cout << "]";
cout << (isLast ? "\n" : ",\n");
}, nestedTuple
);
}
void FindUniqueIndexes(set<int> &indexes, int index)
{
indexes.insert(index);
}
template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
std::apply
(
[&indexes](Ts const&... tupleArgs)
{
(FindUniqueIndexes(indexes, tupleArgs),...);
}, nestedTuple
);
}
template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
for(size_t i = 0; i < size(payloads); i++)
{
if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
}
}
int main()
{
vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"};
auto tpl = make_tuple(make_tuple(
make_tuple(1, 2),
make_tuple(3, 4, 1),
5));
cout << "Mapping indexes to payloads:\n";
PrintPayloads(payloads, tpl);
cout << "\nFinding unused payloads:\n";
set<int> usedIndexes;
FindUniqueIndexes(usedIndexes, tpl);
PrintUnusedPayloads(usedIndexes, payloads);
cout << "\nMapping to some out of range payloads:\n";
PrintPayloads(shortPayloads, tpl);
return 0;
}
| package main
import (
"fmt"
"os"
"sort"
"strings"
"text/template"
)
func main() {
const t = `[[[{{index .P 1}}, {{index .P 2}}],
[{{index .P 3}}, {{index .P 4}}, {{index .P 1}}],
{{index .P 5}}]]
`
type S struct {
P map[int]string
}
var s S
s.P = map[int]string{
0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'",
4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'",
}
tmpl := template.Must(template.New("").Parse(t))
tmpl.Execute(os.Stdout, s)
var unused []int
for k, _ := range s.P {
if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) {
unused = append(unused, k)
}
}
sort.Ints(unused)
fmt.Println("\nThe unused payloads have indices of :", unused)
}
|
Change the following C++ code into Go without altering its purpose. | #include <iostream>
#include <vector>
class Outer
{
int m_privateField;
public:
Outer(int value) : m_privateField{value}{}
class Inner
{
int m_innerValue;
public:
Inner(int innerValue) : m_innerValue{innerValue}{}
int AddOuter(Outer outer) const
{
return outer.m_privateField + m_innerValue;
}
};
};
int main()
{
Outer::Inner inner{42};
Outer outer{1};
auto sum = inner.AddOuter(outer);
std::cout << "sum: " << sum << "\n";
std::vector<int> vec{1,2,3};
std::vector<int>::iterator itr = vec.begin();
std::cout << "vec[0] = " << *itr << "\n";
}
| package main
import "fmt"
type Outer struct {
field int
Inner struct {
field int
}
}
func (o *Outer) outerMethod() {
fmt.Println("Outer's field has a value of", o.field)
}
func (o *Outer) innerMethod() {
fmt.Println("Inner's field has a value of", o.Inner.field)
}
func main() {
o := &Outer{field: 43}
o.Inner.field = 42
o.innerMethod()
o.outerMethod()
p := &Outer{
field: 45,
Inner: struct {
field int
}{
field: 44,
},
}
p.innerMethod()
p.outerMethod()
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <cmath>
#include <concepts>
#include <iostream>
#include <numeric>
#include <optional>
#include <tuple>
using namespace std;
optional<tuple<int, int ,int>> FindPerimeterTriplet(int perimeter)
{
unsigned long long perimeterULL = perimeter;
auto max_M = (unsigned long long)sqrt(perimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto primitive = a + b + c;
auto factor = perimeterULL / primitive;
if(primitive * factor == perimeterULL)
{
if(b<a) swap(a, b);
return tuple{a * factor, b * factor, c * factor};
}
}
}
return nullopt;
}
int main()
{
auto t1 = FindPerimeterTriplet(1000);
if(t1)
{
auto [a, b, c] = *t1;
cout << "[" << a << ", " << b << ", " << c << "]\n";
cout << "a * b * c = " << a * b * c << "\n";
}
else
{
cout << "Perimeter not found\n";
}
}
| package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
for a := 3; ; a++ {
for b := a + 1; ; b++ {
c := 1000 - a - b
if c <= b {
break
}
if a*a+b*b == c*c {
fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
fmt.Println("a + b + c =", a+b+c)
fmt.Println("a * b * c =", a*b*c)
fmt.Println("\nTook", time.Since(start))
return
}
}
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <iostream>
#include <algorithm>
#include <ctime>
#include <string>
#include <vector>
typedef std::vector<char> vecChar;
class master {
public:
master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {
std::string color = "ABCDEFGHIJKLMNOPQRST";
if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;
if( !rpt && clr_count < code_len ) clr_count = code_len;
if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;
if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;
codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;
for( size_t s = 0; s < colorsCnt; s++ ) {
colors.append( 1, color.at( s ) );
}
}
void play() {
bool win = false;
combo = getCombo();
while( guessCnt ) {
showBoard();
if( checkInput( getInput() ) ) {
win = true;
break;
}
guessCnt--;
}
if( win ) {
std::cout << "\n\n--------------------------------\n" <<
"Very well done!\nYou found the code: " << combo <<
"\n--------------------------------\n\n";
} else {
std::cout << "\n\n--------------------------------\n" <<
"I am sorry, you couldn't make it!\nThe code was: " << combo <<
"\n--------------------------------\n\n";
}
}
private:
void showBoard() {
vecChar::iterator y;
for( int x = 0; x < guesses.size(); x++ ) {
std::cout << "\n--------------------------------\n";
std::cout << x + 1 << ": ";
for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {
std::cout << *y << " ";
}
std::cout << " : ";
for( y = results[x].begin(); y != results[x].end(); y++ ) {
std::cout << *y << " ";
}
int z = codeLen - results[x].size();
if( z > 0 ) {
for( int x = 0; x < z; x++ ) std::cout << "- ";
}
}
std::cout << "\n\n";
}
std::string getInput() {
std::string a;
while( true ) {
std::cout << "Enter your guess (" << colors << "): ";
a = ""; std::cin >> a;
std::transform( a.begin(), a.end(), a.begin(), ::toupper );
if( a.length() > codeLen ) a.erase( codeLen );
bool r = true;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
if( colors.find( *x ) == std::string::npos ) {
r = false;
break;
}
}
if( r ) break;
}
return a;
}
bool checkInput( std::string a ) {
vecChar g;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
g.push_back( *x );
}
guesses.push_back( g );
int black = 0, white = 0;
std::vector<bool> gmatch( codeLen, false );
std::vector<bool> cmatch( codeLen, false );
for( int i = 0; i < codeLen; i++ ) {
if( a.at( i ) == combo.at( i ) ) {
gmatch[i] = true;
cmatch[i] = true;
black++;
}
}
for( int i = 0; i < codeLen; i++ ) {
if (gmatch[i]) continue;
for( int j = 0; j < codeLen; j++ ) {
if (i == j || cmatch[j]) continue;
if( a.at( i ) == combo.at( j ) ) {
cmatch[j] = true;
white++;
break;
}
}
}
vecChar r;
for( int b = 0; b < black; b++ ) r.push_back( 'X' );
for( int w = 0; w < white; w++ ) r.push_back( 'O' );
results.push_back( r );
return ( black == codeLen );
}
std::string getCombo() {
std::string c, clr = colors;
int l, z;
for( size_t s = 0; s < codeLen; s++ ) {
z = rand() % ( int )clr.length();
c.append( 1, clr[z] );
if( !repeatClr ) clr.erase( z, 1 );
}
return c;
}
size_t codeLen, colorsCnt, guessCnt;
bool repeatClr;
std::vector<vecChar> guesses, results;
std::string colors, combo;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
master m( 4, 8, 12, false );
m.play();
return 0;
}
| package main
import (
"errors"
"flag"
"fmt"
"log"
"math/rand"
"strings"
"time"
)
func main() {
log.SetPrefix("mastermind: ")
log.SetFlags(0)
colours := flag.Int("colours", 6, "number of colours to use (2-20)")
flag.IntVar(colours, "colors", 6, "alias for colours")
holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)")
guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)")
unique := flag.Bool("unique", false, "disallow duplicate colours in the code")
flag.Parse()
rand.Seed(time.Now().UnixNano())
m, err := NewMastermind(*colours, *holes, *guesses, *unique)
if err != nil {
log.Fatal(err)
}
err = m.Play()
if err != nil {
log.Fatal(err)
}
}
type mastermind struct {
colours int
holes int
guesses int
unique bool
code string
past []string
scores []string
}
func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {
if colours < 2 || colours > 20 {
return nil, errors.New("colours must be between 2 and 20 inclusive")
}
if holes < 4 || holes > 10 {
return nil, errors.New("holes must be between 4 and 10 inclusive")
}
if guesses < 7 || guesses > 20 {
return nil, errors.New("guesses must be between 7 and 20 inclusive")
}
if unique && holes > colours {
return nil, errors.New("holes must be > colours when using unique")
}
return &mastermind{
colours: colours,
holes: holes,
guesses: guesses,
unique: unique,
past: make([]string, 0, guesses),
scores: make([]string, 0, guesses),
}, nil
}
func (m *mastermind) Play() error {
m.generateCode()
fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique))
fmt.Printf("You have %d guesses.\n", m.guesses)
for len(m.past) < m.guesses {
guess, err := m.inputGuess()
if err != nil {
return err
}
fmt.Println()
m.past = append(m.past, guess)
str, won := m.scoreString(m.score(guess))
if won {
plural := "es"
if len(m.past) == 1 {
plural = ""
}
fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural)
return nil
}
m.scores = append(m.scores, str)
m.printHistory()
fmt.Println()
}
fmt.Printf("You are out of guesses. The code was %s.\n", m.code)
return nil
}
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const blacks = "XXXXXXXXXX"
const whites = "OOOOOOOOOO"
const nones = "----------"
func (m *mastermind) describeCode(unique bool) string {
ustr := ""
if unique {
ustr = " unique"
}
return fmt.Sprintf("%d%s letters (from 'A' to %q)",
m.holes, ustr, charset[m.colours-1],
)
}
func (m *mastermind) printHistory() {
for i, g := range m.past {
fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes])
fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i])
}
}
func (m *mastermind) generateCode() {
code := make([]byte, m.holes)
if m.unique {
p := rand.Perm(m.colours)
for i := range code {
code[i] = charset[p[i]]
}
} else {
for i := range code {
code[i] = charset[rand.Intn(m.colours)]
}
}
m.code = string(code)
}
func (m *mastermind) inputGuess() (string, error) {
var input string
for {
fmt.Printf("Enter guess #%d: ", len(m.past)+1)
if _, err := fmt.Scanln(&input); err != nil {
return "", err
}
input = strings.ToUpper(strings.TrimSpace(input))
if m.validGuess(input) {
return input, nil
}
fmt.Printf("A guess must consist of %s.\n", m.describeCode(false))
}
}
func (m *mastermind) validGuess(input string) bool {
if len(input) != m.holes {
return false
}
for i := 0; i < len(input); i++ {
c := input[i]
if c < 'A' || c > charset[m.colours-1] {
return false
}
}
return true
}
func (m *mastermind) score(guess string) (black, white int) {
scored := make([]bool, m.holes)
for i := 0; i < len(guess); i++ {
if guess[i] == m.code[i] {
black++
scored[i] = true
}
}
for i := 0; i < len(guess); i++ {
if guess[i] == m.code[i] {
continue
}
for j := 0; j < len(m.code); j++ {
if i != j && !scored[j] && guess[i] == m.code[j] {
white++
scored[j] = true
}
}
}
return
}
func (m *mastermind) scoreString(black, white int) (string, bool) {
none := m.holes - black - white
return blacks[:black] + whites[:white] + nones[:none], black == m.holes
}
|
Produce a functionally identical Go code for the snippet given in C++. | #include <iostream>
#include <algorithm>
#include <ctime>
#include <string>
#include <vector>
typedef std::vector<char> vecChar;
class master {
public:
master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {
std::string color = "ABCDEFGHIJKLMNOPQRST";
if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;
if( !rpt && clr_count < code_len ) clr_count = code_len;
if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;
if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;
codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;
for( size_t s = 0; s < colorsCnt; s++ ) {
colors.append( 1, color.at( s ) );
}
}
void play() {
bool win = false;
combo = getCombo();
while( guessCnt ) {
showBoard();
if( checkInput( getInput() ) ) {
win = true;
break;
}
guessCnt--;
}
if( win ) {
std::cout << "\n\n--------------------------------\n" <<
"Very well done!\nYou found the code: " << combo <<
"\n--------------------------------\n\n";
} else {
std::cout << "\n\n--------------------------------\n" <<
"I am sorry, you couldn't make it!\nThe code was: " << combo <<
"\n--------------------------------\n\n";
}
}
private:
void showBoard() {
vecChar::iterator y;
for( int x = 0; x < guesses.size(); x++ ) {
std::cout << "\n--------------------------------\n";
std::cout << x + 1 << ": ";
for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {
std::cout << *y << " ";
}
std::cout << " : ";
for( y = results[x].begin(); y != results[x].end(); y++ ) {
std::cout << *y << " ";
}
int z = codeLen - results[x].size();
if( z > 0 ) {
for( int x = 0; x < z; x++ ) std::cout << "- ";
}
}
std::cout << "\n\n";
}
std::string getInput() {
std::string a;
while( true ) {
std::cout << "Enter your guess (" << colors << "): ";
a = ""; std::cin >> a;
std::transform( a.begin(), a.end(), a.begin(), ::toupper );
if( a.length() > codeLen ) a.erase( codeLen );
bool r = true;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
if( colors.find( *x ) == std::string::npos ) {
r = false;
break;
}
}
if( r ) break;
}
return a;
}
bool checkInput( std::string a ) {
vecChar g;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
g.push_back( *x );
}
guesses.push_back( g );
int black = 0, white = 0;
std::vector<bool> gmatch( codeLen, false );
std::vector<bool> cmatch( codeLen, false );
for( int i = 0; i < codeLen; i++ ) {
if( a.at( i ) == combo.at( i ) ) {
gmatch[i] = true;
cmatch[i] = true;
black++;
}
}
for( int i = 0; i < codeLen; i++ ) {
if (gmatch[i]) continue;
for( int j = 0; j < codeLen; j++ ) {
if (i == j || cmatch[j]) continue;
if( a.at( i ) == combo.at( j ) ) {
cmatch[j] = true;
white++;
break;
}
}
}
vecChar r;
for( int b = 0; b < black; b++ ) r.push_back( 'X' );
for( int w = 0; w < white; w++ ) r.push_back( 'O' );
results.push_back( r );
return ( black == codeLen );
}
std::string getCombo() {
std::string c, clr = colors;
int l, z;
for( size_t s = 0; s < codeLen; s++ ) {
z = rand() % ( int )clr.length();
c.append( 1, clr[z] );
if( !repeatClr ) clr.erase( z, 1 );
}
return c;
}
size_t codeLen, colorsCnt, guessCnt;
bool repeatClr;
std::vector<vecChar> guesses, results;
std::string colors, combo;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
master m( 4, 8, 12, false );
m.play();
return 0;
}
| package main
import (
"errors"
"flag"
"fmt"
"log"
"math/rand"
"strings"
"time"
)
func main() {
log.SetPrefix("mastermind: ")
log.SetFlags(0)
colours := flag.Int("colours", 6, "number of colours to use (2-20)")
flag.IntVar(colours, "colors", 6, "alias for colours")
holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)")
guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)")
unique := flag.Bool("unique", false, "disallow duplicate colours in the code")
flag.Parse()
rand.Seed(time.Now().UnixNano())
m, err := NewMastermind(*colours, *holes, *guesses, *unique)
if err != nil {
log.Fatal(err)
}
err = m.Play()
if err != nil {
log.Fatal(err)
}
}
type mastermind struct {
colours int
holes int
guesses int
unique bool
code string
past []string
scores []string
}
func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) {
if colours < 2 || colours > 20 {
return nil, errors.New("colours must be between 2 and 20 inclusive")
}
if holes < 4 || holes > 10 {
return nil, errors.New("holes must be between 4 and 10 inclusive")
}
if guesses < 7 || guesses > 20 {
return nil, errors.New("guesses must be between 7 and 20 inclusive")
}
if unique && holes > colours {
return nil, errors.New("holes must be > colours when using unique")
}
return &mastermind{
colours: colours,
holes: holes,
guesses: guesses,
unique: unique,
past: make([]string, 0, guesses),
scores: make([]string, 0, guesses),
}, nil
}
func (m *mastermind) Play() error {
m.generateCode()
fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique))
fmt.Printf("You have %d guesses.\n", m.guesses)
for len(m.past) < m.guesses {
guess, err := m.inputGuess()
if err != nil {
return err
}
fmt.Println()
m.past = append(m.past, guess)
str, won := m.scoreString(m.score(guess))
if won {
plural := "es"
if len(m.past) == 1 {
plural = ""
}
fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural)
return nil
}
m.scores = append(m.scores, str)
m.printHistory()
fmt.Println()
}
fmt.Printf("You are out of guesses. The code was %s.\n", m.code)
return nil
}
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const blacks = "XXXXXXXXXX"
const whites = "OOOOOOOOOO"
const nones = "----------"
func (m *mastermind) describeCode(unique bool) string {
ustr := ""
if unique {
ustr = " unique"
}
return fmt.Sprintf("%d%s letters (from 'A' to %q)",
m.holes, ustr, charset[m.colours-1],
)
}
func (m *mastermind) printHistory() {
for i, g := range m.past {
fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes])
fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i])
}
}
func (m *mastermind) generateCode() {
code := make([]byte, m.holes)
if m.unique {
p := rand.Perm(m.colours)
for i := range code {
code[i] = charset[p[i]]
}
} else {
for i := range code {
code[i] = charset[rand.Intn(m.colours)]
}
}
m.code = string(code)
}
func (m *mastermind) inputGuess() (string, error) {
var input string
for {
fmt.Printf("Enter guess #%d: ", len(m.past)+1)
if _, err := fmt.Scanln(&input); err != nil {
return "", err
}
input = strings.ToUpper(strings.TrimSpace(input))
if m.validGuess(input) {
return input, nil
}
fmt.Printf("A guess must consist of %s.\n", m.describeCode(false))
}
}
func (m *mastermind) validGuess(input string) bool {
if len(input) != m.holes {
return false
}
for i := 0; i < len(input); i++ {
c := input[i]
if c < 'A' || c > charset[m.colours-1] {
return false
}
}
return true
}
func (m *mastermind) score(guess string) (black, white int) {
scored := make([]bool, m.holes)
for i := 0; i < len(guess); i++ {
if guess[i] == m.code[i] {
black++
scored[i] = true
}
}
for i := 0; i < len(guess); i++ {
if guess[i] == m.code[i] {
continue
}
for j := 0; j < len(m.code); j++ {
if i != j && !scored[j] && guess[i] == m.code[j] {
white++
scored[j] = true
}
}
}
return
}
func (m *mastermind) scoreString(black, white int) (string, bool) {
none := m.holes - black - white
return blacks[:black] + whites[:white] + nones[:none], black == m.holes
}
|
Translate the given C++ code snippet into Go without altering its behavior. |
#include <functional>
#include <bitset>
#include <iostream>
#include <cmath>
using namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>;
const int maxUT{3000000}, dL{(int)log2(maxUT)};
struct uT{
bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{};
void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}}
Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);}
Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};}
Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};}
void fL(Z3 n, int g){for(;;){
if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;}
if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}
if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}
if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;}
}
int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;}
uT(const int n):mUT{n}{
N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size();
N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0);
}
};
| package main
import "fmt"
func sumDivisors(n int) int {
sum := 1
k := 2
if n%2 == 0 {
k = 1
}
for i := 1 + k; i*i <= n; i += k {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
}
return sum
}
func sieve(n int) []bool {
n++
s := make([]bool, n+1)
for i := 6; i <= n; i++ {
sd := sumDivisors(i)
if sd <= n {
s[sd] = true
}
}
return s
}
func primeSieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := 1000000
c := primeSieve(limit)
s := sieve(63 * limit)
untouchable := []int{2, 5}
for n := 6; n <= limit; n += 2 {
if !s[n] && c[n-1] && c[n-3] {
untouchable = append(untouchable, n)
}
}
fmt.Println("List of untouchable numbers <= 2,000:")
count := 0
for i := 0; untouchable[i] <= 2000; i++ {
fmt.Printf("%6s", commatize(untouchable[i]))
if (i+1)%10 == 0 {
fmt.Println()
}
count++
}
fmt.Printf("\n\n%7s untouchable numbers were found <= 2,000\n", commatize(count))
p := 10
count = 0
for _, n := range untouchable {
count++
if n > p {
cc := commatize(count - 1)
cp := commatize(p)
fmt.Printf("%7s untouchable numbers were found <= %9s\n", cc, cp)
p = p * 10
if p == limit {
break
}
}
}
cu := commatize(len(untouchable))
cl := commatize(limit)
fmt.Printf("%7s untouchable numbers were found <= %s\n", cu, cl)
}
|
Generate an equivalent Go version of this C++ code. |
#include <functional>
#include <bitset>
#include <iostream>
#include <cmath>
using namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>;
const int maxUT{3000000}, dL{(int)log2(maxUT)};
struct uT{
bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{};
void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}}
Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);}
Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};}
Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};}
void fL(Z3 n, int g){for(;;){
if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;}
if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}
if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;}
if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;}
}
int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;}
uT(const int n):mUT{n}{
N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size();
N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0);
}
};
| package main
import "fmt"
func sumDivisors(n int) int {
sum := 1
k := 2
if n%2 == 0 {
k = 1
}
for i := 1 + k; i*i <= n; i += k {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
}
return sum
}
func sieve(n int) []bool {
n++
s := make([]bool, n+1)
for i := 6; i <= n; i++ {
sd := sumDivisors(i)
if sd <= n {
s[sd] = true
}
}
return s
}
func primeSieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := 1000000
c := primeSieve(limit)
s := sieve(63 * limit)
untouchable := []int{2, 5}
for n := 6; n <= limit; n += 2 {
if !s[n] && c[n-1] && c[n-3] {
untouchable = append(untouchable, n)
}
}
fmt.Println("List of untouchable numbers <= 2,000:")
count := 0
for i := 0; untouchable[i] <= 2000; i++ {
fmt.Printf("%6s", commatize(untouchable[i]))
if (i+1)%10 == 0 {
fmt.Println()
}
count++
}
fmt.Printf("\n\n%7s untouchable numbers were found <= 2,000\n", commatize(count))
p := 10
count = 0
for _, n := range untouchable {
count++
if n > p {
cc := commatize(count - 1)
cp := commatize(p)
fmt.Printf("%7s untouchable numbers were found <= %9s\n", cc, cp)
p = p * 10
if p == limit {
break
}
}
}
cu := commatize(len(untouchable))
cl := commatize(limit)
fmt.Printf("%7s untouchable numbers were found <= %s\n", cu, cl)
}
|
Write the same code in Go as shown below in PHP. | #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
| package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
if cErr := f.Close(); err == nil {
err = cErr
}
return err
}
func showNotes(w io.Writer, fn string) error {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
_, err = io.Copy(w, f)
f.Close()
return err
}
func main() {
const fn = "NOTES.TXT"
var err error
if len(os.Args) > 1 {
err = addNote(fn, strings.Join(os.Args[1:], " "))
} else {
err = showNotes(os.Stdout, fn)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
|
Write the same algorithm in Go as shown in this PHP implementation. | #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
| package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
if cErr := f.Close(); err == nil {
err = cErr
}
return err
}
func showNotes(w io.Writer, fn string) error {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
_, err = io.Copy(w, f)
f.Close()
return err
}
func main() {
const fn = "NOTES.TXT"
var err error
if len(os.Args) > 1 {
err = addNote(fn, strings.Join(os.Args[1:], " "))
} else {
err = showNotes(os.Stdout, fn)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
|
Translate the given PHP code snippet into Go without altering its behavior. | <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
| package main
import (
"fmt"
"os"
"path"
)
func CommonPrefix(sep byte, paths ...string) string {
switch len(paths) {
case 0:
return ""
case 1:
return path.Clean(paths[0])
}
c := []byte(path.Clean(paths[0]))
c = append(c, sep)
for _, v := range paths[1:] {
v = path.Clean(v) + string(sep)
if len(v) < len(c) {
c = c[:len(v)]
}
for i := 0; i < len(c); i++ {
if v[i] != c[i] {
c = c[:i]
break
}
}
}
for i := len(c) - 1; i >= 0; i-- {
if c[i] == sep {
c = c[:i]
break
}
}
return string(c)
}
func main() {
c := CommonPrefix(os.PathSeparator,
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members",
"/home
"/home/user1/././tmp/covertly/foo",
"/home/bob/../user1/tmp/coved/bar",
)
if c == "" {
fmt.Println("No common path")
} else {
fmt.Println("Common path:", c)
}
}
|
Ensure the translated Go code behaves exactly like the original PHP snippet. | <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
| package main
import (
"fmt"
"os"
"path"
)
func CommonPrefix(sep byte, paths ...string) string {
switch len(paths) {
case 0:
return ""
case 1:
return path.Clean(paths[0])
}
c := []byte(path.Clean(paths[0]))
c = append(c, sep)
for _, v := range paths[1:] {
v = path.Clean(v) + string(sep)
if len(v) < len(c) {
c = c[:len(v)]
}
for i := 0; i < len(c); i++ {
if v[i] != c[i] {
c = c[:i]
break
}
}
}
for i := len(c) - 1; i >= 0; i-- {
if c[i] == sep {
c = c[:i]
break
}
}
return string(c)
}
func main() {
c := CommonPrefix(os.PathSeparator,
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members",
"/home
"/home/user1/././tmp/covertly/foo",
"/home/bob/../user1/tmp/coved/bar",
)
if c == "" {
fmt.Println("No common path")
} else {
fmt.Println("Common path:", c)
}
}
|
Write the same code in Go as shown below in PHP. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
|
Port the provided PHP code into Go while preserving the original functionality. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
|
Change the programming language of this snippet from PHP to Go without modifying what it does. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
|
Please provide an equivalent version of this PHP code in Go. | <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
| package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
|
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically? | <?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\.]{9}/i'; //Cat's game
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border="1">';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied
else { //Available
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type="hidden" name="b" value="', $boardStr, '"/>';
}
echo '</table>';
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
| package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
)
var b []byte
func printBoard() {
fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9])
}
var pScore, cScore int
var pMark, cMark byte = 'X', 'O'
var in = bufio.NewReader(os.Stdin)
func main() {
b = make([]byte, 9)
fmt.Println("Play by entering a digit.")
for {
for i := range b {
b[i] = '1' + byte(i)
}
computerStart := cMark == 'X'
if computerStart {
fmt.Println("I go first, playing X's")
} else {
fmt.Println("You go first, playing X's")
}
TakeTurns:
for {
if !computerStart {
if !playerTurn() {
return
}
if gameOver() {
break TakeTurns
}
}
computerStart = false
computerTurn()
if gameOver() {
break TakeTurns
}
}
fmt.Println("Score: you", pScore, "me", cScore)
fmt.Println("\nLet's play again.")
}
}
func playerTurn() bool {
var pm string
var err error
for i := 0; i < 3; i++ {
printBoard()
fmt.Printf("%c's move? ", pMark)
if pm, err = in.ReadString('\n'); err != nil {
fmt.Println(err)
return false
}
pm = strings.TrimSpace(pm)
if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] {
x := pm[0] - '1'
b[x] = pMark
return true
}
}
fmt.Println("You're not playing right.")
return false
}
var choices = make([]int, 9)
func computerTurn() {
printBoard()
var x int
defer func() {
fmt.Println("My move:", x+1)
b[x] = cMark
}()
block := -1
for _, l := range lines {
var mine, yours int
x = -1
for _, sq := range l {
switch b[sq] {
case cMark:
mine++
case pMark:
yours++
default:
x = sq
}
}
if mine == 2 && x >= 0 {
return
}
if yours == 2 && x >= 0 {
block = x
}
}
if block >= 0 {
x = block
return
}
choices = choices[:0]
for i, sq := range b {
if sq == '1'+byte(i) {
choices = append(choices, i)
}
}
x = choices[rand.Intn(len(choices))]
}
func gameOver() bool {
for _, l := range lines {
if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {
printBoard()
if b[l[0]] == cMark {
fmt.Println("I win!")
cScore++
pMark, cMark = 'X', 'O'
} else {
fmt.Println("You win!")
pScore++
pMark, cMark = 'O', 'X'
}
return true
}
}
for i, sq := range b {
if sq == '1'+byte(i) {
return false
}
}
fmt.Println("Cat game.")
pMark, cMark = cMark, pMark
return true
}
var lines = [][]int{
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{2, 4, 6},
}
|
Generate an equivalent Go version of this PHP code. | <?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\.]{9}/i'; //Cat's game
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border="1">';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied
else { //Available
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type="hidden" name="b" value="', $boardStr, '"/>';
}
echo '</table>';
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
| package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
)
var b []byte
func printBoard() {
fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9])
}
var pScore, cScore int
var pMark, cMark byte = 'X', 'O'
var in = bufio.NewReader(os.Stdin)
func main() {
b = make([]byte, 9)
fmt.Println("Play by entering a digit.")
for {
for i := range b {
b[i] = '1' + byte(i)
}
computerStart := cMark == 'X'
if computerStart {
fmt.Println("I go first, playing X's")
} else {
fmt.Println("You go first, playing X's")
}
TakeTurns:
for {
if !computerStart {
if !playerTurn() {
return
}
if gameOver() {
break TakeTurns
}
}
computerStart = false
computerTurn()
if gameOver() {
break TakeTurns
}
}
fmt.Println("Score: you", pScore, "me", cScore)
fmt.Println("\nLet's play again.")
}
}
func playerTurn() bool {
var pm string
var err error
for i := 0; i < 3; i++ {
printBoard()
fmt.Printf("%c's move? ", pMark)
if pm, err = in.ReadString('\n'); err != nil {
fmt.Println(err)
return false
}
pm = strings.TrimSpace(pm)
if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] {
x := pm[0] - '1'
b[x] = pMark
return true
}
}
fmt.Println("You're not playing right.")
return false
}
var choices = make([]int, 9)
func computerTurn() {
printBoard()
var x int
defer func() {
fmt.Println("My move:", x+1)
b[x] = cMark
}()
block := -1
for _, l := range lines {
var mine, yours int
x = -1
for _, sq := range l {
switch b[sq] {
case cMark:
mine++
case pMark:
yours++
default:
x = sq
}
}
if mine == 2 && x >= 0 {
return
}
if yours == 2 && x >= 0 {
block = x
}
}
if block >= 0 {
x = block
return
}
choices = choices[:0]
for i, sq := range b {
if sq == '1'+byte(i) {
choices = append(choices, i)
}
}
x = choices[rand.Intn(len(choices))]
}
func gameOver() bool {
for _, l := range lines {
if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {
printBoard()
if b[l[0]] == cMark {
fmt.Println("I win!")
cScore++
pMark, cMark = 'X', 'O'
} else {
fmt.Println("You win!")
pScore++
pMark, cMark = 'O', 'X'
}
return true
}
}
for i, sq := range b {
if sq == '1'+byte(i) {
return false
}
}
fmt.Println("Cat game.")
pMark, cMark = cMark, pMark
return true
}
var lines = [][]int{
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{2, 4, 6},
}
|
Preserve the algorithm and functionality while converting the code from PHP to Go. | <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
| package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
|
Write the same algorithm in Go as shown in this PHP implementation. | <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
| package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
|
Preserve the algorithm and functionality while converting the code from PHP to Go. | <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
| package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
|
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically? | <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
| package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
|
Produce a language-to-language conversion: from PHP to Go, same semantics. | <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
| package main
import (
"fmt"
"net"
)
func main() {
if addrs, err := net.LookupHost("www.kame.net"); err == nil {
fmt.Println(addrs)
} else {
fmt.Println(err)
}
}
|
Convert this PHP snippet to Go and keep its semantics consistent. | <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
| package main
import (
"fmt"
"net"
)
func main() {
if addrs, err := net.LookupHost("www.kame.net"); err == nil {
fmt.Println(addrs)
} else {
fmt.Println(err)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | <?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";
$player = strtoupper( $_GET["moves"] );
$wins = [
'ROCK' => 'SCISSORS',
'PAPER' => 'ROCK',
'SCISSORS' => 'PAPER'
];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>";
echo "<br>";
echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>";
$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
$results = "A.I wins";
} else {
$results = "Player wins";
}
echo "<br>" . $results;
?>
| package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
|
Keep all operations the same but rewrite the snippet in Go. | <?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";
$player = strtoupper( $_GET["moves"] );
$wins = [
'ROCK' => 'SCISSORS',
'PAPER' => 'ROCK',
'SCISSORS' => 'PAPER'
];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>";
echo "<br>";
echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>";
$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
$results = "A.I wins";
} else {
$results = "Player wins";
}
echo "<br>" . $results;
?>
| package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
|
Ensure the translated Go code behaves exactly like the original PHP snippet. | <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "\n";
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), "\n";
?>
| package main
import "fmt"
type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func
func main() {
fac := Y(almost_fac)
fib := Y(almost_fib)
fmt.Println("fac(10) = ", fac(10))
fmt.Println("fib(10) = ", fib(10))
}
func Y(f FuncFunc) Func {
g := func(r RecursiveFunc) Func {
return f(func(x int) int {
return r(r)(x)
})
}
return g(g)
}
func almost_fac(f Func) Func {
return func(x int) int {
if x <= 1 {
return 1
}
return x * f(x-1)
}
}
func almost_fib(f Func) Func {
return func(x int) int {
if x <= 2 {
return 1
}
return f(x-1)+f(x-2)
}
}
|
Translate this program into Go but keep the logic exactly as in PHP. | <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "\n";
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), "\n";
?>
| package main
import "fmt"
type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func
func main() {
fac := Y(almost_fac)
fib := Y(almost_fib)
fmt.Println("fac(10) = ", fac(10))
fmt.Println("fib(10) = ", fib(10))
}
func Y(f FuncFunc) Func {
g := func(r RecursiveFunc) Func {
return f(func(x int) int {
return r(r)(x)
})
}
return g(g)
}
func almost_fac(f Func) Func {
return func(x int) int {
if x <= 1 {
return 1
}
return x * f(x-1)
}
}
func almost_fib(f Func) Func {
return func(x int) int {
if x <= 2 {
return 1
}
return f(x-1)+f(x-2)
}
}
|
Keep all operations the same but rewrite the snippet in Go. | function addsub($x, $y) {
return array($x + $y, $x - $y);
}
| func addsub(x, y int) (int, int) {
return x + y, x - y
}
|
Write a version of this PHP function in Go with identical behavior. | function addsub($x, $y) {
return array($x + $y, $x - $y);
}
| func addsub(x, y int) (int, int) {
return x + y, x - y
}
|
Please provide an equivalent version of this PHP code in Go. | $server = "speedtest.tele2.net";
$user = "anonymous";
$pass = "ftptest@example.com";
$conn = ftp_connect($server);
if (!$conn) {
die('unable to connect to: '. $server);
}
$login = ftp_login($conn, $user, $pass);
if (!$login) {
echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;
} else{
echo 'connected successfully'.PHP_EOL;
$directory = ftp_nlist($conn,'');
print_r($directory);
}
if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {
echo "Successfully downloaded file".PHP_EOL;
} else {
echo "failed to download file";
}
| package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Quit()
fmt.Println(conn)
if err = conn.Login(username, password); err != nil {
log.Fatal(err)
}
if err = conn.ChangeDir(dir); err != nil {
log.Fatal(err)
}
fmt.Println(conn.CurrentDir())
files, err := conn.List(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
}
r, err := conn.Retr(file)
if err != nil {
log.Fatal(err)
}
defer r.Close()
f, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
n, err := io.Copy(f, r)
if err != nil {
log.Fatal(err)
}
fmt.Println("Wrote", n, "bytes to", file)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | $server = "speedtest.tele2.net";
$user = "anonymous";
$pass = "ftptest@example.com";
$conn = ftp_connect($server);
if (!$conn) {
die('unable to connect to: '. $server);
}
$login = ftp_login($conn, $user, $pass);
if (!$login) {
echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;
} else{
echo 'connected successfully'.PHP_EOL;
$directory = ftp_nlist($conn,'');
print_r($directory);
}
if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {
echo "Successfully downloaded file".PHP_EOL;
} else {
echo "failed to download file";
}
| package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Quit()
fmt.Println(conn)
if err = conn.Login(username, password); err != nil {
log.Fatal(err)
}
if err = conn.ChangeDir(dir); err != nil {
log.Fatal(err)
}
fmt.Println(conn.CurrentDir())
files, err := conn.List(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
}
r, err := conn.Retr(file)
if err != nil {
log.Fatal(err)
}
defer r.Close()
f, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
n, err := io.Copy(f, r)
if err != nil {
log.Fatal(err)
}
fmt.Println("Wrote", n, "bytes to", file)
}
|
Port the provided PHP code into Go while preserving the original functionality. | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Transform the following PHP implementation into Go, maintaining the same output and logic. | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Change the following PHP code into Go without altering its purpose. | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Generate an equivalent Go version of this PHP code. | for ($i = 1; $i <= 10; $i++) {
echo $i;
if ($i % 5 == 0) {
echo "\n";
continue;
}
echo ', ';
}
| package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
}
|
Generate a Go translation of this PHP snippet without changing its computational steps. | for ($i = 1; $i <= 10; $i++) {
echo $i;
if ($i % 5 == 0) {
echo "\n";
continue;
}
echo ', ';
}
| package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
}
|
Produce a language-to-language conversion: from PHP to Go, same semantics. | <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(255, 255, 0), // yellow
array(255, 255, 255)); // white
define('BARWIDTH', 640 / count($colors));
define('HEIGHT', 480);
$image = imagecreate(BARWIDTH * count($colors), HEIGHT);
foreach ($colors as $position => $color) {
$color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagefilledrectangle($image, $position * BARWIDTH, 0,
$position * BARWIDTH + BARWIDTH - 1,
HEIGHT - 1, $color);
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Convert this PHP snippet to Go and keep its semantics consistent. | <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(255, 255, 0), // yellow
array(255, 255, 255)); // white
define('BARWIDTH', 640 / count($colors));
define('HEIGHT', 480);
$image = imagecreate(BARWIDTH * count($colors), HEIGHT);
foreach ($colors as $position => $color) {
$color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagefilledrectangle($image, $position * BARWIDTH, 0,
$position * BARWIDTH + BARWIDTH - 1,
HEIGHT - 1, $color);
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Generate a Go translation of this PHP snippet without changing its computational steps. | <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(255, 255, 0), // yellow
array(255, 255, 255)); // white
define('BARWIDTH', 640 / count($colors));
define('HEIGHT', 480);
$image = imagecreate(BARWIDTH * count($colors), HEIGHT);
foreach ($colors as $position => $color) {
$color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagefilledrectangle($image, $position * BARWIDTH, 0,
$position * BARWIDTH + BARWIDTH - 1,
HEIGHT - 1, $color);
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Change the following PHP code into Go without altering its purpose. | <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(255, 255, 0), // yellow
array(255, 255, 255)); // white
define('BARWIDTH', 640 / count($colors));
define('HEIGHT', 480);
$image = imagecreate(BARWIDTH * count($colors), HEIGHT);
foreach ($colors as $position => $color) {
$color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagefilledrectangle($image, $position * BARWIDTH, 0,
$position * BARWIDTH + BARWIDTH - 1,
HEIGHT - 1, $color);
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Change the programming language of this snippet from PHP to Go without modifying what it does. | <?php
$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
for ($i = 1 ; $i <= $max ; $i++) {
$matched = false;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
}
echo ($matched ? '' : $i), PHP_EOL;
}
?>
| package main
import (
"fmt"
)
const numbers = 3
func main() {
max := 20
words := map[int]string{
3: "Fizz",
5: "Buzz",
7: "Baxx",
}
keys := []int{3, 5, 7}
divisible := false
for i := 1; i <= max; i++ {
for _, n := range keys {
if i % n == 0 {
fmt.Print(words[n])
divisible = true
}
}
if !divisible {
fmt.Print(i)
}
fmt.Println()
divisible = false
}
}
|
Ensure the translated Go code behaves exactly like the original PHP snippet. | <?php
$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
for ($i = 1 ; $i <= $max ; $i++) {
$matched = false;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
}
echo ($matched ? '' : $i), PHP_EOL;
}
?>
| package main
import (
"fmt"
)
const numbers = 3
func main() {
max := 20
words := map[int]string{
3: "Fizz",
5: "Buzz",
7: "Baxx",
}
keys := []int{3, 5, 7}
divisible := false
for i := 1; i <= max; i++ {
for _, n := range keys {
if i % n == 0 {
fmt.Print(words[n])
divisible = true
}
}
if !divisible {
fmt.Print(i)
}
fmt.Println()
divisible = false
}
}
|
Transform the following PHP implementation into Go, maintaining the same output and logic. | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
| package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line %d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only %d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line %d empty", n)
}
return line, nil
}
|
Write the same code in Go as shown below in PHP. | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
| package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line %d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only %d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line %d empty", n)
}
return line, nil
}
|
Keep all operations the same but rewrite the snippet in Go. | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
| package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line %d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only %d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line %d empty", n)
}
return line, nil
}
|
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically? | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
| package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line %d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only %d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line %d empty", n)
}
return line, nil
}
|
Change the following PHP code into Go without altering its purpose. | $allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
$lc_allowed = array_map('strtolower', $allowed);
$tests = [
['MyData.a##',true],
['MyData.tar.Gz',true],
['MyData.gzip',false],
['MyData.7z.backup',false],
['MyData...',false],
['MyData',false],
['archive.tar.gz', true]
];
foreach ($tests as $test) {
$ext = pathinfo($test[0], PATHINFO_EXTENSION);
if (in_array(strtolower($ext), $lc_allowed)) {
$result = 'true';
} else {
$result = 'false';
}
printf("%20s : %s \n", $test[0],$result);
}
| package main
import (
"fmt"
"strings"
)
var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}
func fileExtInList(filename string) (bool, string) {
filename2 := strings.ToLower(filename)
for _, ext := range extensions {
ext2 := "." + strings.ToLower(ext)
if strings.HasSuffix(filename2, ext2) {
return true, ext
}
}
s := strings.Split(filename, ".")
if len(s) > 1 {
t := s[len(s)-1]
if t != "" {
return false, t
} else {
return false, "<empty>"
}
} else {
return false, "<none>"
}
}
func main() {
fmt.Println("The listed extensions are:")
fmt.Println(extensions, "\n")
tests := []string{
"MyData.a##", "MyData.tar.Gz", "MyData.gzip",
"MyData.7z.backup", "MyData...", "MyData",
"MyData_v1.0.tar.bz2", "MyData_v1.0.bz2",
}
for _, test := range tests {
ok, ext := fileExtInList(test)
fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.