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 < le...
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 { ...
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] >= bes...
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]++ ...
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, ...
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.025...
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...
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. ...
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; pr...
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.Pr...
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 = r...
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(bi...
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 = r...
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(bi...
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...
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 ...
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; ...
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...
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 s...
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 ...
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 &&...
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 := m...
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 &&...
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 := m...
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 *m...
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.FindAll...
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) ...
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 f...
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) ...
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 f...
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; ...
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 uniq...
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) { p...
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 nd...
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 nd...
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_...
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...
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_...
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...
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_...
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...
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 []in...
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("...
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("")...
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....
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 ...
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",...
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 ...
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++] =...
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 { ...
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...
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, ...
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...
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, ...
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(v...
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 := c...
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, ...
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 newlyA...
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, ...
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 newlyA...
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...
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...
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 *hea...
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]) ...
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 na...
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 st...
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.P...
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.P...
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.P...
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<ros...
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...
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(&...
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(need...
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 { ...
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 } } ...
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 { ...
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 } } ...
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 *m...
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...
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 *m...
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...
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 =...
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...
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 =...
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...
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("...
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("...
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 ("Uni...
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 ("Uni...
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; struc...
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 = &Bina...
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; struc...
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 = &Bina...
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)); r...
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 { ...
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)); r...
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 { ...
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, ...
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, ...
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...
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() ...
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...
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() ...
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, ...
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) float...
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, ...
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) float...
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[r...
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() { ...
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...
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...
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...
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...
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(' ')...
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(...
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(' ')...
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(...
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 XCloseD...
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}}; ...
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++...
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 fo...
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...
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...
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 promp...
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*leastWi...
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 = colo...
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 a...
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) ...
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; wrenSetSlotStri...
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 (4...
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; wrenSetSlotStri...
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 (4...
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 =...
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 =...
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...
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]) ...
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) { ...
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 { re...
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) { ...
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 { re...
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) >> 2...
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 ...
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 ...
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(...
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 < 24...
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 ...
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 _,...
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 ...
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 _,...
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' ) ...
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"...
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' ) ...
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"...
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...
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]) ...
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; ...
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 := ...
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; ...
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 := ...
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...
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 ...
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; } ...
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...
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 { i...
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()...
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; ...
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(val...