Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this Go block to C, preserving its control flow and logic.
package main import ( "flag" "fmt" "runtime/debug" ) func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) } func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
Keep all operations the same but rewrite the snippet in C.
package main import "fmt" func mod(n, m int) int { return ((n % m) + m) % m } func isPrime(n int) bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } d := 5 for d * d <= n { if n % d == 0 { return false } d += 2 if n % d ==...
#include <stdio.h> #define mod(n,m) ((((n) % (m)) + (m)) % (m)) int is_prime(unsigned int n) { if (n <= 3) { return n > 1; } else if (!(n % 2) || !(n % 3)) { return 0; } else { unsigned int i; for (i = 5; i*i <= n; i += 6) if (!(n % i) || !(n % (i + 2))...
Translate the given Go code snippet into C without altering its behavior.
package main import ( "fmt" "math" "rcu" "sort" ) func main() { arithmetic := []int{1} primes := []int{} limit := int(1e6) for n := 3; len(arithmetic) < limit; n++ { divs := rcu.Divisors(n) if len(divs) == 2 { primes = append(primes, n) arithmeti...
#include <stdio.h> void divisor_count_and_sum(unsigned int n, unsigned int* pcount, unsigned int* psum) { unsigned int divisor_count = 1; unsigned int divisor_sum = 1; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { ++divisor_count; diviso...
Rewrite the snippet below in C so it works the same as the original Go code.
package main import ( "fmt" "math" "rcu" "sort" ) func main() { arithmetic := []int{1} primes := []int{} limit := int(1e6) for n := 3; len(arithmetic) < limit; n++ { divs := rcu.Divisors(n) if len(divs) == 2 { primes = append(primes, n) arithmeti...
#include <stdio.h> void divisor_count_and_sum(unsigned int n, unsigned int* pcount, unsigned int* psum) { unsigned int divisor_count = 1; unsigned int divisor_sum = 1; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { ++divisor_count; diviso...
Ensure the translated C code behaves exactly like the original Go snippet.
package main import ( "code.google.com/p/x-go-binding/ui/x11" "fmt" "image" "image/color" "image/draw" "log" "os" "time" ) var randcol = genrandcol() func genrandcol() <-chan color.Color { c := make(chan color.Color) go func() { for { select { ...
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <SDL/SDL.h> unsigned int frames = 0; unsigned int t_acc = 0; void print_fps () { static Uint32 last_t = 0; Uint32 t = SDL_GetTicks(); Uint32 dt = t - last_t; t_acc += dt; if (t_acc > 1000) { unsigned int el_time = t_acc / 1000; pr...
Change the programming language of this snippet from Go to C without modifying what it does.
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() var k gc.Key for { gc.FlushInput() s.MovePrint(20, 0, "Press y/n ") s.Refresh() switch k = ...
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; } tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcsetat...
Write the same algorithm in C as shown in this Go implementation.
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() var k gc.Key for { gc.FlushInput() s.MovePrint(20, 0, "Press y/n ") s.Refresh() switch k = ...
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; } tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcsetat...
Write the same algorithm in C as shown in this Go implementation.
package main import "fmt" func computePerfect(n int64) bool { var sum int64 for i := int64(1); i < n; i++ { if n%i == 0 { sum += i } } return sum == n } func isPerfect(n int64) bool { switch n { case 6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2...
#include "stdio.h" #include "math.h" int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } ...
Translate the given Go code snippet into C without altering its behavior.
package main import ( "fmt" "math" "math/cmplx" ) type matrix struct { ele []complex128 cols int } func (m *matrix) conjTranspose() *matrix { r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} rx := 0 for _, e := range m.ele { r.ele[rx] = cmplx.Conj(e) ...
#include<stdlib.h> #include<stdio.h> #include<complex.h> typedef struct { int rows, cols; complex **z; } matrix; matrix transpose (matrix a) { int i, j; matrix b; b.rows = a.cols; b.cols = a.rows; b.z = malloc (b.rows * sizeof (complex *)); for (i = 0; i < b.rows; i++) { b.z[i] = malloc...
Generate an equivalent C version of this Go code.
package main import ( "fmt" "math" "math/cmplx" ) type matrix struct { ele []complex128 cols int } func (m *matrix) conjTranspose() *matrix { r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} rx := 0 for _, e := range m.ele { r.ele[rx] = cmplx.Conj(e) ...
#include<stdlib.h> #include<stdio.h> #include<complex.h> typedef struct { int rows, cols; complex **z; } matrix; matrix transpose (matrix a) { int i, j; matrix b; b.rows = a.cols; b.cols = a.rows; b.z = malloc (b.rows * sizeof (complex *)); for (i = 0; i < b.rows; i++) { b.z[i] = malloc...
Generate a C translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n...
#include <stdio.h> #include <gmp.h> void jacobsthal(mpz_t r, unsigned long n) { mpz_t s; mpz_init(s); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(s, 1); if (n % 2) mpz_neg(s, s); mpz_sub(r, r, s); mpz_div_ui(r, r, 3); } void jacobsthal_lucas(mpz_t r, unsigned long n) { mpz_...
Convert the following code from Go to C, ensuring the logic remains intact.
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n...
#include <stdio.h> #include <gmp.h> void jacobsthal(mpz_t r, unsigned long n) { mpz_t s; mpz_init(s); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(s, 1); if (n % 2) mpz_neg(s, s); mpz_sub(r, r, s); mpz_div_ui(r, r, 3); } void jacobsthal_lucas(mpz_t r, unsigned long n) { mpz_...
Keep all operations the same but rewrite the snippet in C.
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, ...
#include <stdio.h> #include <stdlib.h> void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j] for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) ...
Translate the given Go code snippet into C without altering its behavior.
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, ...
#include <stdio.h> #include <stdlib.h> void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j] for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) ...
Rewrite the snippet below in C so it works the same as the original Go code.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
#include <stdio.h> #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE]; void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { s...
Generate a C translation of this Go snippet without changing its computational steps.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
#include <stdio.h> #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE]; void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { s...
Please provide an equivalent version of this Go code in C.
package main import ( "fmt" "math/big" ) func main() { x := big.NewInt(2) x = x.Exp(big.NewInt(3), x, nil) x = x.Exp(big.NewInt(4), x, nil) x = x.Exp(big.NewInt(5), x, nil) str := x.String() fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n", len(str), str[:20], str[len(str)-20:], ) }
#include <gmp.h> #include <stdio.h> #include <string.h> int main() { mpz_t a; mpz_init_set_ui(a, 5); mpz_pow_ui(a, a, 1 << 18); int len = mpz_sizeinbase(a, 10); printf("GMP says size is: %d\n", len); char *s = mpz_get_str(0, 10, a); printf("size really is %d\n", len = strlen(s)); printf("Digits: %.20s...%...
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] +...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *shades = ".:!*oe&#%@"; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(...
Convert this Go snippet to C and keep its semantics consistent.
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] +...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *shades = ".:!*oe&#%@"; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(...
Convert the following code from Go to C, ensuring the logic remains intact.
package main import ( "bufio" "bytes" "errors" "fmt" "io" "os" ) var index map[string][]int var indexed []doc type doc struct { file string title string } func main() { index = make(map[string][]int) if err := indexDir("docs"); err != nil { fmt.Println(e...
#include <stdio.h> #include <stdlib.h> char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./"; int chr_idx[256] = {0}; char idx_chr[256] = {0}; #define FNAME 0 typedef struct trie_t *trie, trie_t; struct trie_t { trie next[sizeof(chr_legal)]; int eow; }; trie trie_new() { return calloc(sizeof(trie_t...
Ensure the translated C code behaves exactly like the original Go snippet.
package main import ( "bufio" "bytes" "errors" "fmt" "io" "os" ) var index map[string][]int var indexed []doc type doc struct { file string title string } func main() { index = make(map[string][]int) if err := indexDir("docs"); err != nil { fmt.Println(e...
#include <stdio.h> #include <stdlib.h> char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./"; int chr_idx[256] = {0}; char idx_chr[256] = {0}; #define FNAME 0 typedef struct trie_t *trie, trie_t; struct trie_t { trie next[sizeof(chr_legal)]; int eow; }; trie trie_new() { return calloc(sizeof(trie_t...
Generate an equivalent C version of this Go code.
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
Preserve the algorithm and functionality while converting the code from Go to C.
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
Write the same code in C as shown below in Go.
package main import "fmt" import "math/rand" import "time" func main() { rand.Seed(time.Now().UnixNano()) for { a := rand.Intn(20) fmt.Println(a) if a == 10 { break } b := rand.Intn(20) fmt.Println(b) } }
int main(){ time_t t; int a, b; srand((unsigned)time(&t)); for(;;){ a = rand() % 20; printf("%d\n", a); if(a == 10) break; b = rand() % 20; printf("%d\n", b); } return 0; }
Convert the following code from Go to C, ensuring the logic remains intact.
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
Write the same code in C as shown below in Go.
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
Translate this program into C but keep the logic exactly as in Go.
package main import "fmt" func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ m...
#include<stdlib.h> #include<stdio.h> int getWater(int* arr,int start,int end,int cutoff){ int i, sum = 0; for(i=start;i<=end;i++) sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0); return sum; } int netWater(int* arr,int size){ int i, j, ref1, ref2, marker, markerSet = 0,sum = 0; if(size<3) retu...
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, le...
#include <stdio.h> int ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return 0; return 1; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128], nxt[128]; for (a = 0, b = 1; a < pc; a = b++) ps[a] = b; ...
Translate the given Go code snippet into C without altering its behavior.
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true ...
#include <stdio.h> #include <stdlib.h> #include <math.h> #define TRUE 1 #define FALSE 0 #define TRILLION 1000000000000 typedef unsigned char bool; typedef unsigned long long uint64; void sieve(uint64 limit, uint64 *primes, uint64 *length) { uint64 i, count, p, p2; bool *c = calloc(limit + 1, sizeof(bool)); ...
Convert this Go block to C, preserving its control flow and logic.
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true ...
#include <stdio.h> #include <stdlib.h> #include <math.h> #define TRUE 1 #define FALSE 0 #define TRILLION 1000000000000 typedef unsigned char bool; typedef unsigned long long uint64; void sieve(uint64 limit, uint64 *primes, uint64 *length) { uint64 i, count, p, p2; bool *c = calloc(limit + 1, sizeof(bool)); ...
Change the following Go code into C without altering its purpose.
package main import "fmt" func jaro(str1, str2 string) float64 { if len(str1) == 0 && len(str2) == 0 { return 1 } if len(str1) == 0 || len(str2) == 0 { return 0 } match_distance := len(str1) if len(str2) > match_distance { match_distance = len(str2) } match_dist...
#include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #define TRUE 1 #define FALSE 0 #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) double jaro(const char *str1, const char *str2) { int str1_len = strlen(str1); int str2_len = strlen(str2)...
Write the same code in C as shown below in Go.
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all...
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct node_t { int x, y; struct node_t *prev, *next; } node; node *new_node(int x, int y) { node *n = malloc(sizeof(node)); n->x = x; n->y = y; n->next = NULL; n->prev = NULL; return n; } void free_node(node **n) { ...
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } retu...
#include <stdio.h> #include <stdlib.h> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { int i; printf("Base %2d:", base); for (i = 0; i < count; i++)...
Produce a language-to-language conversion: from Go to C, same semantics.
package main import ( "fmt" "math/rand" "strings" "time" ) var cylinder = [6]bool{} func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t } func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } fun...
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> static int nextInt(int size) { return rand() % size; } static bool cylinder[6]; static void rshift() { bool t = cylinder[5]; int i; for (i = 4; i >= 0; i--) { cylinder[i + 1] = cylinder[i]; }...
Translate this program into C but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) f...
#include <sys/types.h> #include <regex.h> #include <stdio.h> typedef struct { const char *s; int len, prec, assoc; } str_tok_t; typedef struct { const char * str; int assoc, prec; regex_t re; } pat_t; enum assoc { A_NONE, A_L, A_R }; pat_t pat_eos = {"", A_NONE, 0}; pat_t pat_ops[] = { {"^\\)", A_NONE, -1}, ...
Produce a functionally identical C code for the snippet given in Go.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) f...
#include <sys/types.h> #include <regex.h> #include <stdio.h> typedef struct { const char *s; int len, prec, assoc; } str_tok_t; typedef struct { const char * str; int assoc, prec; regex_t re; } pat_t; enum assoc { A_NONE, A_L, A_R }; pat_t pat_eos = {"", A_NONE, 0}; pat_t pat_ops[] = { {"^\\)", A_NONE, -1}, ...
Port the following code from Go to C with equivalent syntax and logic.
package main import "fmt" var canFollow [][]bool var arrang []int var bFirst = true var pmap = make(map[int]bool) func init() { for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} { pmap[i] = true } } func ptrs(res, n, done int) int { ad := arrang[done-1] if n-done <= 1 { ...
#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <time.h> bool is_prime(unsigned int n) { assert(n < 64); static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, ...
Convert the following code from Go to C, ensuring the logic remains intact.
package main import ( "fmt" "log" "math" ) func main() { fmt.Print("Enter 11 numbers: ") var s [11]float64 for i := 0; i < 11; { if n, _ := fmt.Scan(&s[i]); n > 0 { i++ } } for i, item := range s[:5] { s[i], s[10-i] = s[10-i], item ...
#include<math.h> #include<stdio.h> int main () { double inputs[11], check = 400, result; int i; printf ("\nPlease enter 11 numbers :"); for (i = 0; i < 11; i++) { scanf ("%lf", &inputs[i]); } printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"); for (i = 10; i >= 0; i-...
Convert this Go snippet to C and keep its semantics consistent.
package m3 import ( "errors" "strconv" ) var ( ErrorLT3 = errors.New("N of at least three digits required.") ErrorEven = errors.New("N with odd number of digits required.") ) func Digits(i int) (string, error) { if i < 0 { i = -i } if i < 100 { return "", ErrorLT3 } ...
#include <stdio.h> #include <stdlib.h> #include <string.h> char * mid3(int n) { static char buf[32]; int l; sprintf(buf, "%d", n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; } int main(void) { int x[] = {123, 12345, 1234567, 987654321, 10001...
Keep all operations the same but rewrite the snippet in C.
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if is...
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #define LIMIT 15 int smallPrimes[LIMIT]; static void sieve() { int i = 2, j; int p = 5; smallPrimes[0] = 2; smallPrimes[1] = 3; while (i < LIMIT) { for (j = 0; j < i; j++) { if (smallPrimes[j] * sma...
Convert this Go snippet to C and keep its semantics consistent.
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 seq :=...
#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, k, n, seq[MAX]; ...
Rewrite the snippet below in C so it works the same as the original Go code.
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) =...
#include <stdio.h> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { int i, j; for (i = 0; i < 4; i++) { for (j = 1; j < 6; j++) { int n = i * 5 + j; ...
Keep all operations the same but rewrite the snippet in C.
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) =...
#include <stdio.h> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { int i, j; for (i = 0; i < 4; i++) { for (j = 1; j < 6; j++) { int n = i * 5 + j; ...
Rewrite this program in C while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) ...
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <time.h> #define TRUE 1 #define FALSE 0 typedef int bool; char grid[8][8]; void placeKings() { int r1, r2, c1, c2; for (;;) { r1 = rand() % 8; c1 = rand() % 8; r2 = rand() % 8; c2 = rand() %...
Produce a functionally identical C code for the snippet given in Go.
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 { ...
#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...
Write a version of this Go function in C with identical behavior.
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 { ...
#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...
Convert the following code from Go to C, ensuring the logic remains intact.
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]++ ...
#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...
Port the following code from Go to C with equivalent syntax and logic.
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...
#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, ...
Keep all operations the same but rewrite the snippet in C.
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. ...
#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...
Please provide an equivalent version of this Go code in C.
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...
#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...
Translate the given Go code snippet into C without altering its behavior.
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...
#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...
Please provide an equivalent version of this Go code in C.
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...
#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...
Port the following code from Go to C with equivalent syntax and logic.
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 ...
#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...
Produce a language-to-language conversion: from Go to C, same semantics.
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...
#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; ...
Change the following Go code into C without altering its purpose.
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 ...
#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...
Write the same algorithm in C as shown in this Go implementation.
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...
#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 &&...
Produce a language-to-language conversion: from Go to C, same semantics.
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...
#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 &&...
Write the same algorithm in C as shown in this Go implementation.
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...
#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...
Maintain the same structure and functionality when rewriting this code in C.
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...
#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) ...
Keep all operations the same but rewrite the snippet in C.
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...
#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) ...
Change the programming language of this snippet from Go to C without modifying what it does.
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...
#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; ...
Translate this program into C but keep the logic exactly as in Go.
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) } }
#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...
Write the same algorithm in C as shown in this Go implementation.
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...
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
Change the following Go code into C without altering its purpose.
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...
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
Preserve the algorithm and functionality while converting the code from Go to C.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
#include <stdlib.h> #include "myutil.h"
Translate this program into C but keep the logic exactly as in Go.
package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
#include <stdlib.h> #include "myutil.h"
Generate a C translation of this Go snippet without changing its computational steps.
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...
#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_...
Transform the following Go implementation into C, maintaining the same output and logic.
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...
#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_...
Keep all operations the same but rewrite the snippet in C.
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...
#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_...
Maintain the same structure and functionality when rewriting this code in C.
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...
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++; }
Write the same code in C as shown below in Go.
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("")...
#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("...
Change the following Go code into C without altering its purpose.
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 ...
#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....
Rewrite the snippet below in C so it works the same as the original Go code.
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 ...
#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",...
Port the following code from Go to C with equivalent syntax and logic.
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 { ...
#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++] =...
Write the same algorithm in C as shown in this Go implementation.
package example var ( X, Y, Z int ) func XP() { } func nonXP() {} var MEMEME int
int add(int a, int b) { return a + b; }
Please provide an equivalent version of this Go code in C.
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, ...
#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...
Generate a C translation of this Go snippet without changing its computational steps.
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, ...
#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...
Produce a language-to-language conversion: from Go to C, same semantics.
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...
#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...
Change the programming language of this snippet from Go to C without modifying what it does.
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...
#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, ...
Keep all operations the same but rewrite the snippet in C.
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...
#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, ...
Port the provided Go code into C while preserving the original functionality.
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...
#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; }
Can you help me rewrite this code in C instead of Go, keeping it the same logically?
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...
#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; }
Produce a language-to-language conversion: from Go to C, same semantics.
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]) ...
#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...
Transform the following Go implementation into C, maintaining the same output and logic.
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...
#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...
Write the same algorithm in C as shown in this Go implementation.
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...
#include <stdlib.h>
Produce a language-to-language conversion: from Go to C, same semantics.
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...
#include <stdlib.h>
Change the programming language of this snippet from Go to C without modifying what it does.
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...
#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; }
Convert this Go block to C, preserving its control flow and logic.
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...
#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...
Preserve the algorithm and functionality while converting the code from Go to C.
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...
#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(&...
Write the same algorithm in C as shown in this Go implementation.
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 } } ...
#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 { ...
Write the same code in C as shown below in Go.
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 } } ...
#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 { ...
Write a version of this Go function in C with identical behavior.
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...
#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...
Maintain the same structure and functionality when rewriting this code in C.
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...
#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...
Change the following Go code into C without altering its purpose.
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...
#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 =...
Translate the given Go code snippet into C without altering its behavior.
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...
#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 =...
Ensure the translated C code behaves exactly like the original Go snippet.
#!/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 C.
#!/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("...
Produce a functionally identical C code for the snippet given in Go.
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") ...
#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...
Rewrite the snippet below in C so it works the same as the original Go code.
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") ...
#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...
Write the same algorithm in C as shown in this Go implementation.
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...
#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...