Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert this C snippet to Go and keep its semantics consistent. | #include <stdio.h>
#include <string.h>
#include <locale.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
char as_digit(int d) {
return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';
}
void revstr(char *str) {
int i, len = strlen(str);
char t;
for (i = 0; i < len/2; ++i) {
t = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = t;
}
}
char* to_base(char s[], ull n, int b) {
int i = 0;
while (n) {
s[i++] = as_digit(n % b);
n /= b;
}
s[i] = '\0';
revstr(s);
return s;
}
ull uabs(ull a, ull b) {
return a > b ? a - b : b - a;
}
bool is_esthetic(ull n, int b) {
int i, j;
if (!n) return FALSE;
i = n % b;
n /= b;
while (n) {
j = n % b;
if (uabs(i, j) != 1) return FALSE;
n /= b;
i = j;
}
return TRUE;
}
ull esths[45000];
int le = 0;
void dfs(ull n, ull m, ull i) {
ull d, i1, i2;
if (i >= n && i <= m) esths[le++] = i;
if (i == 0 || i > m) return;
d = i % 10;
i1 = i * 10 + d - 1;
i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {
int i;
le = 0;
for (i = 0; i < 10; ++i) {
dfs(n2, m2, i);
}
printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m);
if (all) {
for (i = 0; i < le; ++i) {
printf("%llu ", esths[i]);
if (!(i+1)%per_line) printf("\n");
}
} else {
for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]);
printf("\n............\n");
for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]);
}
printf("\n\n");
}
int main() {
ull n;
int b, c;
char ch[15] = {0};
for (b = 2; b <= 16; ++b) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b);
for (n = 1, c = 0; c < 6 * b; ++n) {
if (is_esthetic(n, b)) {
if (++c >= 4 * b) printf("%s ", to_base(ch, n, b));
}
}
printf("\n\n");
}
char *oldLocale = setlocale(LC_NUMERIC, NULL);
setlocale(LC_NUMERIC, "");
list_esths(1000, 1010, 9999, 9898, 16, TRUE);
list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);
list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);
list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);
list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);
setlocale(LC_NUMERIC, oldLocale);
return 0;
}
| package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
}
|
Transform the following C implementation into Go, maintaining the same output and logic. | #include <stdio.h>
#include <string.h>
typedef struct { char v[16]; } deck;
typedef unsigned int uint;
uint n, d, best[16];
void tryswaps(deck *a, uint f, uint s) {
# define A a->v
# define B b.v
if (d > best[n]) best[n] = d;
while (1) {
if ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))
&& (d + best[s] >= best[n] || A[s] == -1))
break;
if (d + best[s] <= best[n]) return;
if (!--s) return;
}
d++;
deck b = *a;
for (uint i = 1, k = 2; i <= s; k <<= 1, i++) {
if (A[i] != i && (A[i] != -1 || (f & k)))
continue;
for (uint j = B[0] = i; j--;) B[i - j] = A[j];
tryswaps(&b, f | k, s);
}
d--;
}
int main(void) {
deck x;
memset(&x, -1, sizeof(x));
x.v[0] = 0;
for (n = 1; n < 13; n++) {
tryswaps(&x, 1, n - 1);
printf("%2d: %d\n", n, best[n]);
}
return 0;
}
|
package main
import "fmt"
const (
maxn = 10
maxl = 50
)
func main() {
for i := 1; i <= maxn; i++ {
fmt.Printf("%d: %d\n", i, steps(i))
}
}
func steps(n int) int {
var a, b [maxl][maxn + 1]int
var x [maxl]int
a[0][0] = 1
var m int
for l := 0; ; {
x[l]++
k := int(x[l])
if k >= n {
if l <= 0 {
break
}
l--
continue
}
if a[l][k] == 0 {
if b[l][k+1] != 0 {
continue
}
} else if a[l][k] != k+1 {
continue
}
a[l+1] = a[l]
for j := 1; j <= k; j++ {
a[l+1][j] = a[l][k-j]
}
b[l+1] = b[l]
a[l+1][0] = k + 1
b[l+1][k+1] = 1
if l > m-1 {
m = l + 1
}
l++
x[l] = 0
}
return m
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
#define UNITS_LENGTH 13
int main(int argC,char* argV[])
{
int i,reference;
char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};
if(argC!=3)
printf("Usage : %s followed by length as <value> <unit>");
else{
for(i=0;argV[2][i]!=00;i++)
argV[2][i] = tolower(argV[2][i]);
for(i=0;i<UNITS_LENGTH;i++){
if(strstr(argV[2],units[i])!=NULL){
reference = i;
factor = atof(argV[1])*values[i];
break;
}
}
printf("%s %s is equal in length to : \n",argV[1],argV[2]);
for(i=0;i<UNITS_LENGTH;i++){
if(i!=reference)
printf("\n%lf %s",factor/values[i],units[i]);
}
}
return 0;
}
| package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
units := []string{
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer",
}
convs := []float32{
0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668, 74676,
1, 100, 10000,
}
scanner := bufio.NewScanner(os.Stdin)
for {
for i, u := range units {
fmt.Printf("%2d %s\n", i+1, u)
}
fmt.Println()
var unit int
var err error
for {
fmt.Print("Please choose a unit 1 to 13 : ")
scanner.Scan()
unit, err = strconv.Atoi(scanner.Text())
if err == nil && unit >= 1 && unit <= 13 {
break
}
}
unit--
var value float64
for {
fmt.Print("Now enter a value in that unit : ")
scanner.Scan()
value, err = strconv.ParseFloat(scanner.Text(), 32)
if err == nil && value >= 0 {
break
}
}
fmt.Println("\nThe equivalent in the remaining units is:\n")
for i, u := range units {
if i == unit {
continue
}
fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i])
}
fmt.Println()
yn := ""
for yn != "y" && yn != "n" {
fmt.Print("Do another one y/n : ")
scanner.Scan()
yn = strings.ToLower(scanner.Text())
}
if yn == "n" {
return
}
}
}
|
Port the provided C code into Go while preserving the original functionality. | #include <stdio.h>
#include <time.h>
struct rate_state_s
{
time_t lastFlush;
time_t period;
size_t tickCount;
};
void tic_rate(struct rate_state_s* pRate)
{
pRate->tickCount += 1;
time_t now = time(NULL);
if((now - pRate->lastFlush) >= pRate->period)
{
size_t tps = 0.0;
if(pRate->tickCount > 0)
tps = pRate->tickCount / (now - pRate->lastFlush);
printf("%u tics per second.\n", tps);
pRate->tickCount = 0;
pRate->lastFlush = now;
}
}
void something_we_do()
{
volatile size_t anchor = 0;
size_t x = 0;
for(x = 0; x < 0xffff; ++x)
{
anchor = x;
}
}
int main()
{
time_t start = time(NULL);
struct rate_state_s rateWatch;
rateWatch.lastFlush = start;
rateWatch.tickCount = 0;
rateWatch.period = 5;
time_t latest = start;
for(latest = start; (latest - start) < 20; latest = time(NULL))
{
something_we_do();
tic_rate(&rateWatch);
}
return 0;
}
| package main
import (
"fmt"
"math/rand"
"time"
)
type rateStateS struct {
lastFlush time.Time
period time.Duration
tickCount int
}
func ticRate(pRate *rateStateS) {
pRate.tickCount++
now := time.Now()
if now.Sub(pRate.lastFlush) >= pRate.period {
tps := 0.
if pRate.tickCount > 0 {
tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()
}
fmt.Println(tps, "tics per second.")
pRate.tickCount = 0
pRate.lastFlush = now
}
}
func somethingWeDo() {
time.Sleep(time.Duration(9e7 + rand.Int63n(2e7)))
}
func main() {
start := time.Now()
rateWatch := rateStateS{
lastFlush: start,
period: 5 * time.Second,
}
latest := start
for latest.Sub(start) < 20*time.Second {
somethingWeDo()
ticRate(&rateWatch)
latest = time.Now()
}
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include <stdio.h>
#define MAX 15
int count_divisors(int n) {
int i, count = 0;
for (i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
int i, next = 1;
printf("The first %d terms of the sequence are:\n", MAX);
for (i = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
printf("%d ", i);
next++;
}
}
printf("\n");
return 0;
}
| package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
fmt.Println("The first", max, "terms of the sequence are:")
for i, next := 1, 1; next <= max; i++ {
if next == countDivisors(i) {
fmt.Printf("%d ", i)
next++
}
}
fmt.Println()
}
|
Convert this C snippet to Go and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int pRec(int n) {
static int *memo = NULL;
static size_t curSize = 0;
if (curSize <= (size_t) n) {
size_t lastSize = curSize;
while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
memo = realloc(memo, curSize * sizeof(int));
memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
}
if (memo[n] == 0) {
if (n<=2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
}
return memo[n];
}
int pFloor(int n) {
long double p = 1.324717957244746025960908854;
long double s = 1.0453567932525329623;
return powl(p, n-1)/s + 0.5;
}
void nextLSystem(const char *prev, char *buf) {
while (*prev) {
switch (*prev++) {
case 'A': *buf++ = 'B'; break;
case 'B': *buf++ = 'C'; break;
case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
}
}
*buf = '\0';
}
int main() {
#define BUFSZ 8192
char buf1[BUFSZ], buf2[BUFSZ];
int i;
printf("P_0 .. P_19: ");
for (i=0; i<20; i++) printf("%d ", pRec(i));
printf("\n");
printf("The floor- and recurrence-based functions ");
for (i=0; i<64; i++) {
if (pRec(i) != pFloor(i)) {
printf("do not match at %d: %d != %d.\n",
i, pRec(i), pFloor(i));
break;
}
}
if (i == 64) {
printf("match from P_0 to P_63.\n");
}
printf("\nThe first 10 L-system strings are:\n");
for (strcpy(buf1, "A"), i=0; i<10; i++) {
printf("%s\n", buf1);
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
printf("\nThe floor- and L-system-based functions ");
for (strcpy(buf1, "A"), i=0; i<32; i++) {
if ((int)strlen(buf1) != pFloor(i)) {
printf("do not match at %d: %d != %d\n",
i, (int)strlen(buf1), pFloor(i));
break;
}
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
if (i == 32) {
printf("match from P_0 to P_31.\n");
}
return 0;
}
| package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)
p, _ = p.SetString("1.324717957244746025960908854")
s, _ = s.SetString("1.0453567932525329623")
f := make([]int, n)
pow := new(big.Rat).SetInt64(1)
u = u.SetFrac64(1, 2)
t.Quo(pow, p)
t.Quo(t, s)
t.Add(t, u)
v, _ := t.Float64()
f[0] = int(math.Floor(v))
for i := 1; i < n; i++ {
t.Quo(pow, s)
t.Add(t, u)
v, _ = t.Float64()
f[i] = int(math.Floor(v))
pow.Mul(pow, p)
}
return f
}
type LSystem struct {
rules map[string]string
init, current string
}
func step(lsys *LSystem) string {
var sb strings.Builder
if lsys.current == "" {
lsys.current = lsys.init
} else {
for _, c := range lsys.current {
sb.WriteString(lsys.rules[string(c)])
}
lsys.current = sb.String()
}
return lsys.current
}
func padovanLSys(n int) []string {
rules := map[string]string{"A": "B", "B": "C", "C": "AB"}
lsys := &LSystem{rules, "A", ""}
p := make([]string, n)
for i := 0; i < n; i++ {
p[i] = step(lsys)
}
return p
}
func areSame(l1, l2 []int) bool {
for i := 0; i < len(l1); i++ {
if l1[i] != l2[i] {
return false
}
}
return true
}
func main() {
fmt.Println("First 20 members of the Padovan sequence:")
fmt.Println(padovanRecur(20))
recur := padovanRecur(64)
floor := padovanFloor(64)
same := areSame(recur, floor)
s := "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.")
p := padovanLSys(32)
lsyst := make([]int, 32)
for i := 0; i < 32; i++ {
lsyst[i] = len(p[i])
}
fmt.Println("\nFirst 10 members of the Padovan L-System:")
fmt.Println(p[:10])
fmt.Println("\nand their lengths:")
fmt.Println(lsyst[:10])
same = areSame(recur[:32], lsyst)
s = "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
|
Convert this C snippet to Go and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int pRec(int n) {
static int *memo = NULL;
static size_t curSize = 0;
if (curSize <= (size_t) n) {
size_t lastSize = curSize;
while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
memo = realloc(memo, curSize * sizeof(int));
memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
}
if (memo[n] == 0) {
if (n<=2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
}
return memo[n];
}
int pFloor(int n) {
long double p = 1.324717957244746025960908854;
long double s = 1.0453567932525329623;
return powl(p, n-1)/s + 0.5;
}
void nextLSystem(const char *prev, char *buf) {
while (*prev) {
switch (*prev++) {
case 'A': *buf++ = 'B'; break;
case 'B': *buf++ = 'C'; break;
case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
}
}
*buf = '\0';
}
int main() {
#define BUFSZ 8192
char buf1[BUFSZ], buf2[BUFSZ];
int i;
printf("P_0 .. P_19: ");
for (i=0; i<20; i++) printf("%d ", pRec(i));
printf("\n");
printf("The floor- and recurrence-based functions ");
for (i=0; i<64; i++) {
if (pRec(i) != pFloor(i)) {
printf("do not match at %d: %d != %d.\n",
i, pRec(i), pFloor(i));
break;
}
}
if (i == 64) {
printf("match from P_0 to P_63.\n");
}
printf("\nThe first 10 L-system strings are:\n");
for (strcpy(buf1, "A"), i=0; i<10; i++) {
printf("%s\n", buf1);
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
printf("\nThe floor- and L-system-based functions ");
for (strcpy(buf1, "A"), i=0; i<32; i++) {
if ((int)strlen(buf1) != pFloor(i)) {
printf("do not match at %d: %d != %d\n",
i, (int)strlen(buf1), pFloor(i));
break;
}
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
if (i == 32) {
printf("match from P_0 to P_31.\n");
}
return 0;
}
| package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)
p, _ = p.SetString("1.324717957244746025960908854")
s, _ = s.SetString("1.0453567932525329623")
f := make([]int, n)
pow := new(big.Rat).SetInt64(1)
u = u.SetFrac64(1, 2)
t.Quo(pow, p)
t.Quo(t, s)
t.Add(t, u)
v, _ := t.Float64()
f[0] = int(math.Floor(v))
for i := 1; i < n; i++ {
t.Quo(pow, s)
t.Add(t, u)
v, _ = t.Float64()
f[i] = int(math.Floor(v))
pow.Mul(pow, p)
}
return f
}
type LSystem struct {
rules map[string]string
init, current string
}
func step(lsys *LSystem) string {
var sb strings.Builder
if lsys.current == "" {
lsys.current = lsys.init
} else {
for _, c := range lsys.current {
sb.WriteString(lsys.rules[string(c)])
}
lsys.current = sb.String()
}
return lsys.current
}
func padovanLSys(n int) []string {
rules := map[string]string{"A": "B", "B": "C", "C": "AB"}
lsys := &LSystem{rules, "A", ""}
p := make([]string, n)
for i := 0; i < n; i++ {
p[i] = step(lsys)
}
return p
}
func areSame(l1, l2 []int) bool {
for i := 0; i < len(l1); i++ {
if l1[i] != l2[i] {
return false
}
}
return true
}
func main() {
fmt.Println("First 20 members of the Padovan sequence:")
fmt.Println(padovanRecur(20))
recur := padovanRecur(64)
floor := padovanFloor(64)
same := areSame(recur, floor)
s := "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.")
p := padovanLSys(32)
lsyst := make([]int, 32)
for i := 0; i < 32; i++ {
lsyst[i] = len(p[i])
}
fmt.Println("\nFirst 10 members of the Padovan L-System:")
fmt.Println(p[:10])
fmt.Println("\nand their lengths:")
fmt.Println(lsyst[:10])
same = areSame(recur[:32], lsyst)
s = "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
|
Generate a Go translation of this C snippet without changing its computational steps. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct{
double x,y;
}point;
void pythagorasTree(point a,point b,int times){
point c,d,e;
c.x = b.x - (a.y - b.y);
c.y = b.y - (b.x - a.x);
d.x = a.x - (a.y - b.y);
d.y = a.y - (b.x - a.x);
e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2;
e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2;
if(times>0){
setcolor(rand()%15 + 1);
line(a.x,a.y,b.x,b.y);
line(c.x,c.y,b.x,b.y);
line(c.x,c.y,d.x,d.y);
line(a.x,a.y,d.x,d.y);
pythagorasTree(d,e,times-1);
pythagorasTree(e,c,times-1);
}
}
int main(){
point a,b;
double side;
int iter;
time_t t;
printf("Enter initial side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
a.x = 6*side/2 - side/2;
a.y = 4*side;
b.x = 6*side/2 + side/2;
b.y = 4*side;
initwindow(6*side,4*side,"Pythagoras Tree ?");
srand((unsigned)time(&t));
pythagorasTree(a,b,iter);
getch();
closegraph();
return 0;
}
| package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
)
const (
width, height = 800, 600
maxDepth = 11
colFactor = uint8(255 / maxDepth)
fileName = "pythagorasTree.png"
)
func main() {
img := image.NewNRGBA(image.Rect(0, 0, width, height))
bg := image.NewUniform(color.RGBA{255, 255, 255, 255})
draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)
drawSquares(340, 550, 460, 550, img, 0)
imgFile, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer imgFile.Close()
if err := png.Encode(imgFile, img); err != nil {
imgFile.Close()
log.Fatal(err)
}
}
func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {
if depth > maxDepth {
return
}
dx, dy := bx-ax, ay-by
x3, y3 := bx-dy, by-dx
x4, y4 := ax-dy, ay-dx
x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2
col := color.RGBA{0, uint8(depth) * colFactor, 0, 255}
drawLine(ax, ay, bx, by, img, col)
drawLine(bx, by, x3, y3, img, col)
drawLine(x3, y3, x4, y4, img, col)
drawLine(x4, y4, ax, ay, img, col)
drawSquares(x4, y4, x5, y5, img, depth+1)
drawSquares(x5, y5, x3, y3, img, depth+1)
}
func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {
dx := abs(x1 - x0)
dy := abs(y1 - y0)
var sx, sy int = -1, -1
if x0 < x1 {
sx = 1
}
if y0 < y1 {
sy = 1
}
err := dx - dy
for {
img.Set(x0, y0, col)
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 > -dy {
err -= dy
x0 += sx
}
if e2 < dx {
err += dx
y0 += sy
}
}
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
int ch = 1;
while ((ch = owp(!ch)) != EOF) {
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
| package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader) {
byte_in := func () byte {
bs := make([]byte, 1)
src.Read(bs)
return bs[0]
}
byte_out := func (b byte) { dst.Write([]byte{b}) }
var odd func() byte
odd = func() byte {
s := byte_in()
if unicode.IsPunct(rune(s)) {
return s
}
b := odd()
byte_out(s)
return b
}
for {
for {
b := byte_in()
byte_out(b)
if b == '.' {
return
}
if unicode.IsPunct(rune(b)) {
break
}
}
b := odd()
byte_out(b)
if b == '.' {
return
}
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <math.h>
#include <stdio.h>
#include <stdint.h>
int64_t mod(int64_t x, int64_t y) {
int64_t m = x % y;
if (m < 0) {
if (y < 0) {
return m - y;
} else {
return m + y;
}
}
return m;
}
const static int64_t a1[3] = { 0, 1403580, -810728 };
const static int64_t m1 = (1LL << 32) - 209;
const static int64_t a2[3] = { 527612, 0, -1370589 };
const static int64_t m2 = (1LL << 32) - 22853;
const static int64_t d = (1LL << 32) - 209 + 1;
static int64_t x1[3];
static int64_t x2[3];
void seed(int64_t seed_state) {
x1[0] = seed_state;
x1[1] = 0;
x1[2] = 0;
x2[0] = seed_state;
x2[1] = 0;
x2[2] = 0;
}
int64_t next_int() {
int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);
int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);
int64_t z = mod(x1i - x2i, m1);
x1[2] = x1[1];
x1[1] = x1[0];
x1[0] = x1i;
x2[2] = x2[1];
x2[1] = x2[0];
x2[0] = x2i;
return z + 1;
}
double next_float() {
return (double)next_int() / d;
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("\n");
seed(987654321);
for (i = 0; i < 100000; i++) {
int64_t value = floor(next_float() * 5);
counts[value]++;
}
for (i = 0; i < 5; i++) {
printf("%d: %d\n", i, counts[i]);
}
return 0;
}
| package main
import (
"fmt"
"log"
"math"
)
var a1 = []int64{0, 1403580, -810728}
var a2 = []int64{527612, 0, -1370589}
const m1 = int64((1 << 32) - 209)
const m2 = int64((1 << 32) - 22853)
const d = m1 + 1
func mod(x, y int64) int64 {
m := x % y
if m < 0 {
if y < 0 {
return m - y
} else {
return m + y
}
}
return m
}
type MRG32k3a struct{ x1, x2 [3]int64 }
func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }
func (mrg *MRG32k3a) seed(seedState int64) {
if seedState <= 0 || seedState >= d {
log.Fatalf("Argument must be in the range [0, %d].\n", d)
}
mrg.x1 = [3]int64{seedState, 0, 0}
mrg.x2 = [3]int64{seedState, 0, 0}
}
func (mrg *MRG32k3a) nextInt() int64 {
x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)
x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)
mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]}
mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]}
return mod(x1i-x2i, m1) + 1
}
func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }
func main() {
randomGen := MRG32k3aNew()
randomGen.seed(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool colorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[10] = {};
int digits[8] = {};
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[36] = {};
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
static int count[8];
static bool used[10];
static int largest = 0;
void count_colorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
count_colorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (colorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
count_colorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
int main() {
setlocale(LC_ALL, "");
clock_t start = clock();
printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (colorful(n))
printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
count_colorful(0, 0, 0);
printf("\n\nLargest colorful number: %'d\n", largest);
printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
printf("%d %'d\n", d + 1, count[d]);
total += count[d];
}
printf("\nTotal: %'d\n", total);
clock_t end = clock();
printf("\nElapsed time: %f seconds\n",
(end - start + 0.0) / CLOCKS_PER_SEC);
return 0;
}
| package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
|
Change the programming language of this snippet from C to Go without modifying what it does. | #include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool colorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[10] = {};
int digits[8] = {};
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[36] = {};
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
static int count[8];
static bool used[10];
static int largest = 0;
void count_colorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
count_colorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (colorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
count_colorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
int main() {
setlocale(LC_ALL, "");
clock_t start = clock();
printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (colorful(n))
printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
count_colorful(0, 0, 0);
printf("\n\nLargest colorful number: %'d\n", largest);
printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
printf("%d %'d\n", d + 1, count[d]);
total += count[d];
}
printf("\nTotal: %'d\n", total);
clock_t end = clock();
printf("\nElapsed time: %f seconds\n",
(end - start + 0.0) / CLOCKS_PER_SEC);
return 0;
}
| package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_tasks_without_examples.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
| package main
import (
"fmt"
"html"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
)
func main() {
ex := `<li><a href="/wiki/(.*?)"`
re := regexp.MustCompile(ex)
page := "http:
resp, _ := http.Get(page)
body, _ := ioutil.ReadAll(resp.Body)
matches := re.FindAllStringSubmatch(string(body), -1)
resp.Body.Close()
tasks := make([]string, len(matches))
for i, match := range matches {
tasks[i] = match[1]
}
const base = "http:
const limit = 3
ex = `(?s)using any language you may know.</div>(.*?)<div id="toc"`
ex2 := `</?[^>]*>`
re = regexp.MustCompile(ex)
re2 := regexp.MustCompile(ex2)
for i, task := range tasks {
page = base + task
resp, _ = http.Get(page)
body, _ = ioutil.ReadAll(resp.Body)
match := re.FindStringSubmatch(string(body))
resp.Body.Close()
text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], ""))
fmt.Println(strings.Replace(task, "_", " ", -1), "\n", text)
if i == limit-1 {
break
}
time.Sleep(5 * time.Second)
}
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
printf(" (critical day)");
printf("\n");
}
int main(int argc, char *argv[]) {
int diff;
if (argc < 7) {
printf("Usage:\n");
printf("cbio y1 m1 d1 y2 m2 d2\n");
exit(1);
}
diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
- day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
printf("Age: %u days\n", diff);
cycle(diff, 23, "Physical");
cycle(diff, 28, "Emotional");
cycle(diff, 33, "Intellectual");
}
| package main
import (
"fmt"
"log"
"math"
"time"
)
const layout = "2006-01-02"
var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "}
var lengths = [3]int{23, 28, 33}
var quadrants = [4][2]string{
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func biorhythms(birthDate, targetDate string) {
bd, err := time.Parse(layout, birthDate)
check(err)
td, err := time.Parse(layout, targetDate)
check(err)
days := int(td.Sub(bd).Hours() / 24)
fmt.Printf("Born %s, Target %s\n", birthDate, targetDate)
fmt.Println("Day", days)
for i := 0; i < 3; i++ {
length := lengths[i]
cycle := cycles[i]
position := days % length
quadrant := position * 4 / length
percent := math.Sin(2 * math.Pi * float64(position) / float64(length))
percent = math.Floor(percent*1000) / 10
descript := ""
if percent > 95 {
descript = " peak"
} else if percent < -95 {
descript = " valley"
} else if math.Abs(percent) < 5 {
descript = " critical transition"
} else {
daysToAdd := (quadrant+1)*length/4 - position
transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))
trend := quadrants[quadrant][0]
next := quadrants[quadrant][1]
transStr := transition.Format(layout)
descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr)
}
fmt.Printf("%s %2d : %s\n", cycle, position, descript)
}
fmt.Println()
}
func main() {
datePairs := [][2]string{
{"1943-03-09", "1972-07-11"},
{"1809-01-12", "1863-11-19"},
{"1809-02-12", "1863-11-19"},
}
for _, datePair := range datePairs {
biorhythms(datePair[0], datePair[1])
}
}
|
Produce a functionally identical Go code for the snippet given in C. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
printf(" (critical day)");
printf("\n");
}
int main(int argc, char *argv[]) {
int diff;
if (argc < 7) {
printf("Usage:\n");
printf("cbio y1 m1 d1 y2 m2 d2\n");
exit(1);
}
diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
- day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
printf("Age: %u days\n", diff);
cycle(diff, 23, "Physical");
cycle(diff, 28, "Emotional");
cycle(diff, 33, "Intellectual");
}
| package main
import (
"fmt"
"log"
"math"
"time"
)
const layout = "2006-01-02"
var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "}
var lengths = [3]int{23, 28, 33}
var quadrants = [4][2]string{
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func biorhythms(birthDate, targetDate string) {
bd, err := time.Parse(layout, birthDate)
check(err)
td, err := time.Parse(layout, targetDate)
check(err)
days := int(td.Sub(bd).Hours() / 24)
fmt.Printf("Born %s, Target %s\n", birthDate, targetDate)
fmt.Println("Day", days)
for i := 0; i < 3; i++ {
length := lengths[i]
cycle := cycles[i]
position := days % length
quadrant := position * 4 / length
percent := math.Sin(2 * math.Pi * float64(position) / float64(length))
percent = math.Floor(percent*1000) / 10
descript := ""
if percent > 95 {
descript = " peak"
} else if percent < -95 {
descript = " valley"
} else if math.Abs(percent) < 5 {
descript = " critical transition"
} else {
daysToAdd := (quadrant+1)*length/4 - position
transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))
trend := quadrants[quadrant][0]
next := quadrants[quadrant][1]
transStr := transition.Format(layout)
descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr)
}
fmt.Printf("%s %2d : %s\n", cycle, position, descript)
}
fmt.Println()
}
func main() {
datePairs := [][2]string{
{"1943-03-09", "1972-07-11"},
{"1809-01-12", "1863-11-19"},
{"1809-02-12", "1863-11-19"},
}
for _, datePair := range datePairs {
biorhythms(datePair[0], datePair[1])
}
}
|
Ensure the translated Go code behaves exactly like the original C snippet. | #include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
const char *code =
"CREATE TABLE address (\n"
" addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" addrStreet TEXT NOT NULL,\n"
" addrCity TEXT NOT NULL,\n"
" addrState TEXT NOT NULL,\n"
" addrZIP TEXT NOT NULL)\n" ;
int main()
{
sqlite3 *db = NULL;
char *errmsg;
if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) {
fprintf(stderr, errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
exit(EXIT_FAILURE);
}
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
| package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "rc.db")
if err != nil {
log.Print(err)
return
}
defer db.Close()
_, err = db.Exec(`create table addr (
id int unique,
street text,
city text,
state text,
zip text
)`)
if err != nil {
log.Print(err)
return
}
rows, err := db.Query(`pragma table_info(addr)`)
if err != nil {
log.Print(err)
return
}
var field, storage string
var ignore sql.RawBytes
for rows.Next() {
err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)
if err != nil {
log.Print(err)
return
}
fmt.Println(field, storage)
}
}
|
Generate an equivalent Go version of this C code. | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
int header[] = {46, 115, 110, 100, 0, 0, 0, 24,
255, 255, 255, 255, 0, 0, 0, 3,
0, 0, 172, 68, 0, 0, 0, 1};
int main(int argc, char *argv[]){
float freq, dur;
long i, v;
if (argc < 3) {
printf("Usage:\n");
printf(" csine <frequency> <duration>\n");
exit(1);
}
freq = atof(argv[1]);
dur = atof(argv[2]);
for (i = 0; i < 24; i++)
putchar(header[i]);
for (i = 0; i < dur * 44100; i++) {
v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));
v = v % 65536;
putchar(v >> 8);
putchar(v % 256);
}
}
| package main
import (
"fmt"
"os/exec"
)
func main() {
synthType := "sine"
duration := "5"
frequency := "440"
cmd := exec.Command("play", "-n", "synth", duration, synthType, frequency)
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
}
|
Translate the given C code snippet into Go without altering its behavior. | count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
| package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
jz
prtc
prts
prti
halt
)
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
}
type atr struct {
enumText string
nodeType NodeType
opcode code
}
var atrs = []atr{
{"Identifier", ndIdent, 255},
{"String", ndString, 255},
{"Integer", ndInteger, 255},
{"Sequence", ndSequence, 255},
{"If", ndIf, 255},
{"Prtc", ndPrtc, 255},
{"Prts", ndPrts, 255},
{"Prti", ndPrti, 255},
{"While", ndWhile, 255},
{"Assign", ndAssign, 255},
{"Negate", ndNegate, neg},
{"Not", ndNot, not},
{"Multiply", ndMul, mul},
{"Divide", ndDiv, div},
{"Mod", ndMod, mod},
{"Add", ndAdd, add},
{"Subtract", ndSub, sub},
{"Less", ndLss, lt},
{"LessEqual", ndLeq, le},
{"Greater", ndGtr, gt},
{"GreaterEqual", ndGeq, ge},
{"Equal", ndEql, eq},
{"NotEqual", ndNeq, ne},
{"And", ndAnd, and},
{"Or", ndOr, or},
}
var (
stringPool []string
globals []string
object []code
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func nodeType2Op(nodeType NodeType) code {
return atrs[nodeType].opcode
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, ""}
}
func makeLeaf(nodeType NodeType, value string) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func emitWordAt(at, n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for i := at; i < at+4; i++ {
object[i] = code(bs[i-at])
}
}
func hole() int {
t := len(object)
emitWord(0)
return t
}
func fetchVarOffset(id string) int {
for i := 0; i < len(globals); i++ {
if globals[i] == id {
return i
}
}
globals = append(globals, id)
return len(globals) - 1
}
func fetchStringOffset(st string) int {
for i := 0; i < len(stringPool); i++ {
if stringPool[i] == st {
return i
}
}
stringPool = append(stringPool, st)
return len(stringPool) - 1
}
func codeGen(x *Tree) {
if x == nil {
return
}
var n, p1, p2 int
switch x.nodeType {
case ndIdent:
emitByte(fetch)
n = fetchVarOffset(x.value)
emitWord(n)
case ndInteger:
emitByte(push)
n, err = strconv.Atoi(x.value)
check(err)
emitWord(n)
case ndString:
emitByte(push)
n = fetchStringOffset(x.value)
emitWord(n)
case ndAssign:
n = fetchVarOffset(x.left.value)
codeGen(x.right)
emitByte(store)
emitWord(n)
case ndIf:
codeGen(x.left)
emitByte(jz)
p1 = hole()
codeGen(x.right.left)
if x.right.right != nil {
emitByte(jmp)
p2 = hole()
}
emitWordAt(p1, len(object)-p1)
if x.right.right != nil {
codeGen(x.right.right)
emitWordAt(p2, len(object)-p2)
}
case ndWhile:
p1 = len(object)
codeGen(x.left)
emitByte(jz)
p2 = hole()
codeGen(x.right)
emitByte(jmp)
emitWord(p1 - len(object))
emitWordAt(p2, len(object)-p2)
case ndSequence:
codeGen(x.left)
codeGen(x.right)
case ndPrtc:
codeGen(x.left)
emitByte(prtc)
case ndPrti:
codeGen(x.left)
emitByte(prti)
case ndPrts:
codeGen(x.left)
emitByte(prts)
case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,
ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:
codeGen(x.left)
codeGen(x.right)
emitByte(nodeType2Op(x.nodeType))
case ndNegate, ndNot:
codeGen(x.left)
emitByte(nodeType2Op(x.nodeType))
default:
msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType)
reportError(msg)
}
}
func codeFinish() {
emitByte(halt)
}
func listCode() {
fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool))
for _, s := range stringPool {
fmt.Println(s)
}
pc := 0
for pc < len(object) {
fmt.Printf("%5d ", pc)
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("fetch [%d]\n", x)
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("store [%d]\n", x)
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("push %d\n", x)
pc += 4
case add:
fmt.Println("add")
case sub:
fmt.Println("sub")
case mul:
fmt.Println("mul")
case div:
fmt.Println("div")
case mod:
fmt.Println("mod")
case lt:
fmt.Println("lt")
case gt:
fmt.Println("gt")
case le:
fmt.Println("le")
case ge:
fmt.Println("ge")
case eq:
fmt.Println("eq")
case ne:
fmt.Println("ne")
case and:
fmt.Println("and")
case or:
fmt.Println("or")
case neg:
fmt.Println("neg")
case not:
fmt.Println("not")
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x)
pc += 4
case jz:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jz (%d) %d\n", x, int32(pc)+x)
pc += 4
case prtc:
fmt.Println("prtc")
case prti:
fmt.Println("prti")
case prts:
fmt.Println("prts")
case halt:
fmt.Println("halt")
default:
reportError(fmt.Sprintf("listCode: Unknown opcode %d", op))
}
}
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
return makeLeaf(nodeType, s)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
codeGen(loadAst())
codeFinish()
listCode()
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C version. | count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
| package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
jz
prtc
prts
prti
halt
)
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
}
type atr struct {
enumText string
nodeType NodeType
opcode code
}
var atrs = []atr{
{"Identifier", ndIdent, 255},
{"String", ndString, 255},
{"Integer", ndInteger, 255},
{"Sequence", ndSequence, 255},
{"If", ndIf, 255},
{"Prtc", ndPrtc, 255},
{"Prts", ndPrts, 255},
{"Prti", ndPrti, 255},
{"While", ndWhile, 255},
{"Assign", ndAssign, 255},
{"Negate", ndNegate, neg},
{"Not", ndNot, not},
{"Multiply", ndMul, mul},
{"Divide", ndDiv, div},
{"Mod", ndMod, mod},
{"Add", ndAdd, add},
{"Subtract", ndSub, sub},
{"Less", ndLss, lt},
{"LessEqual", ndLeq, le},
{"Greater", ndGtr, gt},
{"GreaterEqual", ndGeq, ge},
{"Equal", ndEql, eq},
{"NotEqual", ndNeq, ne},
{"And", ndAnd, and},
{"Or", ndOr, or},
}
var (
stringPool []string
globals []string
object []code
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func nodeType2Op(nodeType NodeType) code {
return atrs[nodeType].opcode
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, ""}
}
func makeLeaf(nodeType NodeType, value string) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func emitWordAt(at, n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for i := at; i < at+4; i++ {
object[i] = code(bs[i-at])
}
}
func hole() int {
t := len(object)
emitWord(0)
return t
}
func fetchVarOffset(id string) int {
for i := 0; i < len(globals); i++ {
if globals[i] == id {
return i
}
}
globals = append(globals, id)
return len(globals) - 1
}
func fetchStringOffset(st string) int {
for i := 0; i < len(stringPool); i++ {
if stringPool[i] == st {
return i
}
}
stringPool = append(stringPool, st)
return len(stringPool) - 1
}
func codeGen(x *Tree) {
if x == nil {
return
}
var n, p1, p2 int
switch x.nodeType {
case ndIdent:
emitByte(fetch)
n = fetchVarOffset(x.value)
emitWord(n)
case ndInteger:
emitByte(push)
n, err = strconv.Atoi(x.value)
check(err)
emitWord(n)
case ndString:
emitByte(push)
n = fetchStringOffset(x.value)
emitWord(n)
case ndAssign:
n = fetchVarOffset(x.left.value)
codeGen(x.right)
emitByte(store)
emitWord(n)
case ndIf:
codeGen(x.left)
emitByte(jz)
p1 = hole()
codeGen(x.right.left)
if x.right.right != nil {
emitByte(jmp)
p2 = hole()
}
emitWordAt(p1, len(object)-p1)
if x.right.right != nil {
codeGen(x.right.right)
emitWordAt(p2, len(object)-p2)
}
case ndWhile:
p1 = len(object)
codeGen(x.left)
emitByte(jz)
p2 = hole()
codeGen(x.right)
emitByte(jmp)
emitWord(p1 - len(object))
emitWordAt(p2, len(object)-p2)
case ndSequence:
codeGen(x.left)
codeGen(x.right)
case ndPrtc:
codeGen(x.left)
emitByte(prtc)
case ndPrti:
codeGen(x.left)
emitByte(prti)
case ndPrts:
codeGen(x.left)
emitByte(prts)
case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,
ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:
codeGen(x.left)
codeGen(x.right)
emitByte(nodeType2Op(x.nodeType))
case ndNegate, ndNot:
codeGen(x.left)
emitByte(nodeType2Op(x.nodeType))
default:
msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType)
reportError(msg)
}
}
func codeFinish() {
emitByte(halt)
}
func listCode() {
fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool))
for _, s := range stringPool {
fmt.Println(s)
}
pc := 0
for pc < len(object) {
fmt.Printf("%5d ", pc)
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("fetch [%d]\n", x)
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("store [%d]\n", x)
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("push %d\n", x)
pc += 4
case add:
fmt.Println("add")
case sub:
fmt.Println("sub")
case mul:
fmt.Println("mul")
case div:
fmt.Println("div")
case mod:
fmt.Println("mod")
case lt:
fmt.Println("lt")
case gt:
fmt.Println("gt")
case le:
fmt.Println("le")
case ge:
fmt.Println("ge")
case eq:
fmt.Println("eq")
case ne:
fmt.Println("ne")
case and:
fmt.Println("and")
case or:
fmt.Println("or")
case neg:
fmt.Println("neg")
case not:
fmt.Println("not")
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x)
pc += 4
case jz:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jz (%d) %d\n", x, int32(pc)+x)
pc += 4
case prtc:
fmt.Println("prtc")
case prti:
fmt.Println("prti")
case prts:
fmt.Println("prts")
case halt:
fmt.Println("halt")
default:
reportError(fmt.Sprintf("listCode: Unknown opcode %d", op))
}
}
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
return makeLeaf(nodeType, s)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
codeGen(loadAst())
codeFinish()
listCode()
}
|
Ensure the translated Go code behaves exactly like the original C snippet. |
#include <stdlib.h>
#include "myutil.h"
|
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
Write the same algorithm in Go as shown in this C implementation. |
#include <stdlib.h>
#include "myutil.h"
|
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
Write a version of this C function in Go with identical behavior. | #include <stdio.h>
#include <stdlib.h>
typedef struct sublist{
struct sublist* next;
int *buf;
} sublist_t;
sublist_t* sublist_new(size_t s)
{
sublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);
sub->buf = (int*)(sub + 1);
sub->next = 0;
return sub;
}
typedef struct vlist_t {
sublist_t* head;
size_t last_size, ofs;
} vlist_t, *vlist;
vlist v_new()
{
vlist v = malloc(sizeof(vlist_t));
v->head = sublist_new(1);
v->last_size = 1;
v->ofs = 0;
return v;
}
void v_del(vlist v)
{
sublist_t *s;
while (v->head) {
s = v->head->next;
free(v->head);
v->head = s;
}
free(v);
}
inline size_t v_size(vlist v)
{
return v->last_size * 2 - v->ofs - 2;
}
int* v_addr(vlist v, size_t idx)
{
sublist_t *s = v->head;
size_t top = v->last_size, i = idx + v->ofs;
if (i + 2 >= (top << 1)) {
fprintf(stderr, "!: idx %d out of range\n", (int)idx);
abort();
}
while (s && i >= top) {
s = s->next, i ^= top;
top >>= 1;
}
return s->buf + i;
}
inline int v_elem(vlist v, size_t idx)
{
return *v_addr(v, idx);
}
int* v_unshift(vlist v, int x)
{
sublist_t* s;
int *p;
if (!v->ofs) {
if (!(s = sublist_new(v->last_size << 1))) {
fprintf(stderr, "?: alloc failure\n");
return 0;
}
v->ofs = (v->last_size <<= 1);
s->next = v->head;
v->head = s;
}
*(p = v->head->buf + --v->ofs) = x;
return p;
}
int v_shift(vlist v)
{
sublist_t* s;
int x;
if (v->last_size == 1 && v->ofs == 1) {
fprintf(stderr, "!: empty list\n");
abort();
}
x = v->head->buf[v->ofs++];
if (v->ofs == v->last_size) {
v->ofs = 0;
if (v->last_size > 1) {
s = v->head, v->head = s->next;
v->last_size >>= 1;
free(s);
}
}
return x;
}
int main()
{
int i;
vlist v = v_new();
for (i = 0; i < 10; i++) v_unshift(v, i);
printf("size: %d\n", v_size(v));
for (i = 0; i < 10; i++) printf("v[%d] = %d\n", i, v_elem(v, i));
for (i = 0; i < 10; i++) printf("shift: %d\n", v_shift(v));
v_del(v);
return 0;
}
| package main
import "fmt"
type vList struct {
base *vSeg
offset int
}
type vSeg struct {
next *vSeg
ele []vEle
}
type vEle string
func (v vList) index(i int) (r vEle) {
if i >= 0 {
i += v.offset
for sg := v.base; sg != nil; sg = sg.next {
if i < len(sg.ele) {
return sg.ele[i]
}
i -= len(sg.ele)
}
}
panic("index out of range")
}
func (v vList) cons(a vEle) vList {
if v.base == nil {
return vList{base: &vSeg{ele: []vEle{a}}}
}
if v.offset == 0 {
l2 := len(v.base.ele) * 2
ele := make([]vEle, l2)
ele[l2-1] = a
return vList{&vSeg{v.base, ele}, l2 - 1}
}
v.offset--
v.base.ele[v.offset] = a
return v
}
func (v vList) cdr() vList {
if v.base == nil {
panic("cdr on empty vList")
}
v.offset++
if v.offset < len(v.base.ele) {
return v
}
return vList{v.base.next, 0}
}
func (v vList) length() int {
if v.base == nil {
return 0
}
return len(v.base.ele)*2 - v.offset - 1
}
func (v vList) String() string {
if v.base == nil {
return "[]"
}
r := fmt.Sprintf("[%v", v.base.ele[v.offset])
for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {
for _, e := range sl {
r = fmt.Sprintf("%s %v", r, e)
}
sg = sg.next
if sg == nil {
break
}
sl = sg.ele
}
return r + "]"
}
func (v vList) printStructure() {
fmt.Println("offset:", v.offset)
for sg := v.base; sg != nil; sg = sg.next {
fmt.Printf(" %q\n", sg.ele)
}
fmt.Println()
}
func main() {
var v vList
fmt.Println("zero value for type. empty vList:", v)
v.printStructure()
for a := '6'; a >= '1'; a-- {
v = v.cons(vEle(a))
}
fmt.Println("demonstrate cons. 6 elements added:", v)
v.printStructure()
v = v.cdr()
fmt.Println("demonstrate cdr. 1 element removed:", v)
v.printStructure()
fmt.Println("demonstrate length. length =", v.length())
fmt.Println()
fmt.Println("demonstrate element access. v[3] =", v.index(3))
fmt.Println()
v = v.cdr().cdr()
fmt.Println("show cdr releasing segment. 2 elements removed:", v)
v.printStructure()
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <stdio.h>
#include <stdlib.h>
typedef struct sublist{
struct sublist* next;
int *buf;
} sublist_t;
sublist_t* sublist_new(size_t s)
{
sublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);
sub->buf = (int*)(sub + 1);
sub->next = 0;
return sub;
}
typedef struct vlist_t {
sublist_t* head;
size_t last_size, ofs;
} vlist_t, *vlist;
vlist v_new()
{
vlist v = malloc(sizeof(vlist_t));
v->head = sublist_new(1);
v->last_size = 1;
v->ofs = 0;
return v;
}
void v_del(vlist v)
{
sublist_t *s;
while (v->head) {
s = v->head->next;
free(v->head);
v->head = s;
}
free(v);
}
inline size_t v_size(vlist v)
{
return v->last_size * 2 - v->ofs - 2;
}
int* v_addr(vlist v, size_t idx)
{
sublist_t *s = v->head;
size_t top = v->last_size, i = idx + v->ofs;
if (i + 2 >= (top << 1)) {
fprintf(stderr, "!: idx %d out of range\n", (int)idx);
abort();
}
while (s && i >= top) {
s = s->next, i ^= top;
top >>= 1;
}
return s->buf + i;
}
inline int v_elem(vlist v, size_t idx)
{
return *v_addr(v, idx);
}
int* v_unshift(vlist v, int x)
{
sublist_t* s;
int *p;
if (!v->ofs) {
if (!(s = sublist_new(v->last_size << 1))) {
fprintf(stderr, "?: alloc failure\n");
return 0;
}
v->ofs = (v->last_size <<= 1);
s->next = v->head;
v->head = s;
}
*(p = v->head->buf + --v->ofs) = x;
return p;
}
int v_shift(vlist v)
{
sublist_t* s;
int x;
if (v->last_size == 1 && v->ofs == 1) {
fprintf(stderr, "!: empty list\n");
abort();
}
x = v->head->buf[v->ofs++];
if (v->ofs == v->last_size) {
v->ofs = 0;
if (v->last_size > 1) {
s = v->head, v->head = s->next;
v->last_size >>= 1;
free(s);
}
}
return x;
}
int main()
{
int i;
vlist v = v_new();
for (i = 0; i < 10; i++) v_unshift(v, i);
printf("size: %d\n", v_size(v));
for (i = 0; i < 10; i++) printf("v[%d] = %d\n", i, v_elem(v, i));
for (i = 0; i < 10; i++) printf("shift: %d\n", v_shift(v));
v_del(v);
return 0;
}
| package main
import "fmt"
type vList struct {
base *vSeg
offset int
}
type vSeg struct {
next *vSeg
ele []vEle
}
type vEle string
func (v vList) index(i int) (r vEle) {
if i >= 0 {
i += v.offset
for sg := v.base; sg != nil; sg = sg.next {
if i < len(sg.ele) {
return sg.ele[i]
}
i -= len(sg.ele)
}
}
panic("index out of range")
}
func (v vList) cons(a vEle) vList {
if v.base == nil {
return vList{base: &vSeg{ele: []vEle{a}}}
}
if v.offset == 0 {
l2 := len(v.base.ele) * 2
ele := make([]vEle, l2)
ele[l2-1] = a
return vList{&vSeg{v.base, ele}, l2 - 1}
}
v.offset--
v.base.ele[v.offset] = a
return v
}
func (v vList) cdr() vList {
if v.base == nil {
panic("cdr on empty vList")
}
v.offset++
if v.offset < len(v.base.ele) {
return v
}
return vList{v.base.next, 0}
}
func (v vList) length() int {
if v.base == nil {
return 0
}
return len(v.base.ele)*2 - v.offset - 1
}
func (v vList) String() string {
if v.base == nil {
return "[]"
}
r := fmt.Sprintf("[%v", v.base.ele[v.offset])
for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {
for _, e := range sl {
r = fmt.Sprintf("%s %v", r, e)
}
sg = sg.next
if sg == nil {
break
}
sl = sg.ele
}
return r + "]"
}
func (v vList) printStructure() {
fmt.Println("offset:", v.offset)
for sg := v.base; sg != nil; sg = sg.next {
fmt.Printf(" %q\n", sg.ele)
}
fmt.Println()
}
func main() {
var v vList
fmt.Println("zero value for type. empty vList:", v)
v.printStructure()
for a := '6'; a >= '1'; a-- {
v = v.cons(vEle(a))
}
fmt.Println("demonstrate cons. 6 elements added:", v)
v.printStructure()
v = v.cdr()
fmt.Println("demonstrate cdr. 1 element removed:", v)
v.printStructure()
fmt.Println("demonstrate length. length =", v.length())
fmt.Println()
fmt.Println("demonstrate element access. v[3] =", v.index(3))
fmt.Println()
v = v.cdr().cdr()
fmt.Println("show cdr releasing segment. 2 elements removed:", v)
v.printStructure()
}
|
Convert this C block to Go, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
typedef struct sublist{
struct sublist* next;
int *buf;
} sublist_t;
sublist_t* sublist_new(size_t s)
{
sublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);
sub->buf = (int*)(sub + 1);
sub->next = 0;
return sub;
}
typedef struct vlist_t {
sublist_t* head;
size_t last_size, ofs;
} vlist_t, *vlist;
vlist v_new()
{
vlist v = malloc(sizeof(vlist_t));
v->head = sublist_new(1);
v->last_size = 1;
v->ofs = 0;
return v;
}
void v_del(vlist v)
{
sublist_t *s;
while (v->head) {
s = v->head->next;
free(v->head);
v->head = s;
}
free(v);
}
inline size_t v_size(vlist v)
{
return v->last_size * 2 - v->ofs - 2;
}
int* v_addr(vlist v, size_t idx)
{
sublist_t *s = v->head;
size_t top = v->last_size, i = idx + v->ofs;
if (i + 2 >= (top << 1)) {
fprintf(stderr, "!: idx %d out of range\n", (int)idx);
abort();
}
while (s && i >= top) {
s = s->next, i ^= top;
top >>= 1;
}
return s->buf + i;
}
inline int v_elem(vlist v, size_t idx)
{
return *v_addr(v, idx);
}
int* v_unshift(vlist v, int x)
{
sublist_t* s;
int *p;
if (!v->ofs) {
if (!(s = sublist_new(v->last_size << 1))) {
fprintf(stderr, "?: alloc failure\n");
return 0;
}
v->ofs = (v->last_size <<= 1);
s->next = v->head;
v->head = s;
}
*(p = v->head->buf + --v->ofs) = x;
return p;
}
int v_shift(vlist v)
{
sublist_t* s;
int x;
if (v->last_size == 1 && v->ofs == 1) {
fprintf(stderr, "!: empty list\n");
abort();
}
x = v->head->buf[v->ofs++];
if (v->ofs == v->last_size) {
v->ofs = 0;
if (v->last_size > 1) {
s = v->head, v->head = s->next;
v->last_size >>= 1;
free(s);
}
}
return x;
}
int main()
{
int i;
vlist v = v_new();
for (i = 0; i < 10; i++) v_unshift(v, i);
printf("size: %d\n", v_size(v));
for (i = 0; i < 10; i++) printf("v[%d] = %d\n", i, v_elem(v, i));
for (i = 0; i < 10; i++) printf("shift: %d\n", v_shift(v));
v_del(v);
return 0;
}
| package main
import "fmt"
type vList struct {
base *vSeg
offset int
}
type vSeg struct {
next *vSeg
ele []vEle
}
type vEle string
func (v vList) index(i int) (r vEle) {
if i >= 0 {
i += v.offset
for sg := v.base; sg != nil; sg = sg.next {
if i < len(sg.ele) {
return sg.ele[i]
}
i -= len(sg.ele)
}
}
panic("index out of range")
}
func (v vList) cons(a vEle) vList {
if v.base == nil {
return vList{base: &vSeg{ele: []vEle{a}}}
}
if v.offset == 0 {
l2 := len(v.base.ele) * 2
ele := make([]vEle, l2)
ele[l2-1] = a
return vList{&vSeg{v.base, ele}, l2 - 1}
}
v.offset--
v.base.ele[v.offset] = a
return v
}
func (v vList) cdr() vList {
if v.base == nil {
panic("cdr on empty vList")
}
v.offset++
if v.offset < len(v.base.ele) {
return v
}
return vList{v.base.next, 0}
}
func (v vList) length() int {
if v.base == nil {
return 0
}
return len(v.base.ele)*2 - v.offset - 1
}
func (v vList) String() string {
if v.base == nil {
return "[]"
}
r := fmt.Sprintf("[%v", v.base.ele[v.offset])
for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {
for _, e := range sl {
r = fmt.Sprintf("%s %v", r, e)
}
sg = sg.next
if sg == nil {
break
}
sl = sg.ele
}
return r + "]"
}
func (v vList) printStructure() {
fmt.Println("offset:", v.offset)
for sg := v.base; sg != nil; sg = sg.next {
fmt.Printf(" %q\n", sg.ele)
}
fmt.Println()
}
func main() {
var v vList
fmt.Println("zero value for type. empty vList:", v)
v.printStructure()
for a := '6'; a >= '1'; a-- {
v = v.cons(vEle(a))
}
fmt.Println("demonstrate cons. 6 elements added:", v)
v.printStructure()
v = v.cdr()
fmt.Println("demonstrate cdr. 1 element removed:", v)
v.printStructure()
fmt.Println("demonstrate length. length =", v.length())
fmt.Println()
fmt.Println("demonstrate element access. v[3] =", v.index(3))
fmt.Println()
v = v.cdr().cdr()
fmt.Println("show cdr releasing segment. 2 elements removed:", v)
v.printStructure()
}
|
Write the same algorithm in Go as shown in this C implementation. | k=2; i=1; j=2;
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
}
| package main
import (
"fmt"
"sternbrocot"
)
func main() {
g := sb.Generator()
fmt.Println("First 15:")
for i := 1; i <= 15; i++ {
fmt.Printf("%2d: %d\n", i, g())
}
s := sb.New()
fmt.Println("First 15:", s.FirstN(15))
for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {
fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x))
}
fmt.Println("1-based indexes: gcd")
for n, f := range s.FirstN(1000)[:999] {
g := gcd(f, (*s)[n+1])
fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g)
if g != 1 {
panic("oh no!")
return
}
}
}
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include <stdio.h>
#include <stdbool.h>
void uselessFunc(int uselessParam) {
auto int i;
if (true) {
} else {
printf("Never called\n");
}
for (i = 0; i < 0; ++i) {
printf("Never called\n");
}
while (false) {
printf("Never called\n");
}
printf("");
return;
}
struct UselessStruct {
};
int main() {
uselessFunc(0);
printf("Working OK.\n");
}
| package main
import (
"fmt"
)
type any = interface{}
func uselessFunc(uselessParam any) {
if true {
} else {
fmt.Println("Never called")
}
for range []any{} {
fmt.Println("Never called")
}
for false {
fmt.Println("Never called")
}
fmt.Print("")
return
}
type NotCompletelyUseless struct {
}
func main() {
uselessFunc(0)
set := make(map[int]NotCompletelyUseless)
set[0] = NotCompletelyUseless{}
set[0] = NotCompletelyUseless{}
fmt.Println(set)
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef struct{
double value;
double delta;
}imprecise;
#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value + b.value;
ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));
return ret;
}
imprecise imprecise_mul(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value * b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));
return ret;
}
imprecise imprecise_div(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value / b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);
return ret;
}
imprecise imprecise_pow(imprecise a, double c)
{
imprecise ret;
ret.value = pow(a.value, c);
ret.delta = fabs(ret.value * c * a.delta / a.value);
return ret;
}
char* printImprecise(imprecise val)
{
char principal[30],error[30],*string,sign[2];
sign[0] = 241;
sign[1] = 00;
sprintf(principal,"%f",val.value);
sprintf(error,"%f",val.delta);
string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));
strcpy(string,principal);
strcat(string,sign);
strcat(string,error);
return string;
}
int main(void) {
imprecise x1 = {100, 1.1};
imprecise y1 = {50, 1.2};
imprecise x2 = {-200, 2.2};
imprecise y2 = {-100, 2.3};
imprecise d;
d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);
printf("Distance, d, between the following points :");
printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1));
printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2));
printf("\nis d = %s", printImprecise(d));
return 0;
}
| package main
import (
"fmt"
"math"
)
type unc struct {
n float64
s float64
}
func newUnc(n, s float64) *unc {
return &unc{n, s * s}
}
func (z *unc) errorTerm() float64 {
return math.Sqrt(z.s)
}
func (z *unc) addC(a *unc, c float64) *unc {
*z = *a
z.n += c
return z
}
func (z *unc) subC(a *unc, c float64) *unc {
*z = *a
z.n -= c
return z
}
func (z *unc) addU(a, b *unc) *unc {
z.n = a.n + b.n
z.s = a.s + b.s
return z
}
func (z *unc) subU(a, b *unc) *unc {
z.n = a.n - b.n
z.s = a.s + b.s
return z
}
func (z *unc) mulC(a *unc, c float64) *unc {
z.n = a.n * c
z.s = a.s * c * c
return z
}
func (z *unc) divC(a *unc, c float64) *unc {
z.n = a.n / c
z.s = a.s / (c * c)
return z
}
func (z *unc) mulU(a, b *unc) *unc {
prod := a.n * b.n
z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
func (z *unc) divU(a, b *unc) *unc {
quot := a.n / b.n
z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
func (z *unc) expC(a *unc, c float64) *unc {
f := math.Pow(a.n, c)
g := f * c / a.n
z.n = f
z.s = a.s * g * g
return z
}
func main() {
x1 := newUnc(100, 1.1)
x2 := newUnc(200, 2.2)
y1 := newUnc(50, 1.2)
y2 := newUnc(100, 2.3)
var d, d2 unc
d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)
fmt.Println("d: ", d.n)
fmt.Println("error:", d.errorTerm())
}
|
Generate an equivalent Go version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
static char code[128] = { 0 };
void add_code(const char *s, int c)
{
while (*s) {
code[(int)*s] = code[0x20 ^ (int)*s] = c;
s++;
}
}
void init()
{
static const char *cls[] =
{ "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0};
int i;
for (i = 0; cls[i]; i++)
add_code(cls[i], i - 1);
}
const char* soundex(const char *s)
{
static char out[5];
int c, prev, i;
out[0] = out[4] = 0;
if (!s || !*s) return out;
out[0] = *s++;
prev = code[(int)out[0]];
for (i = 1; *s && i < 4; s++) {
if ((c = code[(int)*s]) == prev) continue;
if (c == -1) prev = 0;
else if (c > 0) {
out[i++] = c + '0';
prev = c;
}
}
while (i < 4) out[i++] = '0';
return out;
}
int main()
{
int i;
const char *sdx, *names[][2] = {
{"Soundex", "S532"},
{"Example", "E251"},
{"Sownteks", "S532"},
{"Ekzampul", "E251"},
{"Euler", "E460"},
{"Gauss", "G200"},
{"Hilbert", "H416"},
{"Knuth", "K530"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"Ellery", "E460"},
{"Ghosh", "G200"},
{"Heilbronn", "H416"},
{"Kant", "K530"},
{"Ladd", "L300"},
{"Lissajous", "L222"},
{"Wheaton", "W350"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"O'Hara", "O600"},
{"Washington", "W252"},
{"Lee", "L000"},
{"Gutierrez", "G362"},
{"Pfister", "P236"},
{"Jackson", "J250"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Ashcraft", "A261"},
{0, 0}
};
init();
puts(" Test name Code Got\n----------------------");
for (i = 0; names[i][0]; i++) {
sdx = soundex(names[i][0]);
printf("%11s %s %s ", names[i][0], names[i][1], sdx);
printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok");
}
return 0;
}
| package main
import (
"errors"
"fmt"
"unicode"
)
var code = []byte("01230127022455012623017202")
func soundex(s string) (string, error) {
var sx [4]byte
var sxi int
var cx, lastCode byte
for i, c := range s {
switch {
case !unicode.IsLetter(c):
if c < ' ' || c == 127 {
return "", errors.New("ASCII control characters disallowed")
}
if i == 0 {
return "", errors.New("initial character must be a letter")
}
lastCode = '0'
continue
case c >= 'A' && c <= 'Z':
cx = byte(c - 'A')
case c >= 'a' && c <= 'z':
cx = byte(c - 'a')
default:
return "", errors.New("non-ASCII letters unsupported")
}
if i == 0 {
sx[0] = cx + 'A'
sxi = 1
continue
}
switch x := code[cx]; x {
case '7', lastCode:
case '0':
lastCode = '0'
default:
sx[sxi] = x
if sxi == 3 {
return string(sx[:]), nil
}
sxi++
lastCode = x
}
}
if sxi == 0 {
return "", errors.New("no letters present")
}
for ; sxi < 4; sxi++ {
sx[sxi] = '0'
}
return string(sx[:]), nil
}
func main() {
for _, s := range []string{
"Robert",
"Rupert",
"Rubin",
"ashcroft",
"ashcraft",
"moses",
"O'Mally",
"d jay",
"R2-D2",
"12p2",
"naïve",
"",
"bump\t",
} {
if x, err := soundex(s); err == nil {
fmt.Println("soundex", s, "=", x)
} else {
fmt.Printf("\"%s\" fail. %s\n", s, err)
}
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))
tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};
void append(tree t)
{
if (len == cap) {
cap = cap ? cap*2 : 2;
list = realloc(list, cap*sizeof(tree));
}
list[len++] = 1 | t<<1;
}
void show(tree t, uint len)
{
for (; len--; t >>= 1)
putchar(t&1 ? '(' : ')');
}
void listtrees(uint n)
{
uint i;
for (i = offset[n]; i < offset[n+1]; i++) {
show(list[i], n*2);
putchar('\n');
}
}
void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
if (!rem) {
append(t);
return;
}
if (sl > rem)
pos = offset[sl = rem];
else if (pos >= offset[sl + 1]) {
if (!--sl) return;
pos = offset[sl];
}
assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
assemble(n, t, sl, pos + 1, rem);
}
void mktrees(uint n)
{
if (offset[n + 1]) return;
if (n) mktrees(n - 1);
assemble(n, 0, n-1, offset[n-1], n-1);
offset[n+1] = len;
}
int main(int c, char**v)
{
int n;
if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;
append(0);
mktrees((uint)n);
fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
listtrees((uint)n);
return 0;
}
| package main
import (
"fmt"
"log"
"os"
"strconv"
)
type tree uint64
var (
list []tree
offset = [32]uint{1: 1}
)
func add(t tree) {
list = append(list, 1|t<<1)
}
func show(t tree, l uint) {
for ; l > 0; t >>= 1 {
l--
var paren byte
if (t & 1) != 0 {
paren = '('
} else {
paren = ')'
}
fmt.Printf("%c", paren)
}
}
func listTrees(n uint) {
for i := offset[n]; i < offset[n+1]; i++ {
show(list[i], n*2)
fmt.Println()
}
}
func assemble(n uint, t tree, sl, pos, rem uint) {
if rem == 0 {
add(t)
return
}
if sl > rem {
sl = rem
pos = offset[sl]
} else if pos >= offset[sl+1] {
sl--
if sl == 0 {
return
}
pos = offset[sl]
}
assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)
assemble(n, t, sl, pos+1, rem)
}
func mktrees(n uint) {
if offset[n+1] > 0 {
return
}
if n > 0 {
mktrees(n - 1)
}
assemble(n, 0, n-1, offset[n-1], n-1)
offset[n+1] = uint(len(list))
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There must be exactly 1 command line argument")
}
n, err := strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal("Argument is not a valid number")
}
if n <= 0 || n > 19 {
n = 5
}
add(0)
mktrees(uint(n))
fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n])
listTrees(uint(n))
}
|
Ensure the translated Go code behaves exactly like the original C snippet. |
int add(int a, int b) {
return a + b;
}
|
package example
var (
X, Y, Z int
)
func XP() {
}
func nonXP() {}
var MEMEME int
|
Write a version of this C function in Go with identical behavior. | #include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
sqlite3 *db = NULL;
char *errmsg;
const char *code =
"CREATE TABLE employee (\n"
" empID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" firstName TEXT NOT NULL,\n"
" lastName TEXT NOT NULL,\n"
" AGE INTEGER NOT NULL,\n"
" DOB DATE NOT NULL)\n" ;
if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
sqlite3_exec(db, code, NULL, NULL, &errmsg);
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return 0;
}
| package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"log"
)
type StockTrans struct {
Id int
Date string
Trans string
Symbol string
Quantity int
Price float32
Settled bool
}
func (st *StockTrans) save(db *bolt.DB, bucket string) error {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
id, _ := b.NextSequence()
st.Id = int(id)
encoded, err := json.Marshal(st)
if err != nil {
return err
}
return b.Put(itob(st.Id), encoded)
})
return err
}
func itob(i int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(i))
return b
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
db, err := bolt.Open("store.db", 0600, nil)
check(err)
defer db.Close()
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("stocks"))
return err
})
check(err)
transactions := []*StockTrans{
{0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true},
{0, "2006-03-28", "BUY", "IBM", 1000, 45, true},
{0, "2006-04-06", "SELL", "IBM", 500, 53, true},
{0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false},
}
for _, trans := range transactions {
err := trans.save(db, "stocks")
check(err)
}
fmt.Println("Id Date Trans Sym Qty Price Settled")
fmt.Println("------------------------------------------------")
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("stocks"))
b.ForEach(func(k, v []byte) error {
st := new(StockTrans)
err := json.Unmarshal(v, st)
check(err)
fmt.Printf("%d %s %-4s %-5s %4d %2.2f %t\n",
st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)
return nil
})
return nil
})
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
sqlite3 *db = NULL;
char *errmsg;
const char *code =
"CREATE TABLE employee (\n"
" empID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" firstName TEXT NOT NULL,\n"
" lastName TEXT NOT NULL,\n"
" AGE INTEGER NOT NULL,\n"
" DOB DATE NOT NULL)\n" ;
if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
sqlite3_exec(db, code, NULL, NULL, &errmsg);
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return 0;
}
| package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"log"
)
type StockTrans struct {
Id int
Date string
Trans string
Symbol string
Quantity int
Price float32
Settled bool
}
func (st *StockTrans) save(db *bolt.DB, bucket string) error {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
id, _ := b.NextSequence()
st.Id = int(id)
encoded, err := json.Marshal(st)
if err != nil {
return err
}
return b.Put(itob(st.Id), encoded)
})
return err
}
func itob(i int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(i))
return b
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
db, err := bolt.Open("store.db", 0600, nil)
check(err)
defer db.Close()
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("stocks"))
return err
})
check(err)
transactions := []*StockTrans{
{0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true},
{0, "2006-03-28", "BUY", "IBM", 1000, 45, true},
{0, "2006-04-06", "SELL", "IBM", 500, 53, true},
{0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false},
}
for _, trans := range transactions {
err := trans.save(db, "stocks")
check(err)
}
fmt.Println("Id Date Trans Sym Qty Price Settled")
fmt.Println("------------------------------------------------")
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("stocks"))
b.ForEach(func(k, v []byte) error {
st := new(StockTrans)
err := json.Unmarshal(v, st)
check(err)
fmt.Printf("%d %s %-4s %-5s %4d %2.2f %t\n",
st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)
return nil
})
return nil
})
}
|
Write the same algorithm in Go as shown in this C implementation. | #include <stdio.h>
#include <tgmath.h>
#define VERBOSE 0
#define for3 for(int i = 0; i < 3; i++)
typedef complex double vec;
typedef struct { vec c; double r; } circ;
#define re(x) creal(x)
#define im(x) cimag(x)
#define cp(x) re(x), im(x)
#define CPLX "(%6.3f,%6.3f)"
#define CPLX3 CPLX" "CPLX" "CPLX
double cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }
double abs2(vec a) { return a * conj(a); }
int apollonius_in(circ aa[], int ss[], int flip, int divert)
{
vec n[3], x[3], t[3], a, b, center;
int s[3], iter = 0, res = 0;
double diff = 1, diff_old = -1, axb, d, r;
for3 {
s[i] = ss[i] ? 1 : -1;
x[i] = aa[i].c;
}
while (diff > 1e-20) {
a = x[0] - x[2], b = x[1] - x[2];
diff = 0;
axb = -cross(a, b);
d = sqrt(abs2(a) * abs2(b) * abs2(a - b));
if (VERBOSE) {
const char *z = 1 + "-0+";
printf("%c%c%c|%c%c|",
z[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);
printf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));
}
r = fabs(d / (2 * axb));
center = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];
if (!axb && flip != -1 && !divert) {
if (!d) {
printf("Given conditions confused me.\n");
return 0;
}
if (VERBOSE) puts("\n[divert]");
divert = 1;
res = apollonius_in(aa, ss, -1, 1);
}
for3 n[i] = axb ? aa[i].c - center : a * I * flip;
for3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];
for3 diff += abs2(t[i] - x[i]), x[i] = t[i];
if (VERBOSE) printf(" %g\n", diff);
if (diff >= diff_old && diff_old >= 0)
if (iter++ > 20) return res;
diff_old = diff;
}
printf("found: ");
if (axb) printf("circle "CPLX", r = %f\n", cp(center), r);
else printf("line "CPLX3"\n", cp(x[0]), cp(x[1]), cp(x[2]));
return res + 1;
}
int apollonius(circ aa[])
{
int s[3], i, sum = 0;
for (i = 0; i < 8; i++) {
s[0] = i & 1, s[1] = i & 2, s[2] = i & 4;
if (s[0] && !aa[0].r) continue;
if (s[1] && !aa[1].r) continue;
if (s[2] && !aa[2].r) continue;
sum += apollonius_in(aa, s, 1, 0);
}
return sum;
}
int main()
{
circ a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};
circ b[3] = {{-3, 2}, {0, 1}, {3, 2}};
circ c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};
puts("set 1"); apollonius(a);
puts("set 2"); apollonius(b);
puts("set 3"); apollonius(c);
}
| package main
import (
"fmt"
"math"
)
type circle struct {
x, y, r float64
}
func main() {
c1 := circle{0, 0, 1}
c2 := circle{4, 0, 1}
c3 := circle{2, 4, 2}
fmt.Println(ap(c1, c2, c3, true))
fmt.Println(ap(c1, c2, c3, false))
}
func ap(c1, c2, c3 circle, s bool) circle {
x1sq := c1.x * c1.x
y1sq := c1.y * c1.y
r1sq := c1.r * c1.r
x2sq := c2.x * c2.x
y2sq := c2.y * c2.y
r2sq := c2.r * c2.r
x3sq := c3.x * c3.x
y3sq := c3.y * c3.y
r3sq := c3.r * c3.r
v11 := 2 * (c2.x - c1.x)
v12 := 2 * (c2.y - c1.y)
v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq
v14 := 2 * (c2.r - c1.r)
v21 := 2 * (c3.x - c2.x)
v22 := 2 * (c3.y - c2.y)
v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq
v24 := 2 * (c3.r - c2.r)
if s {
v14 = -v14
v24 = -v24
}
w12 := v12 / v11
w13 := v13 / v11
w14 := v14 / v11
w22 := v22/v21 - w12
w23 := v23/v21 - w13
w24 := v24/v21 - w14
p := -w23 / w22
q := w24 / w22
m := -w12*p - w13
n := w14 - w12*q
a := n*n + q*q - 1
b := m*n - n*c1.x + p*q - q*c1.y
if s {
b -= c1.r
} else {
b += c1.r
}
b *= 2
c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq
d := b*b - 4*a*c
rs := (-b - math.Sqrt(d)) / (2 * a)
return circle{m + n*rs, p + q*rs, rs}
}
|
Port the provided C code into Go while preserving the original functionality. | #include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int line_len = 5;
int disjoint = 0;
int **board = 0, width, height;
#define for_i for(i = 0; i < height; i++)
#define for_j for(j = 0; j < width; j++)
enum {
s_blank = 0,
s_occupied = 1 << 0,
s_dir_ns = 1 << 1,
s_dir_ew = 1 << 2,
s_dir_ne_sw = 1 << 3,
s_dir_nw_se = 1 << 4,
s_newly_added = 1 << 5,
s_current = 1 << 6,
};
int irand(int n)
{
int r, rand_max = RAND_MAX - (RAND_MAX % n);
while ((r = rand()) >= rand_max);
return r / (rand_max / n);
}
int** alloc_board(int w, int h)
{
int i;
int **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);
buf[0] = (int*)(buf + h);
for (i = 1; i < h; i++)
buf[i] = buf[i - 1] + w;
return buf;
}
void expand_board(int dw, int dh)
{
int i, j;
int nw = width + !!dw, nh = height + !!dh;
int **nbuf = alloc_board(nw, nh);
dw = -(dw < 0), dh = -(dh < 0);
for (i = 0; i < nh; i++) {
if (i + dh < 0 || i + dh >= height) continue;
for (j = 0; j < nw; j++) {
if (j + dw < 0 || j + dw >= width) continue;
nbuf[i][j] = board[i + dh][j + dw];
}
}
free(board);
board = nbuf;
width = nw;
height = nh;
}
void array_set(int **buf, int v, int x0, int y0, int x1, int y1)
{
int i, j;
for (i = y0; i <= y1; i++)
for (j = x0; j <= x1; j++)
buf[i][j] = v;
}
void show_board()
{
int i, j;
for_i for_j mvprintw(i + 1, j * 2,
(board[i][j] & s_current) ? "X "
: (board[i][j] & s_newly_added) ? "O "
: (board[i][j] & s_occupied) ? "+ " : " ");
refresh();
}
void init_board()
{
width = height = 3 * (line_len - 1);
board = alloc_board(width, height);
array_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);
array_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);
array_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);
array_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);
}
int ofs[4][3] = {
{0, 1, s_dir_ns},
{1, 0, s_dir_ew},
{1, -1, s_dir_ne_sw},
{1, 1, s_dir_nw_se}
};
typedef struct { int m, s, seq, x, y; } move_t;
void test_postion(int y, int x, move_t * rec)
{
int m, k, s, dx, dy, xx, yy, dir;
if (board[y][x] & s_occupied) return;
for (m = 0; m < 4; m++) {
dx = ofs[m][0];
dy = ofs[m][1];
dir = ofs[m][2];
for (s = 1 - line_len; s <= 0; s++) {
for (k = 0; k < line_len; k++) {
if (s + k == 0) continue;
xx = x + dx * (s + k);
yy = y + dy * (s + k);
if (xx < 0 || xx >= width || yy < 0 || yy >= height)
break;
if (!(board[yy][xx] & s_occupied)) break;
if ((board[yy][xx] & dir)) break;
}
if (k != line_len) continue;
if (! irand(++rec->seq))
rec->m = m, rec->s = s, rec->x = x, rec->y = y;
}
}
}
void add_piece(move_t *rec) {
int dx = ofs[rec->m][0];
int dy = ofs[rec->m][1];
int dir= ofs[rec->m][2];
int xx, yy, k;
board[rec->y][rec->x] |= (s_current | s_occupied);
for (k = 0; k < line_len; k++) {
xx = rec->x + dx * (k + rec->s);
yy = rec->y + dy * (k + rec->s);
board[yy][xx] |= s_newly_added;
if (k >= disjoint || k < line_len - disjoint)
board[yy][xx] |= dir;
}
}
int next_move()
{
int i, j;
move_t rec;
rec.seq = 0;
for_i for_j board[i][j] &= ~(s_newly_added | s_current);
for_i for_j test_postion(i, j, &rec);
if (!rec.seq) return 0;
add_piece(&rec);
rec.x = (rec.x == width - 1) ? 1 : rec.x ? 0 : -1;
rec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;
if (rec.x || rec.y) expand_board(rec.x, rec.y);
return 1;
}
int main()
{
int ch = 0;
int move = 0;
int wait_key = 1;
init_board();
srand(time(0));
initscr();
noecho();
cbreak();
do {
mvprintw(0, 0, "Move %d", move++);
show_board();
if (!next_move()) {
next_move();
show_board();
break;
}
if (!wait_key) usleep(100000);
if ((ch = getch()) == ' ') {
wait_key = !wait_key;
if (wait_key) timeout(-1);
else timeout(0);
}
} while (ch != 'q');
timeout(-1);
nocbreak();
echo();
endwin();
return 0;
}
| package main
import (
gc "github.com/rthornton128/goncurses"
"log"
"math/rand"
"time"
)
const (
lineLen = 5
disjoint = 0
)
var (
board [][]int
width int
height int
)
const (
blank = 0
occupied = 1 << (iota - 1)
dirNS
dirEW
dirNESW
dirNWSE
newlyAdded
current
)
var ofs = [4][3]int{
{0, 1, dirNS},
{1, 0, dirEW},
{1, -1, dirNESW},
{1, 1, dirNWSE},
}
type move struct{ m, s, seq, x, y int }
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func allocBoard(w, h int) [][]int {
buf := make([][]int, h)
for i := 0; i < h; i++ {
buf[i] = make([]int, w)
}
return buf
}
func boardSet(v, x0, y0, x1, y1 int) {
for i := y0; i <= y1; i++ {
for j := x0; j <= x1; j++ {
board[i][j] = v
}
}
}
func initBoard() {
height = 3 * (lineLen - 1)
width = height
board = allocBoard(width, height)
boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)
boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)
boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)
boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)
}
func expandBoard(dw, dh int) {
dw2, dh2 := 1, 1
if dw == 0 {
dw2 = 0
}
if dh == 0 {
dh2 = 0
}
nw, nh := width+dw2, height+dh2
nbuf := allocBoard(nw, nh)
dw, dh = -btoi(dw < 0), -btoi(dh < 0)
for i := 0; i < nh; i++ {
if i+dh < 0 || i+dh >= height {
continue
}
for j := 0; j < nw; j++ {
if j+dw < 0 || j+dw >= width {
continue
}
nbuf[i][j] = board[i+dh][j+dw]
}
}
board = nbuf
width, height = nw, nh
}
func showBoard(scr *gc.Window) {
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
var temp string
switch {
case (board[i][j] & current) != 0:
temp = "X "
case (board[i][j] & newlyAdded) != 0:
temp = "0 "
case (board[i][j] & occupied) != 0:
temp = "+ "
default:
temp = " "
}
scr.MovePrintf(i+1, j*2, temp)
}
}
scr.Refresh()
}
func testPosition(y, x int, rec *move) {
if (board[y][x] & occupied) != 0 {
return
}
for m := 0; m < 4; m++ {
dx := ofs[m][0]
dy := ofs[m][1]
dir := ofs[m][2]
var k int
for s := 1 - lineLen; s <= 0; s++ {
for k = 0; k < lineLen; k++ {
if s+k == 0 {
continue
}
xx := x + dx*(s+k)
yy := y + dy*(s+k)
if xx < 0 || xx >= width || yy < 0 || yy >= height {
break
}
if (board[yy][xx] & occupied) == 0 {
break
}
if (board[yy][xx] & dir) != 0 {
break
}
}
if k != lineLen {
continue
}
rec.seq++
if rand.Intn(rec.seq) == 0 {
rec.m, rec.s, rec.x, rec.y = m, s, x, y
}
}
}
}
func addPiece(rec *move) {
dx := ofs[rec.m][0]
dy := ofs[rec.m][1]
dir := ofs[rec.m][2]
board[rec.y][rec.x] |= current | occupied
for k := 0; k < lineLen; k++ {
xx := rec.x + dx*(k+rec.s)
yy := rec.y + dy*(k+rec.s)
board[yy][xx] |= newlyAdded
if k >= disjoint || k < lineLen-disjoint {
board[yy][xx] |= dir
}
}
}
func nextMove() bool {
var rec move
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
board[i][j] &^= newlyAdded | current
}
}
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
testPosition(i, j, &rec)
}
}
if rec.seq == 0 {
return false
}
addPiece(&rec)
if rec.x == width-1 {
rec.x = 1
} else if rec.x != 0 {
rec.x = 0
} else {
rec.x = -1
}
if rec.y == height-1 {
rec.y = 1
} else if rec.y != 0 {
rec.y = 0
} else {
rec.y = -1
}
if rec.x != 0 || rec.y != 0 {
expandBoard(rec.x, rec.y)
}
return true
}
func main() {
rand.Seed(time.Now().UnixNano())
initBoard()
scr, err := gc.Init()
if err != nil {
log.Fatal("init", err)
}
defer gc.End()
gc.Echo(false)
gc.CBreak(true)
ch := gc.Key(0)
move := 0
waitKey := true
for {
scr.MovePrintf(0, 0, "Move %d", move)
move++
showBoard(scr)
if !nextMove() {
nextMove()
showBoard(scr)
break
}
if !waitKey {
time.Sleep(100000 * time.Microsecond)
}
if ch = scr.GetChar(); ch == ' ' {
waitKey = !waitKey
if waitKey {
scr.Timeout(-1)
} else {
scr.Timeout(0)
}
}
if ch == 'q' {
break
}
}
scr.Timeout(-1)
gc.CBreak(false)
gc.Echo(true)
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int line_len = 5;
int disjoint = 0;
int **board = 0, width, height;
#define for_i for(i = 0; i < height; i++)
#define for_j for(j = 0; j < width; j++)
enum {
s_blank = 0,
s_occupied = 1 << 0,
s_dir_ns = 1 << 1,
s_dir_ew = 1 << 2,
s_dir_ne_sw = 1 << 3,
s_dir_nw_se = 1 << 4,
s_newly_added = 1 << 5,
s_current = 1 << 6,
};
int irand(int n)
{
int r, rand_max = RAND_MAX - (RAND_MAX % n);
while ((r = rand()) >= rand_max);
return r / (rand_max / n);
}
int** alloc_board(int w, int h)
{
int i;
int **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);
buf[0] = (int*)(buf + h);
for (i = 1; i < h; i++)
buf[i] = buf[i - 1] + w;
return buf;
}
void expand_board(int dw, int dh)
{
int i, j;
int nw = width + !!dw, nh = height + !!dh;
int **nbuf = alloc_board(nw, nh);
dw = -(dw < 0), dh = -(dh < 0);
for (i = 0; i < nh; i++) {
if (i + dh < 0 || i + dh >= height) continue;
for (j = 0; j < nw; j++) {
if (j + dw < 0 || j + dw >= width) continue;
nbuf[i][j] = board[i + dh][j + dw];
}
}
free(board);
board = nbuf;
width = nw;
height = nh;
}
void array_set(int **buf, int v, int x0, int y0, int x1, int y1)
{
int i, j;
for (i = y0; i <= y1; i++)
for (j = x0; j <= x1; j++)
buf[i][j] = v;
}
void show_board()
{
int i, j;
for_i for_j mvprintw(i + 1, j * 2,
(board[i][j] & s_current) ? "X "
: (board[i][j] & s_newly_added) ? "O "
: (board[i][j] & s_occupied) ? "+ " : " ");
refresh();
}
void init_board()
{
width = height = 3 * (line_len - 1);
board = alloc_board(width, height);
array_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);
array_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);
array_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);
array_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);
}
int ofs[4][3] = {
{0, 1, s_dir_ns},
{1, 0, s_dir_ew},
{1, -1, s_dir_ne_sw},
{1, 1, s_dir_nw_se}
};
typedef struct { int m, s, seq, x, y; } move_t;
void test_postion(int y, int x, move_t * rec)
{
int m, k, s, dx, dy, xx, yy, dir;
if (board[y][x] & s_occupied) return;
for (m = 0; m < 4; m++) {
dx = ofs[m][0];
dy = ofs[m][1];
dir = ofs[m][2];
for (s = 1 - line_len; s <= 0; s++) {
for (k = 0; k < line_len; k++) {
if (s + k == 0) continue;
xx = x + dx * (s + k);
yy = y + dy * (s + k);
if (xx < 0 || xx >= width || yy < 0 || yy >= height)
break;
if (!(board[yy][xx] & s_occupied)) break;
if ((board[yy][xx] & dir)) break;
}
if (k != line_len) continue;
if (! irand(++rec->seq))
rec->m = m, rec->s = s, rec->x = x, rec->y = y;
}
}
}
void add_piece(move_t *rec) {
int dx = ofs[rec->m][0];
int dy = ofs[rec->m][1];
int dir= ofs[rec->m][2];
int xx, yy, k;
board[rec->y][rec->x] |= (s_current | s_occupied);
for (k = 0; k < line_len; k++) {
xx = rec->x + dx * (k + rec->s);
yy = rec->y + dy * (k + rec->s);
board[yy][xx] |= s_newly_added;
if (k >= disjoint || k < line_len - disjoint)
board[yy][xx] |= dir;
}
}
int next_move()
{
int i, j;
move_t rec;
rec.seq = 0;
for_i for_j board[i][j] &= ~(s_newly_added | s_current);
for_i for_j test_postion(i, j, &rec);
if (!rec.seq) return 0;
add_piece(&rec);
rec.x = (rec.x == width - 1) ? 1 : rec.x ? 0 : -1;
rec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;
if (rec.x || rec.y) expand_board(rec.x, rec.y);
return 1;
}
int main()
{
int ch = 0;
int move = 0;
int wait_key = 1;
init_board();
srand(time(0));
initscr();
noecho();
cbreak();
do {
mvprintw(0, 0, "Move %d", move++);
show_board();
if (!next_move()) {
next_move();
show_board();
break;
}
if (!wait_key) usleep(100000);
if ((ch = getch()) == ' ') {
wait_key = !wait_key;
if (wait_key) timeout(-1);
else timeout(0);
}
} while (ch != 'q');
timeout(-1);
nocbreak();
echo();
endwin();
return 0;
}
| package main
import (
gc "github.com/rthornton128/goncurses"
"log"
"math/rand"
"time"
)
const (
lineLen = 5
disjoint = 0
)
var (
board [][]int
width int
height int
)
const (
blank = 0
occupied = 1 << (iota - 1)
dirNS
dirEW
dirNESW
dirNWSE
newlyAdded
current
)
var ofs = [4][3]int{
{0, 1, dirNS},
{1, 0, dirEW},
{1, -1, dirNESW},
{1, 1, dirNWSE},
}
type move struct{ m, s, seq, x, y int }
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func allocBoard(w, h int) [][]int {
buf := make([][]int, h)
for i := 0; i < h; i++ {
buf[i] = make([]int, w)
}
return buf
}
func boardSet(v, x0, y0, x1, y1 int) {
for i := y0; i <= y1; i++ {
for j := x0; j <= x1; j++ {
board[i][j] = v
}
}
}
func initBoard() {
height = 3 * (lineLen - 1)
width = height
board = allocBoard(width, height)
boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)
boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)
boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)
boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)
}
func expandBoard(dw, dh int) {
dw2, dh2 := 1, 1
if dw == 0 {
dw2 = 0
}
if dh == 0 {
dh2 = 0
}
nw, nh := width+dw2, height+dh2
nbuf := allocBoard(nw, nh)
dw, dh = -btoi(dw < 0), -btoi(dh < 0)
for i := 0; i < nh; i++ {
if i+dh < 0 || i+dh >= height {
continue
}
for j := 0; j < nw; j++ {
if j+dw < 0 || j+dw >= width {
continue
}
nbuf[i][j] = board[i+dh][j+dw]
}
}
board = nbuf
width, height = nw, nh
}
func showBoard(scr *gc.Window) {
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
var temp string
switch {
case (board[i][j] & current) != 0:
temp = "X "
case (board[i][j] & newlyAdded) != 0:
temp = "0 "
case (board[i][j] & occupied) != 0:
temp = "+ "
default:
temp = " "
}
scr.MovePrintf(i+1, j*2, temp)
}
}
scr.Refresh()
}
func testPosition(y, x int, rec *move) {
if (board[y][x] & occupied) != 0 {
return
}
for m := 0; m < 4; m++ {
dx := ofs[m][0]
dy := ofs[m][1]
dir := ofs[m][2]
var k int
for s := 1 - lineLen; s <= 0; s++ {
for k = 0; k < lineLen; k++ {
if s+k == 0 {
continue
}
xx := x + dx*(s+k)
yy := y + dy*(s+k)
if xx < 0 || xx >= width || yy < 0 || yy >= height {
break
}
if (board[yy][xx] & occupied) == 0 {
break
}
if (board[yy][xx] & dir) != 0 {
break
}
}
if k != lineLen {
continue
}
rec.seq++
if rand.Intn(rec.seq) == 0 {
rec.m, rec.s, rec.x, rec.y = m, s, x, y
}
}
}
}
func addPiece(rec *move) {
dx := ofs[rec.m][0]
dy := ofs[rec.m][1]
dir := ofs[rec.m][2]
board[rec.y][rec.x] |= current | occupied
for k := 0; k < lineLen; k++ {
xx := rec.x + dx*(k+rec.s)
yy := rec.y + dy*(k+rec.s)
board[yy][xx] |= newlyAdded
if k >= disjoint || k < lineLen-disjoint {
board[yy][xx] |= dir
}
}
}
func nextMove() bool {
var rec move
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
board[i][j] &^= newlyAdded | current
}
}
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
testPosition(i, j, &rec)
}
}
if rec.seq == 0 {
return false
}
addPiece(&rec)
if rec.x == width-1 {
rec.x = 1
} else if rec.x != 0 {
rec.x = 0
} else {
rec.x = -1
}
if rec.y == height-1 {
rec.y = 1
} else if rec.y != 0 {
rec.y = 0
} else {
rec.y = -1
}
if rec.x != 0 || rec.y != 0 {
expandBoard(rec.x, rec.y)
}
return true
}
func main() {
rand.Seed(time.Now().UnixNano())
initBoard()
scr, err := gc.Init()
if err != nil {
log.Fatal("init", err)
}
defer gc.End()
gc.Echo(false)
gc.CBreak(true)
ch := gc.Key(0)
move := 0
waitKey := true
for {
scr.MovePrintf(0, 0, "Move %d", move)
move++
showBoard(scr)
if !nextMove() {
nextMove()
showBoard(scr)
break
}
if !waitKey {
time.Sleep(100000 * time.Microsecond)
}
if ch = scr.GetChar(); ch == ' ' {
waitKey = !waitKey
if waitKey {
scr.Timeout(-1)
} else {
scr.Timeout(0)
}
}
if ch == 'q' {
break
}
}
scr.Timeout(-1)
gc.CBreak(false)
gc.Echo(true)
}
|
Write the same algorithm in Go as shown in this C implementation. | #include<stdio.h>
#include<stdlib.h>
int main(void) {
int list[3][9], i;
for(i=0;i<27;i++) list[i/9][i%9]=1+i;
for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] );
return 0;
}
| package main
import "fmt"
func main() {
list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}
list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}
var list [9]int
for i := 0; i < 9; i++ {
list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]
}
fmt.Println(list)
}
|
Produce a language-to-language conversion: from C to Go, same semantics. | #include<stdio.h>
#include<stdlib.h>
int main(void) {
int list[3][9], i;
for(i=0;i<27;i++) list[i/9][i%9]=1+i;
for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] );
return 0;
}
| package main
import "fmt"
func main() {
list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}
list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}
var list [9]int
for i := 0; i < 9; i++ {
list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]
}
fmt.Println(list)
}
|
Produce a functionally identical Go code for the snippet given in C. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node_t {
char *elem;
int length;
struct node_t *next;
} node;
node *make_node(char *s) {
node *t = malloc(sizeof(node));
t->elem = s;
t->length = strlen(s);
t->next = NULL;
return t;
}
void append_node(node *head, node *elem) {
while (head->next != NULL) {
head = head->next;
}
head->next = elem;
}
void print_node(node *n) {
putc('[', stdout);
while (n != NULL) {
printf("`%s` ", n->elem);
n = n->next;
}
putc(']', stdout);
}
char *lcs(node *list) {
int minLen = INT_MAX;
int i;
char *res;
node *ptr;
if (list == NULL) {
return "";
}
if (list->next == NULL) {
return list->elem;
}
for (ptr = list; ptr != NULL; ptr = ptr->next) {
minLen = min(minLen, ptr->length);
}
if (minLen == 0) {
return "";
}
res = "";
for (i = 1; i < minLen; i++) {
char *suffix = &list->elem[list->length - i];
for (ptr = list->next; ptr != NULL; ptr = ptr->next) {
char *e = &ptr->elem[ptr->length - i];
if (strcmp(suffix, e) != 0) {
return res;
}
}
res = suffix;
}
return res;
}
void test(node *n) {
print_node(n);
printf(" -> `%s`\n", lcs(n));
}
void case1() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbabc"));
test(n);
}
void case2() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbazc"));
test(n);
}
void case3() {
node *n = make_node("Sunday");
append_node(n, make_node("Monday"));
append_node(n, make_node("Tuesday"));
append_node(n, make_node("Wednesday"));
append_node(n, make_node("Thursday"));
append_node(n, make_node("Friday"));
append_node(n, make_node("Saturday"));
test(n);
}
void case4() {
node *n = make_node("longest");
append_node(n, make_node("common"));
append_node(n, make_node("suffix"));
test(n);
}
void case5() {
node *n = make_node("suffix");
test(n);
}
void case6() {
node *n = make_node("");
test(n);
}
int main() {
case1();
case2();
case3();
case4();
case5();
case6();
return 0;
}
| package main
import (
"fmt"
"strings"
)
func lcs(a []string) string {
le := len(a)
if le == 0 {
return ""
}
if le == 1 {
return a[0]
}
le0 := len(a[0])
minLen := le0
for i := 1; i < le; i++ {
if len(a[i]) < minLen {
minLen = len(a[i])
}
}
if minLen == 0 {
return ""
}
res := ""
a1 := a[1:]
for i := 1; i <= minLen; i++ {
suffix := a[0][le0-i:]
for _, e := range a1 {
if !strings.HasSuffix(e, suffix) {
return res
}
}
res = suffix
}
return res
}
func main() {
tests := [][]string{
{"baabababc", "baabc", "bbbabc"},
{"baabababc", "baabc", "bbbazc"},
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
{"longest", "common", "suffix"},
{"suffix"},
{""},
}
for _, test := range tests {
fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
}
}
|
Generate a Go translation of this C snippet without changing its computational steps. | #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h>
int tsocket;
struct sockaddr_in tsockinfo;
fd_set status, current;
void ClientText(int handle, char *buf, int buf_len);
struct client
{
char buffer[4096];
int pos;
char name[32];
} *connections[FD_SETSIZE];
void AddConnection(int handle)
{
connections[handle] = malloc(sizeof(struct client));
connections[handle]->buffer[0] = '\0';
connections[handle]->pos = 0;
connections[handle]->name[0] = '\0';
}
void CloseConnection(int handle)
{
char buf[512];
int j;
FD_CLR(handle, &status);
if (connections[handle]->name[0])
{
sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name);
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, buf, strlen(buf)) < 0)
{
CloseConnection(j);
}
}
}
} else
{
printf ("-- Connection %d disconnected\n", handle);
}
if (connections[handle])
{
free(connections[handle]);
}
close(handle);
}
void strip(char *buf)
{
char *x;
x = strchr(buf, '\n');
if (x) { *x='\0'; }
x = strchr(buf, '\r');
if (x) { *x='\0'; }
}
int RelayText(int handle)
{
char *begin, *end;
int ret = 0;
begin = connections[handle]->buffer;
if (connections[handle]->pos == 4000)
{
if (begin[3999] != '\n')
begin[4000] = '\0';
else {
begin[4000] = '\n';
begin[4001] = '\0';
}
} else {
begin[connections[handle]->pos] = '\0';
}
end = strchr(begin, '\n');
while (end != NULL)
{
char output[8000];
output[0] = '\0';
if (!connections[handle]->name[0])
{
strncpy(connections[handle]->name, begin, 31);
connections[handle]->name[31] = '\0';
strip(connections[handle]->name);
sprintf(output, "* Connected: %s\r\n", connections[handle]->name);
ret = 1;
} else
{
sprintf(output, "%s: %.*s\r\n", connections[handle]->name,
end-begin, begin);
ret = 1;
}
if (output[0])
{
int j;
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, output, strlen(output)) < 0)
{
CloseConnection(j);
}
}
}
}
begin = end+1;
end = strchr(begin, '\n');
}
strcpy(connections[handle]->buffer, begin);
connections[handle]->pos -= begin - connections[handle]->buffer;
return ret;
}
void ClientText(int handle, char *buf, int buf_len)
{
int i, j;
if (!connections[handle])
return;
j = connections[handle]->pos;
for (i = 0; i < buf_len; ++i, ++j)
{
connections[handle]->buffer[j] = buf[i];
if (j == 4000)
{
while (RelayText(handle));
j = connections[handle]->pos;
}
}
connections[handle]->pos = j;
while (RelayText(handle));
}
int ChatLoop()
{
int i, j;
FD_ZERO(&status);
FD_SET(tsocket, &status);
FD_SET(0, &status);
while(1)
{
current = status;
if (select(FD_SETSIZE, ¤t, NULL, NULL, NULL)==-1)
{
perror("Select");
return 0;
}
for (i = 0; i < FD_SETSIZE; ++i)
{
if (FD_ISSET(i, ¤t))
{
if (i == tsocket)
{
struct sockaddr_in cliinfo;
socklen_t addrlen = sizeof(cliinfo);
int handle;
handle = accept(tsocket, &cliinfo, &addrlen);
if (handle == -1)
{
perror ("Couldn't accept connection");
} else if (handle > FD_SETSIZE)
{
printf ("Unable to accept new connection.\n");
close(handle);
}
else
{
if (write(handle, "Enter name: ", 12) >= 0)
{
printf("-- New connection %d from %s:%hu\n",
handle,
inet_ntoa (cliinfo.sin_addr),
ntohs(cliinfo.sin_port));
FD_SET(handle, &status);
AddConnection(handle);
}
}
}
else
{
char buf[512];
int b;
b = read(i, buf, 500);
if (b <= 0)
{
CloseConnection(i);
}
else
{
ClientText(i, buf, b);
}
}
}
}
}
}
int main (int argc, char*argv[])
{
tsocket = socket(PF_INET, SOCK_STREAM, 0);
tsockinfo.sin_family = AF_INET;
tsockinfo.sin_port = htons(7070);
if (argc > 1)
{
tsockinfo.sin_port = htons(atoi(argv[1]));
}
tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);
printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));
if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)
{
perror("Couldn't bind socket");
return -1;
}
if (listen(tsocket, 10) == -1)
{
perror("Couldn't listen to port");
}
ChatLoop();
return 0;
}
| package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
}
type Server struct {
add chan *conn
rem chan string
msg chan string
stop chan bool
}
func ListenAndServe(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
rwc, err := ln.Accept()
if err != nil {
close(s.stop)
return err
}
log.Println("New connection from", rwc.RemoteAddr())
go newConn(s, rwc).welcome()
}
}
func (s *Server) handleConns() {
conns := make(map[string]*conn)
var dropConn func(string)
writeAll := func(str string) {
log.Printf("Broadcast: %q", str)
for name, c := range conns {
c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))
_, err := c.Write([]byte(str))
if err != nil {
log.Printf("Error writing to %q: %v", name, err)
c.Close()
delete(conns, name)
defer dropConn(name)
}
}
}
dropConn = func(name string) {
if c, ok := conns[name]; ok {
log.Printf("Closing connection with %q from %v",
name, c.RemoteAddr())
c.Close()
delete(conns, name)
} else {
log.Printf("Dropped connection with %q", name)
}
str := fmt.Sprintf("--- %q disconnected ---\n", name)
writeAll(str)
}
defer func() {
writeAll("Server stopping!\n")
for _, c := range conns {
c.Close()
}
}()
for {
select {
case c := <-s.add:
if _, exists := conns[c.name]; exists {
fmt.Fprintf(c, "Name %q is not available\n", c.name)
go c.welcome()
continue
}
str := fmt.Sprintf("+++ %q connected +++\n", c.name)
writeAll(str)
conns[c.name] = c
go c.readloop()
case str := <-s.msg:
writeAll(str)
case name := <-s.rem:
dropConn(name)
case <-s.stop:
return
}
}
}
type conn struct {
*bufio.Reader
net.Conn
server *Server
name string
}
func newConn(s *Server, rwc net.Conn) *conn {
return &conn{
Reader: bufio.NewReader(rwc),
Conn: rwc,
server: s,
}
}
func (c *conn) welcome() {
var err error
for c.name = ""; c.name == ""; {
fmt.Fprint(c, "Enter your name: ")
c.name, err = c.ReadString('\n')
if err != nil {
log.Printf("Reading name from %v: %v", c.RemoteAddr(), err)
c.Close()
return
}
c.name = strings.TrimSpace(c.name)
}
c.server.add <- c
}
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')
if err != nil {
break
}
c.server.msg <- c.name + "> " + msg
}
c.server.rem <- c.name
}
|
Write the same code in Go as shown below in C. | #include <stdlib.h>
| package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
p := sync.Pool{New: func() interface{} {
fmt.Println("pool empty")
return new(int)
}}
i := new(int)
j := new(int)
*i = 1
*j = 2
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
i = p.Get().(*int)
j = p.Get().(*int)
*i = 4
*j = 5
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
runtime.GC()
i = p.Get().(*int)
j = p.Get().(*int)
*i = 7
*j = 8
fmt.Println(*i + *j)
}
|
Write a version of this C function in Go with identical behavior. | #include <stdlib.h>
| package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
p := sync.Pool{New: func() interface{} {
fmt.Println("pool empty")
return new(int)
}}
i := new(int)
j := new(int)
*i = 1
*j = 2
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
i = p.Get().(*int)
j = p.Get().(*int)
*i = 4
*j = 5
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
runtime.GC()
i = p.Get().(*int)
j = p.Get().(*int)
*i = 7
*j = 8
fmt.Println(*i + *j)
}
|
Write the same code in Go as shown below in C. | #include <stdio.h>
int main(int argc, char const *argv[]) {
for (char c = 0x41; c < 0x5b; c ++) putchar(c);
putchar('\n');
for (char c = 0x61; c < 0x7b; c ++) putchar(c);
putchar('\n');
return 0;
}
| package main
import (
"fmt"
"unicode"
)
const (
lcASCII = "abcdefghijklmnopqrstuvwxyz"
ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func main() {
fmt.Println("ASCII lower case:")
fmt.Println(lcASCII)
for l := 'a'; l <= 'z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nASCII upper case:")
fmt.Println(ucASCII)
for l := 'A'; l <= 'Z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nUnicode version " + unicode.Version)
showRange16("Lower case 16-bit code points:", unicode.Lower.R16)
showRange32("Lower case 32-bit code points:", unicode.Lower.R32)
showRange16("Upper case 16-bit code points:", unicode.Upper.R16)
showRange32("Upper case 32-bit code points:", unicode.Upper.R32)
}
func showRange16(hdr string, rList []unicode.Range16) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
func showRange32(hdr string, rList []unicode.Range32) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
|
Write the same code in Go as shown below in C. | #include<stdlib.h>
#include<stdio.h>
typedef struct{
int rows,cols;
int** dataSet;
}matrix;
matrix readMatrix(char* dataFile){
FILE* fp = fopen(dataFile,"r");
matrix rosetta;
int i,j;
fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);
rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
for(i=0;i<rosetta.rows;i++){
rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
for(j=0;j<rosetta.cols;j++)
fscanf(fp,"%d",&rosetta.dataSet[i][j]);
}
fclose(fp);
return rosetta;
}
void printMatrix(matrix rosetta){
int i,j;
for(i=0;i<rosetta.rows;i++){
printf("\n");
for(j=0;j<rosetta.cols;j++)
printf("%3d",rosetta.dataSet[i][j]);
}
}
int findSum(matrix rosetta){
int i,j,sum = 0;
for(i=1;i<rosetta.rows;i++){
for(j=0;j<i;j++){
sum += rosetta.dataSet[i][j];
}
}
return sum;
}
int main(int argC,char* argV[])
{
if(argC!=2)
return printf("Usage : %s <filename>",argV[0]);
matrix data = readMatrix(argV[1]);
printf("\n\nMatrix is : \n\n");
printMatrix(data);
printf("\n\nSum below main diagonal : %d",findSum(data));
return 0;
}
| package main
import (
"fmt"
"log"
)
func main() {
m := [][]int{
{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5},
}
if len(m) != len(m[0]) {
log.Fatal("Matrix must be square.")
}
sum := 0
for i := 1; i < len(m); i++ {
for j := 0; j < i; j++ {
sum = sum + m[i][j]
}
}
fmt.Println("Sum of elements below main diagonal is", sum)
}
|
Please provide an equivalent version of this C code in Go. | #include<curl/curl.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
void searchChatLogs(char* searchString){
char* baseURL = "http:
time_t t;
struct tm* currentDate;
char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];
int i,flag;
FILE *fp;
CURL *curl;
CURLcode res;
time(&t);
currentDate = localtime(&t);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
printf("Today is : %s",dateString);
if((curl = curl_easy_init())!=NULL){
for(i=0;i<=10;i++){
flag = 0;
sprintf(targetURL,"%s%s.tcl",baseURL,dateString);
strcpy(dateStringFile,dateString);
printf("\nRetrieving chat logs from %s\n",targetURL);
if((fp = fopen("nul","w"))==0){
printf("Cant's read from %s",targetURL);
}
else{
curl_easy_setopt(curl, CURLOPT_URL, targetURL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
if(res == CURLE_OK){
while(fgets(lineData,MAX_LEN,fp)!=NULL){
if(strstr(lineData,searchString)!=NULL){
flag = 1;
fputs(lineData,stdout);
}
}
if(flag==0)
printf("\nNo matching lines found.");
}
fflush(fp);
fclose(fp);
}
currentDate->tm_mday--;
mktime(currentDate);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
}
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <followed by search string, enclosed by \" if it contains spaces>",argV[0]);
else
searchChatLogs(argV[1]);
return 0;
}
| package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func get(url string) (res string, err error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(buf), nil
}
func grep(needle string, haystack string) (res []string) {
for _, line := range strings.Split(haystack, "\n") {
if strings.Contains(line, needle) {
res = append(res, line)
}
}
return res
}
func genUrl(i int, loc *time.Location) string {
date := time.Now().In(loc).AddDate(0, 0, i)
return date.Format("http:
}
func main() {
needle := os.Args[1]
back := -10
serverLoc, err := time.LoadLocation("Europe/Berlin")
if err != nil {
log.Fatal(err)
}
for i := back; i <= 0; i++ {
url := genUrl(i, serverLoc)
contents, err := get(url)
if err != nil {
log.Fatal(err)
}
found := grep(needle, contents)
if len(found) > 0 {
fmt.Printf("%v\n------\n", url)
for _, line := range found {
fmt.Printf("%v\n", line)
}
fmt.Printf("------\n\n")
}
}
}
|
Produce a language-to-language conversion: from C to Go, same semantics. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
#define ESC 27
#define TEST TRUE
typedef int bool;
int get_number(const char *prompt, int min, int max, bool show_mm) {
int n;
char *line = NULL;
size_t len = 0;
ssize_t read;
fflush(stdin);
do {
printf("%s", prompt);
if (show_mm)
printf(" from %d to %d : ", min, max);
else
printf(" : ");
read = getline(&line, &len, stdin);
if (read < 2) continue;
n = atoi(line);
}
while (n < min || n > max);
printf("\n");
return n;
}
int compare_int(const void *a, const void* b) {
int i = *(int *)a;
int j = *(int *)b;
return i - j;
}
int main() {
int i, j, n, players, coins, first, round = 1, rem_size;
int min, max, guess, index, index2, total;
int remaining[9], hands[10], guesses[10];
bool found, eliminated;
char c;
players = get_number("Number of players", 2, 9, TRUE);
coins = get_number("Number of coins per player", 3, 6, TRUE);
for (i = 0; i < 9; ++i) remaining[i] = i + 1;
rem_size = players;
srand(time(NULL));
first = 1 + rand() % players;
printf("The number of coins in your hand will be randomly determined for");
printf("\neach round and displayed to you. However, when you press ENTER");
printf("\nit will be erased so that the other players, who should look");
printf("\naway until it's their turn, won't see it. When asked to guess");
printf("\nthe total, the computer won't allow a 'bum guess'.\n");
while(TRUE) {
printf("\nROUND %d:\n", round);
n = first;
for (i = 0; i < 10; ++i) {
hands[i] = 0; guesses[i] = -1;
}
do {
printf(" PLAYER %d:\n", n);
printf(" Please come to the computer and press ENTER\n");
hands[n] = rand() % (coins + 1);
printf(" <There are %d coin(s) in your hand>", hands[n]);
while (getchar() != '\n');
if (!TEST) {
printf("%c[1A", ESC);
printf("%c[2K", ESC);
printf("\r\n");
}
else printf("\n");
while (TRUE) {
min = hands[n];
max = (rem_size - 1) * coins + hands[n];
guess = get_number(" Guess the total", min, max, FALSE);
found = FALSE;
for (i = 1; i < 10; ++i) {
if (guess == guesses[i]) {
found = TRUE;
break;
}
}
if (!found) {
guesses[n] = guess;
break;
}
printf(" Already guessed by another player, try again\n");
}
index = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == n) {
index = i;
break;
}
}
if (index < rem_size - 1)
n = remaining[index + 1];
else
n = remaining[0];
}
while (n != first);
total = 0;
for (i = 1; i < 10; ++i) total += hands[i];
printf(" Total coins held = %d\n", total);
eliminated = FALSE;
for (i = 0; i < rem_size; ++i) {
j = remaining[i];
if (guesses[j] == total) {
printf(" PLAYER %d guessed correctly and is eliminated\n", j);
remaining[i] = 10;
rem_size--;
qsort(remaining, players, sizeof(int), compare_int);
eliminated = TRUE;
break;
}
}
if (!eliminated)
printf(" No players guessed correctly in this round\n");
else if (rem_size == 1) {
printf("\nPLAYER %d buys the drinks!\n", remaining[0]);
break;
}
index2 = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == first) {
index2 = i;
break;
}
}
if (index2 < rem_size - 1)
first = remaining[index2 + 1];
else
first = remaining[0];
round++;
}
return 0;
}
| package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
)
const (
esc = "\033"
test = true
)
var scanner = bufio.NewScanner(os.Stdin)
func indexOf(s []int, el int) int {
for i, v := range s {
if v == el {
return i
}
}
return -1
}
func getNumber(prompt string, min, max int, showMinMax bool) (int, error) {
for {
fmt.Print(prompt)
if showMinMax {
fmt.Printf(" from %d to %d : ", min, max)
} else {
fmt.Printf(" : ")
}
scanner.Scan()
if scerr := scanner.Err(); scerr != nil {
return 0, scerr
}
input, err := strconv.Atoi(scanner.Text())
if err == nil && input >= min && input <= max {
fmt.Println()
return input, nil
}
}
}
func check(err error, text string) {
if err != nil {
log.Fatalln(err, text)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
players, err := getNumber("Number of players", 2, 9, true)
check(err, "when getting players")
coins, err2 := getNumber("Number of coins per player", 3, 6, true)
check(err2, "when getting coins")
remaining := make([]int, players)
for i := range remaining {
remaining[i] = i + 1
}
first := 1 + rand.Intn(players)
fmt.Println("The number of coins in your hand will be randomly determined for")
fmt.Println("each round and displayed to you. However, when you press ENTER")
fmt.Println("it will be erased so that the other players, who should look")
fmt.Println("away until it's their turn, won't see it. When asked to guess")
fmt.Println("the total, the computer won't allow a 'bum guess'.")
for round := 1; ; round++ {
fmt.Printf("\nROUND %d:\n\n", round)
n := first
hands := make([]int, players+1)
guesses := make([]int, players+1)
for i := range guesses {
guesses[i] = -1
}
for {
fmt.Printf(" PLAYER %d:\n", n)
fmt.Println(" Please come to the computer and press ENTER")
hands[n] = rand.Intn(coins + 1)
fmt.Print(" <There are ", hands[n], " coin(s) in your hand>")
scanner.Scan()
check(scanner.Err(), "when pressing ENTER")
if !test {
fmt.Print(esc, "[1A")
fmt.Print(esc, "[2K")
fmt.Println("\r")
} else {
fmt.Println()
}
for {
min := hands[n]
max := (len(remaining)-1)*coins + hands[n]
guess, err3 := getNumber(" Guess the total", min, max, false)
check(err3, "when guessing the total")
if indexOf(guesses, guess) == -1 {
guesses[n] = guess
break
}
fmt.Println(" Already guessed by another player, try again")
}
index := indexOf(remaining, n)
if index < len(remaining)-1 {
n = remaining[index+1]
} else {
n = remaining[0]
}
if n == first {
break
}
}
total := 0
for _, hand := range hands {
total += hand
}
fmt.Println(" Total coins held =", total)
eliminated := false
for _, v := range remaining {
if guesses[v] == total {
fmt.Println(" PLAYER", v, "guessed correctly and is eliminated")
r := indexOf(remaining, v)
remaining = append(remaining[:r], remaining[r+1:]...)
eliminated = true
break
}
}
if !eliminated {
fmt.Println(" No players guessed correctly in this round")
} else if len(remaining) == 1 {
fmt.Println("\nPLAYER", remaining[0], "buys the drinks!")
return
}
index2 := indexOf(remaining, n)
if index2 < len(remaining)-1 {
first = remaining[index2+1]
} else {
first = remaining[0]
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
#define ESC 27
#define TEST TRUE
typedef int bool;
int get_number(const char *prompt, int min, int max, bool show_mm) {
int n;
char *line = NULL;
size_t len = 0;
ssize_t read;
fflush(stdin);
do {
printf("%s", prompt);
if (show_mm)
printf(" from %d to %d : ", min, max);
else
printf(" : ");
read = getline(&line, &len, stdin);
if (read < 2) continue;
n = atoi(line);
}
while (n < min || n > max);
printf("\n");
return n;
}
int compare_int(const void *a, const void* b) {
int i = *(int *)a;
int j = *(int *)b;
return i - j;
}
int main() {
int i, j, n, players, coins, first, round = 1, rem_size;
int min, max, guess, index, index2, total;
int remaining[9], hands[10], guesses[10];
bool found, eliminated;
char c;
players = get_number("Number of players", 2, 9, TRUE);
coins = get_number("Number of coins per player", 3, 6, TRUE);
for (i = 0; i < 9; ++i) remaining[i] = i + 1;
rem_size = players;
srand(time(NULL));
first = 1 + rand() % players;
printf("The number of coins in your hand will be randomly determined for");
printf("\neach round and displayed to you. However, when you press ENTER");
printf("\nit will be erased so that the other players, who should look");
printf("\naway until it's their turn, won't see it. When asked to guess");
printf("\nthe total, the computer won't allow a 'bum guess'.\n");
while(TRUE) {
printf("\nROUND %d:\n", round);
n = first;
for (i = 0; i < 10; ++i) {
hands[i] = 0; guesses[i] = -1;
}
do {
printf(" PLAYER %d:\n", n);
printf(" Please come to the computer and press ENTER\n");
hands[n] = rand() % (coins + 1);
printf(" <There are %d coin(s) in your hand>", hands[n]);
while (getchar() != '\n');
if (!TEST) {
printf("%c[1A", ESC);
printf("%c[2K", ESC);
printf("\r\n");
}
else printf("\n");
while (TRUE) {
min = hands[n];
max = (rem_size - 1) * coins + hands[n];
guess = get_number(" Guess the total", min, max, FALSE);
found = FALSE;
for (i = 1; i < 10; ++i) {
if (guess == guesses[i]) {
found = TRUE;
break;
}
}
if (!found) {
guesses[n] = guess;
break;
}
printf(" Already guessed by another player, try again\n");
}
index = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == n) {
index = i;
break;
}
}
if (index < rem_size - 1)
n = remaining[index + 1];
else
n = remaining[0];
}
while (n != first);
total = 0;
for (i = 1; i < 10; ++i) total += hands[i];
printf(" Total coins held = %d\n", total);
eliminated = FALSE;
for (i = 0; i < rem_size; ++i) {
j = remaining[i];
if (guesses[j] == total) {
printf(" PLAYER %d guessed correctly and is eliminated\n", j);
remaining[i] = 10;
rem_size--;
qsort(remaining, players, sizeof(int), compare_int);
eliminated = TRUE;
break;
}
}
if (!eliminated)
printf(" No players guessed correctly in this round\n");
else if (rem_size == 1) {
printf("\nPLAYER %d buys the drinks!\n", remaining[0]);
break;
}
index2 = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == first) {
index2 = i;
break;
}
}
if (index2 < rem_size - 1)
first = remaining[index2 + 1];
else
first = remaining[0];
round++;
}
return 0;
}
| package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
)
const (
esc = "\033"
test = true
)
var scanner = bufio.NewScanner(os.Stdin)
func indexOf(s []int, el int) int {
for i, v := range s {
if v == el {
return i
}
}
return -1
}
func getNumber(prompt string, min, max int, showMinMax bool) (int, error) {
for {
fmt.Print(prompt)
if showMinMax {
fmt.Printf(" from %d to %d : ", min, max)
} else {
fmt.Printf(" : ")
}
scanner.Scan()
if scerr := scanner.Err(); scerr != nil {
return 0, scerr
}
input, err := strconv.Atoi(scanner.Text())
if err == nil && input >= min && input <= max {
fmt.Println()
return input, nil
}
}
}
func check(err error, text string) {
if err != nil {
log.Fatalln(err, text)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
players, err := getNumber("Number of players", 2, 9, true)
check(err, "when getting players")
coins, err2 := getNumber("Number of coins per player", 3, 6, true)
check(err2, "when getting coins")
remaining := make([]int, players)
for i := range remaining {
remaining[i] = i + 1
}
first := 1 + rand.Intn(players)
fmt.Println("The number of coins in your hand will be randomly determined for")
fmt.Println("each round and displayed to you. However, when you press ENTER")
fmt.Println("it will be erased so that the other players, who should look")
fmt.Println("away until it's their turn, won't see it. When asked to guess")
fmt.Println("the total, the computer won't allow a 'bum guess'.")
for round := 1; ; round++ {
fmt.Printf("\nROUND %d:\n\n", round)
n := first
hands := make([]int, players+1)
guesses := make([]int, players+1)
for i := range guesses {
guesses[i] = -1
}
for {
fmt.Printf(" PLAYER %d:\n", n)
fmt.Println(" Please come to the computer and press ENTER")
hands[n] = rand.Intn(coins + 1)
fmt.Print(" <There are ", hands[n], " coin(s) in your hand>")
scanner.Scan()
check(scanner.Err(), "when pressing ENTER")
if !test {
fmt.Print(esc, "[1A")
fmt.Print(esc, "[2K")
fmt.Println("\r")
} else {
fmt.Println()
}
for {
min := hands[n]
max := (len(remaining)-1)*coins + hands[n]
guess, err3 := getNumber(" Guess the total", min, max, false)
check(err3, "when guessing the total")
if indexOf(guesses, guess) == -1 {
guesses[n] = guess
break
}
fmt.Println(" Already guessed by another player, try again")
}
index := indexOf(remaining, n)
if index < len(remaining)-1 {
n = remaining[index+1]
} else {
n = remaining[0]
}
if n == first {
break
}
}
total := 0
for _, hand := range hands {
total += hand
}
fmt.Println(" Total coins held =", total)
eliminated := false
for _, v := range remaining {
if guesses[v] == total {
fmt.Println(" PLAYER", v, "guessed correctly and is eliminated")
r := indexOf(remaining, v)
remaining = append(remaining[:r], remaining[r+1:]...)
eliminated = true
break
}
}
if !eliminated {
fmt.Println(" No players guessed correctly in this round")
} else if len(remaining) == 1 {
fmt.Println("\nPLAYER", remaining[0], "buys the drinks!")
return
}
index2 := indexOf(remaining, n)
if index2 < len(remaining)-1 {
first = remaining[index2+1]
} else {
first = remaining[0]
}
}
}
|
Can you help me rewrite this code in Go instead of C, keeping it the same logically? |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_rank_languages_by_number_of_users.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
| package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"sort"
"strconv"
)
type Result struct {
lang string
users int
}
func main() {
const minimum = 25
ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)`
re := regexp.MustCompile(ex)
page := "http:
action := "action=query"
format := "format=json"
fversion := "formatversion=2"
generator := "generator=categorymembers"
gcmTitle := "gcmtitle=Category:Language%20users"
gcmLimit := "gcmlimit=500"
prop := "prop=categoryinfo"
rawContinue := "rawcontinue="
page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion,
generator, gcmTitle, gcmLimit, prop, rawContinue)
resp, _ := http.Get(page)
body, _ := ioutil.ReadAll(resp.Body)
matches := re.FindAllStringSubmatch(string(body), -1)
resp.Body.Close()
var results []Result
for _, match := range matches {
if len(match) == 5 {
users, _ := strconv.Atoi(match[4])
if users >= minimum {
result := Result{match[1], users}
results = append(results, result)
}
}
}
sort.Slice(results, func(i, j int) bool {
return results[j].users < results[i].users
})
fmt.Println("Rank Users Language")
fmt.Println("---- ----- --------")
rank := 0
lastUsers := 0
lastRank := 0
for i, result := range results {
eq := " "
rank = i + 1
if lastUsers == result.users {
eq = "="
rank = lastRank
} else {
lastUsers = result.users
lastRank = rank
}
fmt.Printf(" %-2d%s %3d %s\n", rank, eq, result.users, result.lang)
}
}
|
Please provide an equivalent version of this C code in Go. |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_rank_languages_by_number_of_users.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
| package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"sort"
"strconv"
)
type Result struct {
lang string
users int
}
func main() {
const minimum = 25
ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)`
re := regexp.MustCompile(ex)
page := "http:
action := "action=query"
format := "format=json"
fversion := "formatversion=2"
generator := "generator=categorymembers"
gcmTitle := "gcmtitle=Category:Language%20users"
gcmLimit := "gcmlimit=500"
prop := "prop=categoryinfo"
rawContinue := "rawcontinue="
page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion,
generator, gcmTitle, gcmLimit, prop, rawContinue)
resp, _ := http.Get(page)
body, _ := ioutil.ReadAll(resp.Body)
matches := re.FindAllStringSubmatch(string(body), -1)
resp.Body.Close()
var results []Result
for _, match := range matches {
if len(match) == 5 {
users, _ := strconv.Atoi(match[4])
if users >= minimum {
result := Result{match[1], users}
results = append(results, result)
}
}
}
sort.Slice(results, func(i, j int) bool {
return results[j].users < results[i].users
})
fmt.Println("Rank Users Language")
fmt.Println("---- ----- --------")
rank := 0
lastUsers := 0
lastRank := 0
for i, result := range results {
eq := " "
rank = i + 1
if lastUsers == result.users {
eq = "="
rank = lastRank
} else {
lastUsers = result.users
lastRank = rank
}
fmt.Printf(" %-2d%s %3d %s\n", rank, eq, result.users, result.lang)
}
}
|
Convert this C block to Go, preserving its control flow and logic. | #include <stdio.h>
#include "achain.c"
typedef struct {double u, v;} cplx;
inline cplx c_mul(cplx a, cplx b)
{
cplx c;
c.u = a.u * b.u - a.v * b.v;
c.v = a.u * b.v + a.v * b.u;
return c;
}
cplx chain_expo(cplx x, int n)
{
int i, j, k, l, e[32];
cplx v[32];
l = seq(n, 0, e);
puts("Exponents:");
for (i = 0; i <= l; i++)
printf("%d%c", e[i], i == l ? '\n' : ' ');
v[0] = x; v[1] = c_mul(x, x);
for (i = 2; i <= l; i++) {
for (j = i - 1; j; j--) {
for (k = j; k >= 0; k--) {
if (e[k] + e[j] < e[i]) break;
if (e[k] + e[j] > e[i]) continue;
v[i] = c_mul(v[j], v[k]);
j = 1;
break;
}
}
}
printf("(%f + i%f)^%d = %f + i%f\n",
x.u, x.v, n, v[l].u, v[l].v);
return x;
}
int bin_len(int n)
{
int r, o;
for (r = o = -1; n; n >>= 1, r++)
if (n & 1) o++;
return r + o;
}
int main()
{
cplx r1 = {1.0000254989, 0.0000577896},
r2 = {1.0000220632, 0.0000500026};
int n1 = 27182, n2 = 31415, i;
init();
puts("Precompute chain lengths");
seq_len(n2);
chain_expo(r1, n1);
chain_expo(r2, n2);
puts("\nchain lengths: shortest binary");
printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1));
printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2));
for (i = 1; i < 100; i++)
printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i));
return 0;
}
| package main
import (
"fmt"
"math"
)
const (
N = 32
NMAX = 40000
)
var (
u = [N]int{0: 1, 1: 2}
l = [N]int{0: 1, 1: 2}
out = [N]int{}
sum = [N]int{}
tail = [N]int{}
cache = [NMAX + 1]int{2: 1}
known = 2
stack = 0
undo = [N * N]save{}
)
type save struct {
p *int
v int
}
func replace(x *[N]int, i, n int) {
undo[stack].p = &x[i]
undo[stack].v = x[i]
x[i] = n
stack++
}
func restore(n int) {
for stack > n {
stack--
*undo[stack].p = undo[stack].v
}
}
func lower(n int, up *int) int {
if n <= 2 || (n <= NMAX && cache[n] != 0) {
if up != nil {
*up = cache[n]
}
return cache[n]
}
i, o := -1, 0
for ; n != 0; n, i = n>>1, i+1 {
if n&1 != 0 {
o++
}
}
if up != nil {
i--
*up = o + i
}
for {
i++
o >>= 1
if o == 0 {
break
}
}
if up == nil {
return i
}
for o = 2; o*o < n; o++ {
if n%o != 0 {
continue
}
q := cache[o] + cache[n/o]
if q < *up {
*up = q
if q == i {
break
}
}
}
if n > 2 {
if *up > cache[n-2]+1 {
*up = cache[n-1] + 1
}
if *up > cache[n-2]+1 {
*up = cache[n-2] + 1
}
}
return i
}
func insert(x, pos int) bool {
save := stack
if l[pos] > x || u[pos] < x {
return false
}
if l[pos] == x {
goto replU
}
replace(&l, pos, x)
for i := pos - 1; u[i]*2 < u[i+1]; i-- {
t := l[i+1] + 1
if t*2 > u[i] {
goto bail
}
replace(&l, i, t)
}
for i := pos + 1; l[i] <= l[i-1]; i++ {
t := l[i-1] + 1
if t > u[i] {
goto bail
}
replace(&l, i, t)
}
replU:
if u[pos] == x {
return true
}
replace(&u, pos, x)
for i := pos - 1; u[i] >= u[i+1]; i-- {
t := u[i+1] - 1
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
for i := pos + 1; u[i] > u[i-1]*2; i++ {
t := u[i-1] * 2
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
return true
bail:
restore(save)
return false
}
func try(p, q, le int) bool {
pl := cache[p]
if pl >= le {
return false
}
ql := cache[q]
if ql >= le {
return false
}
var pu, qu int
for pl < le && u[pl] < p {
pl++
}
for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {
}
for ql < le && u[ql] < q {
ql++
}
for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {
}
if p != q && pl <= ql {
pl = ql + 1
}
if pl > pu || ql > qu || ql > pu {
return false
}
if out[le] == 0 {
pu = le - 1
pl = pu
}
ps := stack
for ; pu >= pl; pu-- {
if !insert(p, pu) {
continue
}
out[pu]++
sum[pu] += le
if p != q {
qs := stack
j := qu
if j >= pu {
j = pu - 1
}
for ; j >= ql; j-- {
if !insert(q, j) {
continue
}
out[j]++
sum[j] += le
tail[le] = q
if seqRecur(le - 1) {
return true
}
restore(qs)
out[j]--
sum[j] -= le
}
} else {
out[pu]++
sum[pu] += le
tail[le] = p
if seqRecur(le - 1) {
return true
}
out[pu]--
sum[pu] -= le
}
out[pu]--
sum[pu] -= le
restore(ps)
}
return false
}
func seqRecur(le int) bool {
n := l[le]
if le < 2 {
return true
}
limit := n - 1
if out[le] == 1 {
limit = n - tail[sum[le]]
}
if limit > u[le-1] {
limit = u[le-1]
}
p := limit
for q := n - p; q <= p; q, p = q+1, p-1 {
if try(p, q, le) {
return true
}
}
return false
}
func seq(n, le int, buf []int) int {
if le == 0 {
le = seqLen(n)
}
stack = 0
l[le], u[le] = n, n
for i := 0; i <= le; i++ {
out[i], sum[i] = 0, 0
}
for i := 2; i < le; i++ {
l[i] = l[i-1] + 1
u[i] = u[i-1] * 2
}
for i := le - 1; i > 2; i-- {
if l[i]*2 < l[i+1] {
l[i] = (1 + l[i+1]) / 2
}
if u[i] >= u[i+1] {
u[i] = u[i+1] - 1
}
}
if !seqRecur(le) {
return 0
}
if buf != nil {
for i := 0; i <= le; i++ {
buf[i] = u[i]
}
}
return le
}
func seqLen(n int) int {
if n <= known {
return cache[n]
}
for known+1 < n {
seqLen(known + 1)
}
var ub int
lb := lower(n, &ub)
for lb < ub && seq(n, lb, nil) == 0 {
lb++
}
known = n
if n&1023 == 0 {
fmt.Printf("Cached %d\n", known)
}
cache[n] = lb
return lb
}
func binLen(n int) int {
r, o := -1, -1
for ; n != 0; n, r = n>>1, r+1 {
if n&1 != 0 {
o++
}
}
return r + o
}
type(
vector = []float64
matrix []vector
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func (m matrix) pow(n int, printout bool) matrix {
e := make([]int, N)
var v [N]matrix
le := seq(n, 0, e)
if printout {
fmt.Println("Addition chain:")
for i := 0; i <= le; i++ {
c := ' '
if i == le {
c = '\n'
}
fmt.Printf("%d%c", e[i], c)
}
}
v[0] = m
v[1] = m.mul(m)
for i := 2; i <= le; i++ {
for j := i - 1; j != 0; j-- {
for k := j; k >= 0; k-- {
if e[k]+e[j] < e[i] {
break
}
if e[k]+e[j] > e[i] {
continue
}
v[i] = v[j].mul(v[k])
j = 1
break
}
}
}
return v[le]
}
func (m matrix) print() {
for _, v := range m {
fmt.Printf("% f\n", v)
}
fmt.Println()
}
func main() {
m := 27182
n := 31415
fmt.Println("Precompute chain lengths:")
seqLen(n)
rh := math.Sqrt(0.5)
mx := matrix{
{rh, 0, rh, 0, 0, 0},
{0, rh, 0, rh, 0, 0},
{0, rh, 0, -rh, 0, 0},
{-rh, 0, rh, 0, 0, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 1, 0},
}
fmt.Println("\nThe first 100 terms of A003313 are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%d ", seqLen(i))
if i%10 == 0 {
fmt.Println()
}
}
exs := [2]int{m, n}
mxs := [2]matrix{}
for i, ex := range exs {
fmt.Println("\nExponent:", ex)
mxs[i] = mx.pow(ex, true)
fmt.Printf("A ^ %d:-\n\n", ex)
mxs[i].print()
fmt.Println("Number of A/C multiplies:", seqLen(ex))
fmt.Println(" c.f. Binary multiplies:", binLen(ex))
}
fmt.Printf("\nExponent: %d x %d = %d\n", m, n, m*n)
fmt.Printf("A ^ %d = (A ^ %d) ^ %d:-\n\n", m*n, m, n)
mx2 := mxs[0].pow(n, false)
mx2.print()
}
|
Ensure the translated Go code behaves exactly like the original C snippet. | #include <stdio.h>
#include "achain.c"
typedef struct {double u, v;} cplx;
inline cplx c_mul(cplx a, cplx b)
{
cplx c;
c.u = a.u * b.u - a.v * b.v;
c.v = a.u * b.v + a.v * b.u;
return c;
}
cplx chain_expo(cplx x, int n)
{
int i, j, k, l, e[32];
cplx v[32];
l = seq(n, 0, e);
puts("Exponents:");
for (i = 0; i <= l; i++)
printf("%d%c", e[i], i == l ? '\n' : ' ');
v[0] = x; v[1] = c_mul(x, x);
for (i = 2; i <= l; i++) {
for (j = i - 1; j; j--) {
for (k = j; k >= 0; k--) {
if (e[k] + e[j] < e[i]) break;
if (e[k] + e[j] > e[i]) continue;
v[i] = c_mul(v[j], v[k]);
j = 1;
break;
}
}
}
printf("(%f + i%f)^%d = %f + i%f\n",
x.u, x.v, n, v[l].u, v[l].v);
return x;
}
int bin_len(int n)
{
int r, o;
for (r = o = -1; n; n >>= 1, r++)
if (n & 1) o++;
return r + o;
}
int main()
{
cplx r1 = {1.0000254989, 0.0000577896},
r2 = {1.0000220632, 0.0000500026};
int n1 = 27182, n2 = 31415, i;
init();
puts("Precompute chain lengths");
seq_len(n2);
chain_expo(r1, n1);
chain_expo(r2, n2);
puts("\nchain lengths: shortest binary");
printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1));
printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2));
for (i = 1; i < 100; i++)
printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i));
return 0;
}
| package main
import (
"fmt"
"math"
)
const (
N = 32
NMAX = 40000
)
var (
u = [N]int{0: 1, 1: 2}
l = [N]int{0: 1, 1: 2}
out = [N]int{}
sum = [N]int{}
tail = [N]int{}
cache = [NMAX + 1]int{2: 1}
known = 2
stack = 0
undo = [N * N]save{}
)
type save struct {
p *int
v int
}
func replace(x *[N]int, i, n int) {
undo[stack].p = &x[i]
undo[stack].v = x[i]
x[i] = n
stack++
}
func restore(n int) {
for stack > n {
stack--
*undo[stack].p = undo[stack].v
}
}
func lower(n int, up *int) int {
if n <= 2 || (n <= NMAX && cache[n] != 0) {
if up != nil {
*up = cache[n]
}
return cache[n]
}
i, o := -1, 0
for ; n != 0; n, i = n>>1, i+1 {
if n&1 != 0 {
o++
}
}
if up != nil {
i--
*up = o + i
}
for {
i++
o >>= 1
if o == 0 {
break
}
}
if up == nil {
return i
}
for o = 2; o*o < n; o++ {
if n%o != 0 {
continue
}
q := cache[o] + cache[n/o]
if q < *up {
*up = q
if q == i {
break
}
}
}
if n > 2 {
if *up > cache[n-2]+1 {
*up = cache[n-1] + 1
}
if *up > cache[n-2]+1 {
*up = cache[n-2] + 1
}
}
return i
}
func insert(x, pos int) bool {
save := stack
if l[pos] > x || u[pos] < x {
return false
}
if l[pos] == x {
goto replU
}
replace(&l, pos, x)
for i := pos - 1; u[i]*2 < u[i+1]; i-- {
t := l[i+1] + 1
if t*2 > u[i] {
goto bail
}
replace(&l, i, t)
}
for i := pos + 1; l[i] <= l[i-1]; i++ {
t := l[i-1] + 1
if t > u[i] {
goto bail
}
replace(&l, i, t)
}
replU:
if u[pos] == x {
return true
}
replace(&u, pos, x)
for i := pos - 1; u[i] >= u[i+1]; i-- {
t := u[i+1] - 1
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
for i := pos + 1; u[i] > u[i-1]*2; i++ {
t := u[i-1] * 2
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
return true
bail:
restore(save)
return false
}
func try(p, q, le int) bool {
pl := cache[p]
if pl >= le {
return false
}
ql := cache[q]
if ql >= le {
return false
}
var pu, qu int
for pl < le && u[pl] < p {
pl++
}
for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {
}
for ql < le && u[ql] < q {
ql++
}
for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {
}
if p != q && pl <= ql {
pl = ql + 1
}
if pl > pu || ql > qu || ql > pu {
return false
}
if out[le] == 0 {
pu = le - 1
pl = pu
}
ps := stack
for ; pu >= pl; pu-- {
if !insert(p, pu) {
continue
}
out[pu]++
sum[pu] += le
if p != q {
qs := stack
j := qu
if j >= pu {
j = pu - 1
}
for ; j >= ql; j-- {
if !insert(q, j) {
continue
}
out[j]++
sum[j] += le
tail[le] = q
if seqRecur(le - 1) {
return true
}
restore(qs)
out[j]--
sum[j] -= le
}
} else {
out[pu]++
sum[pu] += le
tail[le] = p
if seqRecur(le - 1) {
return true
}
out[pu]--
sum[pu] -= le
}
out[pu]--
sum[pu] -= le
restore(ps)
}
return false
}
func seqRecur(le int) bool {
n := l[le]
if le < 2 {
return true
}
limit := n - 1
if out[le] == 1 {
limit = n - tail[sum[le]]
}
if limit > u[le-1] {
limit = u[le-1]
}
p := limit
for q := n - p; q <= p; q, p = q+1, p-1 {
if try(p, q, le) {
return true
}
}
return false
}
func seq(n, le int, buf []int) int {
if le == 0 {
le = seqLen(n)
}
stack = 0
l[le], u[le] = n, n
for i := 0; i <= le; i++ {
out[i], sum[i] = 0, 0
}
for i := 2; i < le; i++ {
l[i] = l[i-1] + 1
u[i] = u[i-1] * 2
}
for i := le - 1; i > 2; i-- {
if l[i]*2 < l[i+1] {
l[i] = (1 + l[i+1]) / 2
}
if u[i] >= u[i+1] {
u[i] = u[i+1] - 1
}
}
if !seqRecur(le) {
return 0
}
if buf != nil {
for i := 0; i <= le; i++ {
buf[i] = u[i]
}
}
return le
}
func seqLen(n int) int {
if n <= known {
return cache[n]
}
for known+1 < n {
seqLen(known + 1)
}
var ub int
lb := lower(n, &ub)
for lb < ub && seq(n, lb, nil) == 0 {
lb++
}
known = n
if n&1023 == 0 {
fmt.Printf("Cached %d\n", known)
}
cache[n] = lb
return lb
}
func binLen(n int) int {
r, o := -1, -1
for ; n != 0; n, r = n>>1, r+1 {
if n&1 != 0 {
o++
}
}
return r + o
}
type(
vector = []float64
matrix []vector
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func (m matrix) pow(n int, printout bool) matrix {
e := make([]int, N)
var v [N]matrix
le := seq(n, 0, e)
if printout {
fmt.Println("Addition chain:")
for i := 0; i <= le; i++ {
c := ' '
if i == le {
c = '\n'
}
fmt.Printf("%d%c", e[i], c)
}
}
v[0] = m
v[1] = m.mul(m)
for i := 2; i <= le; i++ {
for j := i - 1; j != 0; j-- {
for k := j; k >= 0; k-- {
if e[k]+e[j] < e[i] {
break
}
if e[k]+e[j] > e[i] {
continue
}
v[i] = v[j].mul(v[k])
j = 1
break
}
}
}
return v[le]
}
func (m matrix) print() {
for _, v := range m {
fmt.Printf("% f\n", v)
}
fmt.Println()
}
func main() {
m := 27182
n := 31415
fmt.Println("Precompute chain lengths:")
seqLen(n)
rh := math.Sqrt(0.5)
mx := matrix{
{rh, 0, rh, 0, 0, 0},
{0, rh, 0, rh, 0, 0},
{0, rh, 0, -rh, 0, 0},
{-rh, 0, rh, 0, 0, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 1, 0},
}
fmt.Println("\nThe first 100 terms of A003313 are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%d ", seqLen(i))
if i%10 == 0 {
fmt.Println()
}
}
exs := [2]int{m, n}
mxs := [2]matrix{}
for i, ex := range exs {
fmt.Println("\nExponent:", ex)
mxs[i] = mx.pow(ex, true)
fmt.Printf("A ^ %d:-\n\n", ex)
mxs[i].print()
fmt.Println("Number of A/C multiplies:", seqLen(ex))
fmt.Println(" c.f. Binary multiplies:", binLen(ex))
}
fmt.Printf("\nExponent: %d x %d = %d\n", m, n, m*n)
fmt.Printf("A ^ %d = (A ^ %d) ^ %d:-\n\n", m*n, m, n)
mx2 := mxs[0].pow(n, false)
mx2.print()
}
|
Change the following C code into Go without altering its purpose. | #!/bin/bash
sed -n -e '12,$p' < "$0" > ttmmpp.go
go build ttmmpp.go
rm ttmmpp.go
binfile="${0%.*}"
mv ttmmpp $binfile
$binfile "$@"
STATUS=$?
rm $binfile
exit $STATUS
######## Go Code start on line 12
package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args {
if i == 0 {
fmt.Printf("This program is named %s.\n", x)
} else {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
}
| |
Keep all operations the same but rewrite the snippet in Go. | #!/bin/bash
sed -n -e '12,$p' < "$0" > ttmmpp.go
go build ttmmpp.go
rm ttmmpp.go
binfile="${0%.*}"
mv ttmmpp $binfile
$binfile "$@"
STATUS=$?
rm $binfile
exit $STATUS
######## Go Code start on line 12
package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args {
if i == 0 {
fmt.Printf("This program is named %s.\n", x)
} else {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
}
| |
Convert this C snippet to Go and keep its semantics consistent. | #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Unicode is supported on this terminal and U+25B3 is : \u25b3");
i = -1;
break;
}
}
if (i != -1)
printf ("Unicode is not supported on this terminal.");
return 0;
}
| package main
import (
"fmt"
"os"
"strings"
)
func main() {
lang := strings.ToUpper(os.Getenv("LANG"))
if strings.Contains(lang, "UTF") {
fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
} else {
fmt.Println("This terminal does not support unicode")
}
}
|
Change the following C code into Go without altering its purpose. | #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Unicode is supported on this terminal and U+25B3 is : \u25b3");
i = -1;
break;
}
}
if (i != -1)
printf ("Unicode is not supported on this terminal.");
return 0;
}
| package main
import (
"fmt"
"os"
"strings"
)
func main() {
lang := strings.ToUpper(os.Getenv("LANG"))
if strings.Contains(lang, "UTF") {
fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
} else {
fmt.Println("This terminal does not support unicode")
}
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
typedef struct node_tag {
int item;
struct node_tag* prev;
struct node_tag* next;
} node_t;
void list_initialize(node_t* list) {
list->prev = list;
list->next = list;
}
void list_destroy(node_t* list) {
node_t* n = list->next;
while (n != list) {
node_t* tmp = n->next;
free(n);
n = tmp;
}
}
void list_append_node(node_t* list, node_t* node) {
node_t* prev = list->prev;
prev->next = node;
list->prev = node;
node->prev = prev;
node->next = list;
}
void list_append_item(node_t* list, int item) {
node_t* node = xmalloc(sizeof(node_t));
node->item = item;
list_append_node(list, node);
}
void list_print(node_t* list) {
printf("[");
node_t* n = list->next;
if (n != list) {
printf("%d", n->item);
n = n->next;
}
for (; n != list; n = n->next)
printf(", %d", n->item);
printf("]\n");
}
void tree_insert(node_t** p, node_t* n) {
while (*p != NULL) {
if (n->item < (*p)->item)
p = &(*p)->prev;
else
p = &(*p)->next;
}
*p = n;
}
void tree_to_list(node_t* list, node_t* node) {
if (node == NULL)
return;
node_t* prev = node->prev;
node_t* next = node->next;
tree_to_list(list, prev);
list_append_node(list, node);
tree_to_list(list, next);
}
void tree_sort(node_t* list) {
node_t* n = list->next;
if (n == list)
return;
node_t* root = NULL;
while (n != list) {
node_t* next = n->next;
n->next = n->prev = NULL;
tree_insert(&root, n);
n = next;
}
list_initialize(list);
tree_to_list(list, root);
}
int main() {
srand(time(0));
node_t list;
list_initialize(&list);
for (int i = 0; i < 16; ++i)
list_append_item(&list, rand() % 100);
printf("before sort: ");
list_print(&list);
tree_sort(&list);
printf(" after sort: ");
list_print(&list);
list_destroy(&list);
return 0;
}
| package main
import (
"container/list"
"fmt"
)
type BinaryTree struct {
node int
leftSubTree *BinaryTree
rightSubTree *BinaryTree
}
func (bt *BinaryTree) insert(item int) {
if bt.node == 0 {
bt.node = item
bt.leftSubTree = &BinaryTree{}
bt.rightSubTree = &BinaryTree{}
} else if item < bt.node {
bt.leftSubTree.insert(item)
} else {
bt.rightSubTree.insert(item)
}
}
func (bt *BinaryTree) inOrder(ll *list.List) {
if bt.node == 0 {
return
}
bt.leftSubTree.inOrder(ll)
ll.PushBack(bt.node)
bt.rightSubTree.inOrder(ll)
}
func treeSort(ll *list.List) *list.List {
searchTree := &BinaryTree{}
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
searchTree.insert(i)
}
ll2 := list.New()
searchTree.inOrder(ll2)
return ll2
}
func printLinkedList(ll *list.List, f string, sorted bool) {
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
fmt.Printf(f+" ", i)
}
if !sorted {
fmt.Print("-> ")
} else {
fmt.Println()
}
}
func main() {
sl := []int{5, 3, 7, 9, 1}
ll := list.New()
for _, i := range sl {
ll.PushBack(i)
}
printLinkedList(ll, "%d", false)
lls := treeSort(ll)
printLinkedList(lls, "%d", true)
sl2 := []int{'d', 'c', 'e', 'b', 'a'}
ll2 := list.New()
for _, c := range sl2 {
ll2.PushBack(c)
}
printLinkedList(ll2, "%c", false)
lls2 := treeSort(ll2)
printLinkedList(lls2, "%c", true)
}
|
Write a version of this C function in Go with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
typedef struct node_tag {
int item;
struct node_tag* prev;
struct node_tag* next;
} node_t;
void list_initialize(node_t* list) {
list->prev = list;
list->next = list;
}
void list_destroy(node_t* list) {
node_t* n = list->next;
while (n != list) {
node_t* tmp = n->next;
free(n);
n = tmp;
}
}
void list_append_node(node_t* list, node_t* node) {
node_t* prev = list->prev;
prev->next = node;
list->prev = node;
node->prev = prev;
node->next = list;
}
void list_append_item(node_t* list, int item) {
node_t* node = xmalloc(sizeof(node_t));
node->item = item;
list_append_node(list, node);
}
void list_print(node_t* list) {
printf("[");
node_t* n = list->next;
if (n != list) {
printf("%d", n->item);
n = n->next;
}
for (; n != list; n = n->next)
printf(", %d", n->item);
printf("]\n");
}
void tree_insert(node_t** p, node_t* n) {
while (*p != NULL) {
if (n->item < (*p)->item)
p = &(*p)->prev;
else
p = &(*p)->next;
}
*p = n;
}
void tree_to_list(node_t* list, node_t* node) {
if (node == NULL)
return;
node_t* prev = node->prev;
node_t* next = node->next;
tree_to_list(list, prev);
list_append_node(list, node);
tree_to_list(list, next);
}
void tree_sort(node_t* list) {
node_t* n = list->next;
if (n == list)
return;
node_t* root = NULL;
while (n != list) {
node_t* next = n->next;
n->next = n->prev = NULL;
tree_insert(&root, n);
n = next;
}
list_initialize(list);
tree_to_list(list, root);
}
int main() {
srand(time(0));
node_t list;
list_initialize(&list);
for (int i = 0; i < 16; ++i)
list_append_item(&list, rand() % 100);
printf("before sort: ");
list_print(&list);
tree_sort(&list);
printf(" after sort: ");
list_print(&list);
list_destroy(&list);
return 0;
}
| package main
import (
"container/list"
"fmt"
)
type BinaryTree struct {
node int
leftSubTree *BinaryTree
rightSubTree *BinaryTree
}
func (bt *BinaryTree) insert(item int) {
if bt.node == 0 {
bt.node = item
bt.leftSubTree = &BinaryTree{}
bt.rightSubTree = &BinaryTree{}
} else if item < bt.node {
bt.leftSubTree.insert(item)
} else {
bt.rightSubTree.insert(item)
}
}
func (bt *BinaryTree) inOrder(ll *list.List) {
if bt.node == 0 {
return
}
bt.leftSubTree.inOrder(ll)
ll.PushBack(bt.node)
bt.rightSubTree.inOrder(ll)
}
func treeSort(ll *list.List) *list.List {
searchTree := &BinaryTree{}
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
searchTree.insert(i)
}
ll2 := list.New()
searchTree.inOrder(ll2)
return ll2
}
func printLinkedList(ll *list.List, f string, sorted bool) {
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
fmt.Printf(f+" ", i)
}
if !sorted {
fmt.Print("-> ")
} else {
fmt.Println()
}
}
func main() {
sl := []int{5, 3, 7, 9, 1}
ll := list.New()
for _, i := range sl {
ll.PushBack(i)
}
printLinkedList(ll, "%d", false)
lls := treeSort(ll)
printLinkedList(lls, "%d", true)
sl2 := []int{'d', 'c', 'e', 'b', 'a'}
ll2 := list.New()
for _, c := range sl2 {
ll2.PushBack(c)
}
printLinkedList(ll2, "%c", false)
lls2 := treeSort(ll2)
printLinkedList(lls2, "%c", true)
}
|
Write a version of this C function in Go with identical behavior. | #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int issquare( int p ) {
int i;
for(i=0;i*i<p;i++);
return i*i==p;
}
int main(void) {
int i=3, j=2;
for(i=3;j<=1000000;i=j) {
j=nextprime(i);
if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
}
return 0;
}
| package main
import (
"fmt"
"math"
"rcu"
)
func main() {
limit := 999999
primes := rcu.Primes(limit)
fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:")
for i := 1; i < len(primes); i++ {
diff := primes[i] - primes[i-1]
if diff > 36 {
s := int(math.Sqrt(float64(diff)))
if diff == s*s {
cp1 := rcu.Commatize(primes[i])
cp2 := rcu.Commatize(primes[i-1])
fmt.Printf("%7s - %7s = %3d = %2d x %2d\n", cp1, cp2, diff, s, s)
}
}
}
}
|
Change the programming language of this snippet from C to Go without modifying what it does. | #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int issquare( int p ) {
int i;
for(i=0;i*i<p;i++);
return i*i==p;
}
int main(void) {
int i=3, j=2;
for(i=3;j<=1000000;i=j) {
j=nextprime(i);
if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
}
return 0;
}
| package main
import (
"fmt"
"math"
"rcu"
)
func main() {
limit := 999999
primes := rcu.Primes(limit)
fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:")
for i := 1; i < len(primes); i++ {
diff := primes[i] - primes[i-1]
if diff > 36 {
s := int(math.Sqrt(float64(diff)))
if diff == s*s {
cp1 := rcu.Commatize(primes[i])
cp2 := rcu.Commatize(primes[i-1])
fmt.Printf("%7s - %7s = %3d = %2d x %2d\n", cp1, cp2, diff, s, s)
}
}
}
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
| import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
|
Write the same algorithm in Go as shown in this C implementation. | #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
| import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
|
Preserve the algorithm and functionality while converting the code from C to Go. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_xrandr(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 8];
strcpy(command, "xrandr ");
strcat(command, arg);
system(command);
}
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr;
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "video_display_modes.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
| package main
import (
"fmt"
"log"
"os/exec"
"time"
)
func main() {
out, err := exec.Command("xrandr", "-q").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1024x768").Run()
if err != nil {
log.Fatal(err)
}
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1366x768").Run()
if err != nil {
log.Fatal(err)
}
}
|
Translate the given C code snippet into Go without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_xrandr(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 8];
strcpy(command, "xrandr ");
strcat(command, arg);
system(command);
}
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr;
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "video_display_modes.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
| package main
import (
"fmt"
"log"
"os/exec"
"time"
)
func main() {
out, err := exec.Command("xrandr", "-q").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1024x768").Run()
if err != nil {
log.Fatal(err)
}
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1366x768").Run()
if err != nil {
log.Fatal(err)
}
}
|
Convert this C block to Go, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char text[256];
getchar();
fseek(stdin, 0, SEEK_END);
fgets(text, sizeof(text), stdin);
puts(text);
return EXIT_SUCCESS;
}
| package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
_, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
gc.FlushInput()
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include <stdio.h>
#include <math.h>
typedef struct { double m; double fm; double simp; } triple;
triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = f(m);
double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);
triple t = {m, fm, simp};
return t;
}
double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {
triple lt = _quad_simpsons_mem(f, a, fa, m, fm);
triple rt = _quad_simpsons_mem(f, m, fm, b, fb);
double delta = lt.simp + rt.simp - whole;
if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;
return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);
}
double quad_asr(double (*f)(double), double a, double b, double eps) {
double fa = f(a);
double fb = f(b);
triple t = _quad_simpsons_mem(f, a, fa, b, fb);
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);
}
int main(){
double a = 0.0, b = 1.0;
double sinx = quad_asr(sin, a, b, 1e-09);
printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx);
return 0;
}
| package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
|
Transform the following C implementation into Go, maintaining the same output and logic. | #include <stdio.h>
#include <math.h>
typedef struct { double m; double fm; double simp; } triple;
triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = f(m);
double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);
triple t = {m, fm, simp};
return t;
}
double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {
triple lt = _quad_simpsons_mem(f, a, fa, m, fm);
triple rt = _quad_simpsons_mem(f, m, fm, b, fb);
double delta = lt.simp + rt.simp - whole;
if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;
return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);
}
double quad_asr(double (*f)(double), double a, double b, double eps) {
double fa = f(a);
double fb = f(b);
triple t = _quad_simpsons_mem(f, a, fa, b, fb);
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);
}
int main(){
double a = 0.0, b = 1.0;
double sinx = quad_asr(sin, a, b, 1e-09);
printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx);
return 0;
}
| package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
|
Produce a language-to-language conversion: from C to Go, same semantics. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("fasta.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
int state = 0;
while ((read = getline(&line, &len, fp)) != -1) {
if (line[read - 1] == '\n')
line[read - 1] = 0;
if (line[0] == '>') {
if (state == 1)
printf("\n");
printf("%s: ", line+1);
state = 1;
} else {
printf("%s", line);
}
}
printf("\n");
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
| package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.Open("rc.fasta")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
headerFound := false
for s.Scan() {
line := s.Text()
switch {
case line == "":
continue
case line[0] != '>':
if !headerFound {
fmt.Println("missing header")
return
}
fmt.Print(line)
case headerFound:
fmt.Println()
fallthrough
default:
fmt.Printf("%s: ", line[1:])
headerFound = true
}
}
if headerFound {
fmt.Println()
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
}
|
Can you help me rewrite this code in Go instead of C, keeping it the same logically? | #include <stdio.h>
#include <string.h>
#define LIMIT 1000
void sieve(int max, char *s) {
int p, k;
memset(s, 0, max);
for (p=2; p*p<=max; p++)
if (!s[p])
for (k=p*p; k<=max; k+=p)
s[k]=1;
}
int main(void) {
char primes[LIMIT+1];
int p, count=0;
sieve(LIMIT, primes);
for (p=2; p<=LIMIT; p++) {
if (!primes[p] && !primes[p+4]) {
count++;
printf("%4d: %4d\n", p, p+4);
}
}
printf("There are %d cousin prime pairs below %d.\n", count, LIMIT);
return 0;
}
| package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func main() {
count := 0
fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
for i := 3; i <= 995; i += 2 {
if isPrime(i) && isPrime(i+4) {
fmt.Printf("%3d:%3d ", i, i+4)
count++
if count%7 == 0 {
fmt.Println()
}
if i != 3 {
i += 4
} else {
i += 2
}
}
}
fmt.Printf("\n\n%d pairs found\n", count)
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <stdio.h>
#include <string.h>
#define LIMIT 1000
void sieve(int max, char *s) {
int p, k;
memset(s, 0, max);
for (p=2; p*p<=max; p++)
if (!s[p])
for (k=p*p; k<=max; k+=p)
s[k]=1;
}
int main(void) {
char primes[LIMIT+1];
int p, count=0;
sieve(LIMIT, primes);
for (p=2; p<=LIMIT; p++) {
if (!primes[p] && !primes[p+4]) {
count++;
printf("%4d: %4d\n", p, p+4);
}
}
printf("There are %d cousin prime pairs below %d.\n", count, LIMIT);
return 0;
}
| package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func main() {
count := 0
fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
for i := 3; i <= 995; i += 2 {
if isPrime(i) && isPrime(i+4) {
fmt.Printf("%3d:%3d ", i, i+4)
count++
if count%7 == 0 {
fmt.Println()
}
if i != 3 {
i += 4
} else {
i += 2
}
}
}
fmt.Printf("\n\n%d pairs found\n", count)
}
|
Generate an equivalent Go version of this C code. | #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
| package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
| package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
|
Port the provided C code into Go while preserving the original functionality. | #include <unistd.h>
#include <stdio.h>
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
}
| package main
import (
"golang.org/x/crypto/ssh/terminal"
"fmt"
"os"
)
func main() {
if terminal.IsTerminal(int(os.Stdin.Fd())) {
fmt.Println("Hello terminal")
} else {
fmt.Println("Who are you? You're not a terminal.")
}
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <unistd.h>
#include <stdio.h>
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
}
| package main
import (
"golang.org/x/crypto/ssh/terminal"
"fmt"
"os"
)
func main() {
if terminal.IsTerminal(int(os.Stdin.Fd())) {
fmt.Println("Hello terminal")
} else {
fmt.Println("Who are you? You're not a terminal.")
}
}
|
Convert this C snippet to Go and keep its semantics consistent. | '--- added a flush to exit cleanly
PRAGMA LDFLAGS `pkg-config --cflags --libs x11`
PRAGMA INCLUDE <X11/Xlib.h>
PRAGMA INCLUDE <X11/Xutil.h>
OPTION PARSE FALSE
'---XLIB is so ugly
ALIAS XNextEvent TO EVENT
ALIAS XOpenDisplay TO DISPLAY
ALIAS DefaultScreen TO SCREEN
ALIAS XCreateSimpleWindow TO CREATE
ALIAS XCloseDisplay TO CLOSE_DISPLAY
ALIAS XSelectInput TO EVENT_TYPE
ALIAS XMapWindow TO MAP_EVENT
ALIAS XFillRectangle TO FILL_RECTANGLE
ALIAS XDrawString TO DRAW_STRING
ALIAS XFlush TO FLUSH
'---pointer to X Display structure
DECLARE d TYPE Display*
'---pointer to the newly created window
'DECLARE w TYPE WINDOW
'---pointer to the XEvent
DECLARE e TYPE XEvent
DECLARE msg TYPE char*
'--- number of screen to place the window on
DECLARE s TYPE int
msg = "Hello, World!"
d = DISPLAY(NULL)
IF d == NULL THEN
EPRINT "Cannot open display" FORMAT "%s%s\n"
END
END IF
s = SCREEN(d)
w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))
EVENT_TYPE(d, w, ExposureMask | KeyPressMask)
MAP_EVENT(d, w)
WHILE (1)
EVENT(d, &e)
IF e.type == Expose THEN
FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)
DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))
END IF
IF e.type == KeyPress THEN
BREAK
END IF
WEND
FLUSH(d)
CLOSE_DISPLAY(d)
| package main
import (
"log"
"github.com/jezek/xgb"
"github.com/jezek/xgb/xproto"
)
func main() {
X, err := xgb.NewConn()
if err != nil {
log.Fatal(err)
}
points := []xproto.Point{
{10, 10},
{10, 20},
{20, 10},
{20, 20}};
polyline := []xproto.Point{
{50, 10},
{ 5, 20},
{25,-20},
{10, 10}};
segments := []xproto.Segment{
{100, 10, 140, 30},
{110, 25, 130, 60}};
rectangles := []xproto.Rectangle{
{ 10, 50, 40, 20},
{ 80, 50, 10, 40}};
arcs := []xproto.Arc{
{10, 100, 60, 40, 0, 90 << 6},
{90, 100, 55, 40, 0, 270 << 6}};
setup := xproto.Setup(X)
screen := setup.DefaultScreen(X)
foreground, _ := xproto.NewGcontextId(X)
mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)
values := []uint32{screen.BlackPixel, 0}
xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)
win, _ := xproto.NewWindowId(X)
winDrawable := xproto.Drawable(win)
mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)
values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}
xproto.CreateWindow(X,
screen.RootDepth,
win,
screen.Root,
0, 0,
150, 150,
10,
xproto.WindowClassInputOutput,
screen.RootVisual,
mask, values)
xproto.MapWindow(X, win)
for {
evt, err := X.WaitForEvent()
switch evt.(type) {
case xproto.ExposeEvent:
xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)
xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)
xproto.PolySegment(X, winDrawable, foreground, segments)
xproto.PolyRectangle(X, winDrawable, foreground, rectangles)
xproto.PolyArc(X, winDrawable, foreground, arcs)
default:
}
if err != nil {
log.Fatal(err)
}
}
return
}
|
Write the same code in Go as shown below in C. | #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++)
if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
state |= B(i);
}
printf(" %d", b);
}
putchar('\n');
return;
}
int main(void)
{
evolve(1, 30);
return 0;
}
| package main
import "fmt"
const n = 64
func pow2(x uint) uint64 {
return uint64(1) << x
}
func evolve(state uint64, rule int) {
for p := 0; p < 10; p++ {
b := uint64(0)
for q := 7; q >= 0; q-- {
st := state
b |= (st & 1) << uint(q)
state = 0
for i := uint(0); i < n; i++ {
var t1, t2, t3 uint64
if i > 0 {
t1 = st >> (i - 1)
} else {
t1 = st >> 63
}
if i == 0 {
t2 = st << 1
} else if i == 1 {
t2 = st << 63
} else {
t2 = st << (n + 1 - i)
}
t3 = 7 & (t1 | t2)
if (uint64(rule) & pow2(uint(t3))) != 0 {
state |= pow2(i)
}
}
}
fmt.Printf("%d ", b)
}
fmt.Println()
}
func main() {
evolve(1, 30)
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <sys/ioctl.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int
main()
{
struct winsize ws;
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
err(1, "/dev/tty");
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, "/dev/tty");
printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
}
| package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
}
|
Convert this C block to Go, preserving its control flow and logic. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;
typedef struct statechange {
const int in;
const State out;
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State state;
void (*Action)(void);
const statechange table[MAXINPUTS];
} FSM;
char str[10];
void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); }
void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); }
void Refund(void) { fprintf(stderr, "Please collect refund.\n"); }
void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); }
void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); }
void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); }
const FSM fsm[] = {
{ READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }},
{ WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }},
{ REFUND, &Refund, {{ -1, READY} }},
{ DISPENSE, &Dispense, {{ -1, COLLECT} }},
{ COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }},
{ QUIT, &Quit, {{ -1, QUIT} }},
};
int each;
State state = READY;
for (;;) {
fsm[state].Action();
each = 0;
while (!( ((fsm[state].table[each].in == -1)
|| (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;
state = fsm[state].table[each].out;
}
return 0;
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
type state int
const (
ready state = iota
waiting
exit
dispense
refunding
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func fsm() {
fmt.Println("Please enter your option when prompted")
fmt.Println("(any characters after the first will be ignored)")
state := ready
var trans string
scanner := bufio.NewScanner(os.Stdin)
for {
switch state {
case ready:
for {
fmt.Print("\n(D)ispense or (Q)uit : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'd' {
state = waiting
break
} else if option == 'q' {
state = exit
break
}
}
case waiting:
fmt.Println("OK, put your money in the slot")
for {
fmt.Print("(S)elect product or choose a (R)efund : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 's' {
state = dispense
break
} else if option == 'r' {
state = refunding
break
}
}
case dispense:
for {
fmt.Print("(R)emove product : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'r' {
state = ready
break
}
}
case refunding:
fmt.Println("OK, refunding your money")
state = ready
case exit:
fmt.Println("OK, quitting")
return
}
}
}
func main() {
fsm()
}
|
Please provide an equivalent version of this C code in Go. |
#include<graphics.h>
void vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)
{
int color = 1,i,x = winWidth/2, y = winHeight/2;
while(!kbhit()){
setcolor(color++);
for(i=num;i>0;i--){
rectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);
delay(msec);
}
if(color>MAXCOLORS){
color = 1;
}
}
}
int main()
{
initwindow(1000,1000,"Vibrating Rectangles...");
vibratingRectangles(1000,1000,30,15,20,500);
closegraph();
return 0;
}
| package main
import (
"image"
"image/color"
"image/gif"
"log"
"os"
)
var (
black = color.RGBA{0, 0, 0, 255}
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
yellow = color.RGBA{255, 255, 0, 255}
white = color.RGBA{255, 255, 255, 255}
)
var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}
func hline(img *image.Paletted, x1, y, x2 int, ci uint8) {
for ; x1 <= x2; x1++ {
img.SetColorIndex(x1, y, ci)
}
}
func vline(img *image.Paletted, x, y1, y2 int, ci uint8) {
for ; y1 <= y2; y1++ {
img.SetColorIndex(x, y1, ci)
}
}
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 drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
hline(img, x1, y1, x2, ci)
hline(img, x1, y2, x2, ci)
vline(img, x1, y1, y2, ci)
vline(img, x2, y1, y2, ci)
}
func main() {
const nframes = 140
const delay = 10
width, height := 500, 500
anim := gif.GIF{LoopCount: nframes}
rect := image.Rect(0, 0, width, height)
for c := uint8(0); c < 7; c++ {
for f := 0; f < 20; f++ {
img := image.NewPaletted(rect, palette)
setBackgroundColor(img, width, height, 7)
for r := 0; r < 20; r++ {
ix := c
if r < f {
ix = (ix + 1) % 7
}
x := width * (r + 1) / 50
y := height * (r + 1) / 50
w := width - x
h := height - y
drawRectangle(img, x, y, w, h, ix)
}
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
}
file, err := os.Create("vibrating.gif")
if err != nil {
log.Fatal(err)
}
defer file.Close()
if err2 := gif.EncodeAll(file, &anim); err != nil {
log.Fatal(err2)
}
}
|
Ensure the translated Go code behaves exactly like the original C snippet. | #include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
int aa = *(const int *)a;
int bb = *(const int *)b;
if (aa < bb) return -1;
if (aa > bb) return 1;
return 0;
}
int main() {
int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};
int isize = sizeof(int);
int asize = sizeof(a) / isize;
int i, sum;
while (asize > 1) {
qsort(a, asize, isize, compare);
printf("Sorted list: ");
for (i = 0; i < asize; ++i) printf("%d ", a[i]);
printf("\n");
sum = a[0] + a[1];
printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum);
for (i = 2; i < asize; ++i) a[i-2] = a[i];
a[asize - 2] = sum;
asize--;
}
printf("Last item is %d.\n", a[0]);
return 0;
}
| package main
import (
"fmt"
"sort"
)
func main() {
a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}
for len(a) > 1 {
sort.Ints(a)
fmt.Println("Sorted list:", a)
sum := a[0] + a[1]
fmt.Printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum)
a = append(a, sum)
a = a[2:]
}
fmt.Println("Last item is", a[0], "\b.")
}
|
Convert this C snippet to Go and keep its semantics consistent. | #include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
void C_play(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 5];
strcpy(command, "play ");
strcat(command, args);
system(command);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "play(_)") == 0) return C_play;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "audio_frequency_generator.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
freq := 0
for freq < 40 || freq > 10000 {
fmt.Print("Enter frequency in Hz (40 to 10000) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
freq, _ = strconv.Atoi(input)
}
freqS := strconv.Itoa(freq)
vol := 0
for vol < 1 || vol > 50 {
fmt.Print("Enter volume in dB (1 to 50) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
vol, _ = strconv.Atoi(input)
}
volS := strconv.Itoa(vol)
dur := 0.0
for dur < 2 || dur > 10 {
fmt.Print("Enter duration in seconds (2 to 10) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
dur, _ = strconv.ParseFloat(input, 64)
}
durS := strconv.FormatFloat(dur, 'f', -1, 64)
kind := 0
for kind < 1 || kind > 3 {
fmt.Print("Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
kind, _ = strconv.Atoi(input)
}
kindS := "sine"
if kind == 2 {
kindS = "square"
} else if kind == 3 {
kindS = "sawtooth"
}
args := []string{"-n", "synth", durS, kindS, freqS, "vol", volS, "dB"}
cmd := exec.Command("play", args...)
err := cmd.Run()
check(err)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
void C_play(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 5];
strcpy(command, "play ");
strcat(command, args);
system(command);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "play(_)") == 0) return C_play;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "audio_frequency_generator.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
freq := 0
for freq < 40 || freq > 10000 {
fmt.Print("Enter frequency in Hz (40 to 10000) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
freq, _ = strconv.Atoi(input)
}
freqS := strconv.Itoa(freq)
vol := 0
for vol < 1 || vol > 50 {
fmt.Print("Enter volume in dB (1 to 50) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
vol, _ = strconv.Atoi(input)
}
volS := strconv.Itoa(vol)
dur := 0.0
for dur < 2 || dur > 10 {
fmt.Print("Enter duration in seconds (2 to 10) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
dur, _ = strconv.ParseFloat(input, 64)
}
durS := strconv.FormatFloat(dur, 'f', -1, 64)
kind := 0
for kind < 1 || kind > 3 {
fmt.Print("Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
kind, _ = strconv.Atoi(input)
}
kindS := "sine"
if kind == 2 {
kindS = "square"
} else if kind == 3 {
kindS = "sawtooth"
}
args := []string{"-n", "synth", durS, kindS, freqS, "vol", volS, "dB"}
cmd := exec.Command("play", args...)
err := cmd.Run()
check(err)
}
|
Change the following C code into Go without altering its purpose. | #include <stdio.h>
#include <stdlib.h>
int isprime( int n ) {
int i;
if (n<2) return 0;
for(i=2; i*i<=n; i++) {
if (n % i == 0) {return 0;}
}
return 1;
}
int main(void) {
int n = 0, p = 1;
while (n<22) {
printf( "%d ", n );
p++;
if (isprime(p)) n+=1;
}
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(79)
ix := 0
n := 1
count := 0
var pi []int
for {
if primes[ix] <= n {
count++
if count == 22 {
break
}
ix++
}
n++
pi = append(pi, count)
}
fmt.Println("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
for i, n := range pi {
fmt.Printf("%2d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
}
|
Produce a functionally identical Go code for the snippet given in C. | #include <stdio.h>
#include <stdlib.h>
int isprime( int n ) {
int i;
if (n<2) return 0;
for(i=2; i*i<=n; i++) {
if (n % i == 0) {return 0;}
}
return 1;
}
int main(void) {
int n = 0, p = 1;
while (n<22) {
printf( "%d ", n );
p++;
if (isprime(p)) n+=1;
}
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(79)
ix := 0
n := 1
count := 0
var pi []int
for {
if primes[ix] <= n {
count++
if count == 22 {
break
}
ix++
}
n++
pi = append(pi, count)
}
fmt.Println("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
for i, n := range pi {
fmt.Printf("%2d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
}
|
Convert this C snippet to Go and keep its semantics consistent. | #include <stdio.h>
int min(int a, int b) {
if (a < b) return a;
return b;
}
int main() {
int n;
int numbers1[5] = {5, 45, 23, 21, 67};
int numbers2[5] = {43, 22, 78, 46, 38};
int numbers3[5] = {9, 98, 12, 98, 53};
int numbers[5] = {};
for (n = 0; n < 5; ++n) {
numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);
printf("%d ", numbers[n]);
}
printf("\n");
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
numbers1 := [5]int{5, 45, 23, 21, 67}
numbers2 := [5]int{43, 22, 78, 46, 38}
numbers3 := [5]int{9, 98, 12, 98, 53}
numbers := [5]int{}
for n := 0; n < 5; n++ {
numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])
}
fmt.Println(numbers)
}
|
Produce a language-to-language conversion: from C to Go, same semantics. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
| package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
| package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
|
Preserve the algorithm and functionality while converting the code from C to Go. | #include <math.h>
#include <stdint.h>
#include <stdio.h>
const uint64_t N = 6364136223846793005;
static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;
uint32_t pcg32_int() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double pcg32_float() {
return ((double)pcg32_int()) / (1LL << 32);
}
void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
pcg32_int();
state = state + seed_state;
pcg32_int();
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
pcg32_seed(42, 54);
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("\n");
pcg32_seed(987654321, 1);
for (i = 0; i < 100000; i++) {
int j = (int)floor(pcg32_float() * 5.0);
counts[j]++;
}
printf("The counts for 100,000 repetitions are:\n");
for (i = 0; i < 5; i++) {
printf(" %d : %d\n", i, counts[i]);
}
return 0;
}
| package main
import (
"fmt"
"math"
)
const CONST = 6364136223846793005
type Pcg32 struct{ state, inc uint64 }
func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }
func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
pcg.state = 0
pcg.inc = (seedSequence << 1) | 1
pcg.nextInt()
pcg.state = pcg.state + seedState
pcg.nextInt()
}
func (pcg *Pcg32) nextInt() uint32 {
old := pcg.state
pcg.state = old*CONST + pcg.inc
pcgshifted := uint32(((old >> 18) ^ old) >> 27)
rot := uint32(old >> 59)
return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}
func (pcg *Pcg32) nextFloat() float64 {
return float64(pcg.nextInt()) / (1 << 32)
}
func main() {
randomGen := Pcg32New()
randomGen.seed(42, 54)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321, 1)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
|
Write a version of this C function in Go with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx t = cexp(-I * PI * i / n) * out[i + step];
buf[i / 2] = out[i] + t;
buf[(i + n)/2] = out[i] - t;
}
}
}
void fft(cplx buf[], int n)
{
cplx out[n];
for (int i = 0; i < n; i++) out[i] = buf[i];
_fft(buf, out, n, 1);
}
cplx *pad_two(double g[], int len, int *ns)
{
int n = 1;
if (*ns) n = *ns;
else while (n < len) n *= 2;
cplx *buf = calloc(sizeof(cplx), n);
for (int i = 0; i < len; i++) buf[i] = g[i];
*ns = n;
return buf;
}
void deconv(double g[], int lg, double f[], int lf, double out[]) {
int ns = 0;
cplx *g2 = pad_two(g, lg, &ns);
cplx *f2 = pad_two(f, lf, &ns);
fft(g2, ns);
fft(f2, ns);
cplx h[ns];
for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];
fft(h, ns);
for (int i = 0; i >= lf - lg; i--)
out[-i] = h[(i + ns) % ns]/32;
free(g2);
free(f2);
}
int main()
{
PI = atan2(1,1) * 4;
double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};
double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };
double h[] = { -8,-9,-3,-1,-6,7 };
int lg = sizeof(g)/sizeof(double);
int lf = sizeof(f)/sizeof(double);
int lh = sizeof(h)/sizeof(double);
double h2[lh];
double f2[lf];
printf("f[] data is : ");
for (int i = 0; i < lf; i++) printf(" %g", f[i]);
printf("\n");
printf("deconv(g, h): ");
deconv(g, lg, h, lh, f2);
for (int i = 0; i < lf; i++) printf(" %g", f2[i]);
printf("\n");
printf("h[] data is : ");
for (int i = 0; i < lh; i++) printf(" %g", h[i]);
printf("\n");
printf("deconv(g, f): ");
deconv(g, lg, f, lf, h2);
for (int i = 0; i < lh; i++) printf(" %g", h2[i]);
printf("\n");
}
| package main
import "fmt"
func main() {
h := []float64{-8, -9, -3, -1, -6, 7}
f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7}
fmt.Println(h)
fmt.Println(deconv(g, f))
fmt.Println(f)
fmt.Println(deconv(g, h))
}
func deconv(g, f []float64) []float64 {
h := make([]float64, len(g)-len(f)+1)
for n := range h {
h[n] = g[n]
var lower int
if n >= len(f) {
lower = n - len(f) + 1
}
for i := lower; i < n; i++ {
h[n] -= h[i] * f[n-i]
}
h[n] /= f[0]
}
return h
}
|
Please provide an equivalent version of this C code in Go. |
void print_jpg(image img, int qual);
| package main
import (
"fmt"
"math/rand"
"os/exec"
"raster"
)
func main() {
b := raster.NewBitmap(400, 300)
b.FillRgb(0xc08040)
for i := 0; i < 2000; i++ {
b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)
}
for x := 0; x < 400; x++ {
for y := 240; y < 245; y++ {
b.SetPxRgb(x, y, 0x804020)
}
for y := 260; y < 265; y++ {
b.SetPxRgb(x, y, 0x804020)
}
}
for y := 0; y < 300; y++ {
for x := 80; x < 85; x++ {
b.SetPxRgb(x, y, 0x804020)
}
for x := 95; x < 100; x++ {
b.SetPxRgb(x, y, 0x804020)
}
}
c := exec.Command("cjpeg", "-outfile", "pipeout.jpg")
pipe, err := c.StdinPipe()
if err != nil {
fmt.Println(err)
return
}
err = c.Start()
if err != nil {
fmt.Println(err)
return
}
err = b.WritePpmTo(pipe)
if err != nil {
fmt.Println(err)
return
}
err = pipe.Close()
if err != nil {
fmt.Println(err)
}
}
|
Convert the following code from C to Go, ensuring the logic remains intact. | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
| package main
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"golang.org/x/crypto/ripemd160"
)
type Point struct {
x, y [32]byte
}
func (p *Point) SetHex(x, y string) error {
if len(x) != 64 || len(y) != 64 {
return errors.New("invalid hex string length")
}
if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {
return err
}
_, err := hex.Decode(p.y[:], []byte(y))
return err
}
type A25 [25]byte
func (a *A25) doubleSHA256() []byte {
h := sha256.New()
h.Write(a[:21])
d := h.Sum([]byte{})
h = sha256.New()
h.Write(d)
return h.Sum(d[:0])
}
func (a *A25) UpdateChecksum() {
copy(a[21:], a.doubleSHA256())
}
func (a *A25) SetPoint(p *Point) {
c := [65]byte{4}
copy(c[1:], p.x[:])
copy(c[33:], p.y[:])
h := sha256.New()
h.Write(c[:])
s := h.Sum([]byte{})
h = ripemd160.New()
h.Write(s)
h.Sum(a[1:1])
a.UpdateChecksum()
}
var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
func (a *A25) A58() []byte {
var out [34]byte
for n := 33; n >= 0; n-- {
c := 0
for i := 0; i < 25; i++ {
c = c*256 + int(a[i])
a[i] = byte(c / 58)
c %= 58
}
out[n] = tmpl[c]
}
i := 1
for i < 34 && out[i] == '1' {
i++
}
return out[i-1:]
}
func main() {
var p Point
err := p.SetHex(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6")
if err != nil {
fmt.Println(err)
return
}
var a A25
a.SetPoint(&p)
fmt.Println(string(a.A58()))
}
|
Write a version of this C function in Go with identical behavior. | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
| package main
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"golang.org/x/crypto/ripemd160"
)
type Point struct {
x, y [32]byte
}
func (p *Point) SetHex(x, y string) error {
if len(x) != 64 || len(y) != 64 {
return errors.New("invalid hex string length")
}
if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {
return err
}
_, err := hex.Decode(p.y[:], []byte(y))
return err
}
type A25 [25]byte
func (a *A25) doubleSHA256() []byte {
h := sha256.New()
h.Write(a[:21])
d := h.Sum([]byte{})
h = sha256.New()
h.Write(d)
return h.Sum(d[:0])
}
func (a *A25) UpdateChecksum() {
copy(a[21:], a.doubleSHA256())
}
func (a *A25) SetPoint(p *Point) {
c := [65]byte{4}
copy(c[1:], p.x[:])
copy(c[33:], p.y[:])
h := sha256.New()
h.Write(c[:])
s := h.Sum([]byte{})
h = ripemd160.New()
h.Write(s)
h.Sum(a[1:1])
a.UpdateChecksum()
}
var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
func (a *A25) A58() []byte {
var out [34]byte
for n := 33; n >= 0; n-- {
c := 0
for i := 0; i < 25; i++ {
c = c*256 + int(a[i])
a[i] = byte(c / 58)
c %= 58
}
out[n] = tmpl[c]
}
i := 1
for i < 34 && out[i] == '1' {
i++
}
return out[i-1:]
}
func main() {
var p Point
err := p.SetHex(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6")
if err != nil {
fmt.Println(err)
return
}
var a A25
a.SetPoint(&p)
fmt.Println(string(a.A58()))
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
| package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16s : %s\n", name, name2)
}
}
|
Produce a functionally identical Go code for the snippet given in C. | #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
| package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16s : %s\n", name, name2)
}
}
|
Write the same code in Go as shown below in C. | #include<gl/freeglut.h>
double rot = 0;
float matCol[] = {1,0,0,0};
void display(){
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(30,1,1,0);
glRotatef(rot,0,1,1);
glMaterialfv(GL_FRONT,GL_DIFFUSE,matCol);
glutWireTeapot(0.5);
glPopMatrix();
glFlush();
}
void onIdle(){
rot += 0.01;
glutPostRedisplay();
}
void init(){
float pos[] = {1,1,1,0};
float white[] = {1,1,1,0};
float shini[] = {70};
glClearColor(.5,.5,.5,0);
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0,GL_AMBIENT,white);
glLightfv(GL_LIGHT0,GL_DIFFUSE,white);
glMaterialfv(GL_FRONT,GL_SHININESS,shini);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
}
int main(int argC, char* argV[])
{
glutInit(&argC,argV);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(900,700);
glutCreateWindow("The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.");
init();
glutDisplayFunc(display);
glutIdleFunc(onIdle);
glutMainLoop();
return 0;
}
| package main
import "C"
import "unsafe"
var rot = 0.0
var matCol = [4]C.float{1, 0, 0, 0}
func display() {
C.glClear(C.GL_COLOR_BUFFER_BIT | C.GL_DEPTH_BUFFER_BIT)
C.glPushMatrix()
C.glRotatef(30, 1, 1, 0)
C.glRotatef(C.float(rot), 0, 1, 1)
C.glMaterialfv(C.GL_FRONT, C.GL_DIFFUSE, &matCol[0])
C.glutWireTeapot(0.5)
C.glPopMatrix()
C.glFlush()
}
func onIdle() {
rot += 0.01
C.glutPostRedisplay()
}
func initialize() {
white := [4]C.float{1, 1, 1, 0}
shini := [1]C.float{70}
C.glClearColor(0.5, 0.5, 0.5, 0)
C.glShadeModel(C.GL_SMOOTH)
C.glLightfv(C.GL_LIGHT0, C.GL_AMBIENT, &white[0])
C.glLightfv(C.GL_LIGHT0, C.GL_DIFFUSE, &white[0])
C.glMaterialfv(C.GL_FRONT, C.GL_SHININESS, &shini[0])
C.glEnable(C.GL_LIGHTING)
C.glEnable(C.GL_LIGHT0)
C.glEnable(C.GL_DEPTH_TEST)
}
func main() {
argc := C.int(0)
C.glutInit(&argc, nil)
C.glutInitDisplayMode(C.GLUT_SINGLE | C.GLUT_RGB | C.GLUT_DEPTH)
C.glutInitWindowSize(900, 700)
tl := "The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut."
tlc := C.CString(tl)
C.glutCreateWindow(tlc)
initialize()
C.glutDisplayFunc(C.displayFunc())
C.glutIdleFunc(C.idleFunc())
C.glutMainLoop()
C.free(unsafe.Pointer(tlc))
}
|
Convert this C block to Go, preserving its control flow and logic. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
| package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
|
Generate an equivalent Go version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
| package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
|
Ensure the translated Go code behaves exactly like the original C snippet. | #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
initwindow(windowSide,windowSide,"Polygon Chaos");
vertices = (double**)malloc(numSides*sizeof(double*));
for(i=0;i<numSides;i++){
vertices[i] = (double*)malloc(2 * sizeof(double));
vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
sumX+= vertices[i][0];
sumY+= vertices[i][1];
putpixel(vertices[i][0],vertices[i][1],15);
}
srand((unsigned)time(&t));
seedX = sumX/numSides;
seedY = sumY/numSides;
putpixel(seedX,seedY,15);
for(i=0;i<iter;i++){
choice = rand()%numSides;
seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
putpixel(seedX,seedY,15);
}
free(vertices);
getch();
closegraph();
return 0;
}
| package main
import (
"github.com/fogleman/gg"
"image/color"
"math"
)
var (
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
)
var (
w, h = 640, 640
dc = gg.NewContext(w, h)
deg72 = gg.Radians(72)
scaleFactor = 1 / (2 + math.Cos(deg72)*2)
palette = [5]color.Color{red, green, blue, magenta, cyan}
colorIndex = 0
)
func drawPentagon(x, y, side float64, depth int) {
angle := 3 * deg72
if depth == 0 {
dc.MoveTo(x, y)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * side
y -= math.Sin(angle) * side
dc.LineTo(x, y)
angle += deg72
}
dc.SetColor(palette[colorIndex])
dc.Fill()
colorIndex = (colorIndex + 1) % 5
} else {
side *= scaleFactor
dist := side * (1 + math.Cos(deg72)*2)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * dist
y -= math.Sin(angle) * dist
drawPentagon(x, y, side, depth-1)
angle += deg72
}
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
order := 5
hw := float64(w / 2)
margin := 20.0
radius := hw - 2*margin
side := radius * math.Sin(math.Pi/5) * 2
drawPentagon(hw, 3*margin, side, order-1)
dc.SavePNG("sierpinski_pentagon.png")
}
|
Ensure the translated Go code behaves exactly like the original C snippet. | #include <stdio.h>
#define TRUE 1
#define FALSE 0
int isPrime(int n) {
int d;
if (n < 2) return FALSE;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
d = 5;
while (d*d <= n) {
if (!(n%d)) return FALSE;
d += 2;
if (!(n%d)) return FALSE;
d += 4;
}
return TRUE;
}
int max(int a, int b) {
if (a > b) return a;
return b;
}
int main() {
int n, m;
int numbers1[5] = { 5, 45, 23, 21, 67};
int numbers2[5] = {43, 22, 78, 46, 38};
int numbers3[5] = { 9, 98, 12, 54, 53};
int primes[5] = {};
for (n = 0; n < 5; ++n) {
m = max(max(numbers1[n], numbers2[n]), numbers3[n]);
if (!(m % 2)) m++;
while (!isPrime(m)) m += 2;
primes[n] = m;
printf("%d ", primes[n]);
}
printf("\n");
return 0;
}
| package main
import (
"fmt"
"rcu"
)
func main() {
numbers1 := [5]int{5, 45, 23, 21, 67}
numbers2 := [5]int{43, 22, 78, 46, 38}
numbers3 := [5]int{9, 98, 12, 54, 53}
primes := [5]int{}
for n := 0; n < 5; n++ {
max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])
if max % 2 == 0 {
max++
}
for !rcu.IsPrime(max) {
max += 2
}
primes[n] = max
}
fmt.Println(primes)
}
|
Keep all operations the same but rewrite the snippet in Go. | typedef unsigned int histogram_t;
typedef histogram_t *histogram;
#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )
histogram get_histogram(grayimage im);
luminance histogram_median(histogram h);
| package raster
import "math"
func (g *Grmap) Histogram(bins int) []int {
if bins <= 0 {
bins = g.cols
}
h := make([]int, bins)
for _, p := range g.px {
h[int(p)*(bins-1)/math.MaxUint16]++
}
return h
}
func (g *Grmap) Threshold(t uint16) {
for i, p := range g.px {
if p < t {
g.px[i] = 0
} else {
g.px[i] = math.MaxUint16
}
}
}
|
Port the provided C code into Go while preserving the original functionality. | #include <stdio.h>
void padovanN(int n, size_t t, int *p) {
int i, j;
if (n < 2 || t < 3) {
for (i = 0; i < t; ++i) p[i] = 1;
return;
}
padovanN(n-1, t, p);
for (i = n + 1; i < t; ++i) {
p[i] = 0;
for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
}
}
int main() {
int n, i;
const size_t t = 15;
int p[t];
printf("First %ld terms of the Padovan n-step number sequences:\n", t);
for (n = 2; n <= 8; ++n) {
for (i = 0; i < t; ++i) p[i] = 0;
padovanN(n, t, p);
printf("%d: ", n);
for (i = 0; i < t; ++i) printf("%3d ", p[i]);
printf("\n");
}
return 0;
}
| package main
import "fmt"
func padovanN(n, t int) []int {
if n < 2 || t < 3 {
ones := make([]int, t)
for i := 0; i < t; i++ {
ones[i] = 1
}
return ones
}
p := padovanN(n-1, t)
for i := n + 1; i < t; i++ {
p[i] = 0
for j := i - 2; j >= i-n-1; j-- {
p[i] += p[j]
}
}
return p
}
func main() {
t := 15
fmt.Println("First", t, "terms of the Padovan n-step number sequences:")
for n := 2; n <= 8; n++ {
fmt.Printf("%d: %3d\n", n, padovanN(n, t))
}
}
|
Generate a Go translation of this C snippet without changing its computational steps. | HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
| package main
import (
"fmt"
"sync"
"time"
)
var value int
var m sync.Mutex
var wg sync.WaitGroup
func slowInc() {
m.Lock()
v := value
time.Sleep(1e8)
value = v+1
m.Unlock()
wg.Done()
}
func main() {
wg.Add(2)
go slowInc()
go slowInc()
wg.Wait()
fmt.Println(value)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.