Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ stk_##name stk_##name##_create(size_t init_size) { \ stk_##name s; if (!init_size) init_size = 4; \ s = malloc(sizeof(struct stk_##name##_t)); \ if (!s) return 0; \ s->buf = malloc(sizeof(type) * init_size); \ if (!s->buf) { free(s); return 0; } \ s->len = 0, s->alloc = init_size; \ return s; } \ int stk_##name##_push(stk_##name s, type item) { \ type *tmp; \ if (s->len >= s->alloc) { \ tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ if (!tmp) return -1; s->buf = tmp; \ s->alloc *= 2; } \ s->buf[s->len++] = item; \ return s->len; } \ type stk_##name##_pop(stk_##name s) { \ type tmp; \ if (!s->len) abort(); \ tmp = s->buf[--s->len]; \ if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ s->alloc /= 2; \ s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ return tmp; } \ void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) #define stk_size(s) ((s)->len) DECL_STACK_TYPE(int, int) int main(void) { int i; stk_int stk = stk_int_create(0); printf("pushing: "); for (i = 'a'; i <= 'z'; i++) { printf(" %c", i); stk_int_push(stk, i); } printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); printf("\npoppoing:"); while (stk_size(stk)) printf(" %c", stk_int_pop(stk)); printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); stk_int_delete(stk); return 0; }
var intStack []int
Write the same code in Go as shown below in C.
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { t >>= 1 } if t > 0 { n = t } else { k = -t } t = n - k } return n * s } func totient(n int) int { tot := 0 for k := 1; k <= n; k++ { if gcd(n, k) == 1 { tot++ } } return tot } func main() { fmt.Println(" n phi prime") fmt.Println("---------------") count := 0 for n := 1; n <= 25; n++ { tot := totient(n) isPrime := n-1 == tot if isPrime { count++ } fmt.Printf("%2d %2d %t\n", n, tot, isPrime) } fmt.Println("\nNumber of primes up to 25 =", count) for n := 26; n <= 100000; n++ { tot := totient(n) if tot == n-1 { count++ } if n == 100 || n == 1000 || n%10000 == 0 { fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count) } } }
Transform the following C implementation into Go, maintaining the same output and logic.
int a = 3; if (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } unless (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } switch (a) { case 2: puts ("a is 2"); break; case 3: puts ("a is 3"); break; case 4: puts ("a is 4"); break; default: puts("is neither"); }
if booleanExpression { statements }
Produce a language-to-language conversion: from C to Go, same semantics.
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); else gmp_printf(" %Zd", val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf("\nhalt: %Zd has no divisors\n", val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); return 0; }
package main import ( "fmt" "log" "math/big" "os" "strconv" "strings" ) func compile(src string) ([]big.Rat, bool) { s := strings.Fields(src) r := make([]big.Rat, len(s)) for i, s1 := range s { if _, ok := r[i].SetString(s1); !ok { return nil, false } } return r, true } func exec(p []big.Rat, n *big.Int, limit int) { var q, r big.Int rule: for i := 0; i < limit; i++ { fmt.Printf("%d ", n) for j := range p { q.QuoRem(n, p[j].Denom(), &r) if r.BitLen() == 0 { n.Mul(&q, p[j].Num()) continue rule } } break } fmt.Println() } func usage() { log.Fatal("usage: ft <limit> <n> <prog>") } func main() { if len(os.Args) != 4 { usage() } limit, err := strconv.Atoi(os.Args[1]) if err != nil { usage() } var n big.Int _, ok := n.SetString(os.Args[2], 10) if !ok { usage() } p, ok := compile(os.Args[3]) if !ok { usage() } exec(p, &n, limit) }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } int main(int argc, char *argv[]) { int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; int i, n; n = sizeof(nums)/sizeof(int); StoogeSort(nums, 0, n-1); for(i = 0; i <= n-1; i++) printf("%5d", nums[i]); return 0; }
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] } if last > 1 { t := len(a) / 3 stoogesort(a[:len(a)-t]) stoogesort(a[t:]) stoogesort(a[:len(a)-t]) } }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b; #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts("\033[H"), i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++, putchar(' ')) printf(B(i, j) == '*' ? C(i - 1, j) ? "\033[32m%c\033[m" : "\033[31m%c\033[m" : "%c", B(i, j)); } void init() { int i, j; puts("\033[H\033[J"); b = malloc(w * h); memset(b, ' ', w * h); x = malloc(sizeof(int) * BALLS * 2); y = x + BALLS; for (i = 0; i < n; i++) for (j = -i; j <= i; j += 2) B(2 * i+2, j + w/2) = '*'; srand(time(0)); } void move(int idx) { int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0; if (yy < 0) return; if (yy == h - 1) { y[idx] = -1; return; } switch(c = B(yy + 1, xx)) { case ' ': yy++; break; case '*': sl = 1; default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1)) if (!rnd(sl++)) o = 1; if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1)) if (!rnd(sl++)) o = -1; if (!o) kill = 1; xx += o; } c = V(idx); V(idx) = ' '; idx[y] = yy, idx[x] = xx; B(yy, xx) = c; if (kill) idx[y] = -1; } int run(void) { static int step = 0; int i; for (i = 0; i < cnt; i++) move(i); if (2 == ++step && cnt < BALLS) { step = 0; x[cnt] = w/2; y[cnt] = 0; if (V(cnt) != ' ') return 0; V(cnt) = rnd(80) + 43; cnt++; } return 1; } int main(int c, char **v) { if (c < 2 || (n = atoi(v[1])) <= 3) n = 5; if (n >= 20) n = 20; w = n * 2 + 1; init(); do { show_board(), usleep(60000); } while (run()); return 0; }
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) type Ball struct{ x, y int } func newBall(x, y int) *Ball { if box[y][x] != empty { panic("Tried to create a new ball in a non-empty cell. Program terminated.") } b := Ball{x, y} box[y][x] = ball return &b } func (b *Ball) doStep() { if b.y <= 0 { return } cell := box[b.y-1][b.x] switch cell { case empty: box[b.y][b.x] = empty b.y-- box[b.y][b.x] = ball case pin: box[b.y][b.x] = empty b.y-- if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty { b.x += rand.Intn(2)*2 - 1 box[b.y][b.x] = ball return } else if box[b.y][b.x-1] == empty { b.x++ } else { b.x-- } box[b.y][b.x] = ball default: } } type Cell = byte var box [boxH][boxW]Cell func initializeBox() { box[0][0] = corner box[0][boxW-1] = corner for i := 1; i < boxW-1; i++ { box[0][i] = floor } for i := 0; i < boxW; i++ { box[boxH-1][i] = box[0][i] } for r := 1; r < boxH-1; r++ { box[r][0] = wall box[r][boxW-1] = wall } for i := 1; i < boxH-1; i++ { for j := 1; j < boxW-1; j++ { box[i][j] = empty } } for nPins := 1; nPins <= pinsBaseW; nPins++ { for p := 0; p < nPins; p++ { box[boxH-2-nPins][centerH+1-nPins+p*2] = pin } } } func drawBox() { for r := boxH - 1; r >= 0; r-- { for c := 0; c < boxW; c++ { fmt.Printf("%c", box[r][c]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) initializeBox() var balls []*Ball for i := 0; i < nMaxBalls+boxH; i++ { fmt.Println("\nStep", i, ":") if i < nMaxBalls { balls = append(balls, newBall(centerH, boxH-2)) } drawBox() for _, b := range balls { b.doStep() } } }
Write a version of this C function in Go with identical behavior.
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf("%d ", x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); } int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x)); return 0; }
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circleSort(a, low, low+mid, swaps) swaps = circleSort(a, low+mid+1, high, swaps) return swaps } func main() { aa := [][]int{ {6, 7, 8, 9, 2, 5, 3, 4, 1}, {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}, } for _, a := range aa { fmt.Printf("Original: %v\n", a) for circleSort(a, 0, len(a)-1, 0) != 0 { } fmt.Printf("Sorted  : %v\n\n", a) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = fopen(inputFile,"r"); int i,j,k,l; unsigned long prod; int** matrix; cell *coreList,*tempList,*resultList; fscanf(fp,"%d%d",&ROW,&COL); matrix = (int**)malloc(ROW*sizeof(int*)); for(i=0;i<ROW;i++){ matrix[i] = (int*)malloc(COL*sizeof(int)); for(j=0;j<COL;j++){ fscanf(fp,"%d",&matrix[i][j]); if(matrix[i][j]==1) SUM++; } } coreList = (cell*)malloc(SUM*sizeof(cell)); resultList = (cell*)malloc(SUM*sizeof(cell)); k = 0; for(i=0;i<ROW;i++){ for(j=0;j<COL;j++){ if(matrix[i][j]==1){ coreList[k].row = i+1; coreList[k].col = j+1; resultList[k].row = i+1; resultList[k].col = j+1; k++; } } } prod = k; for(i=2;i<=power;i++){ tempList = (cell*)malloc(prod*k*sizeof(cell)); l = 0; for(j=0;j<prod;j++){ for(k=0;k<SUM;k++){ tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row; tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col; l++; } } free(resultList); prod *= k; resultList = (cell*)malloc(prod*sizeof(cell)); for(j=0;j<prod;j++){ resultList[j].row = tempList[j].row; resultList[j].col = tempList[j].col; } free(tempList); } return resultList; } int main(){ char fileName[100]; int power,i,length; cell* resultList; printf("Enter input file name : "); scanf("%s",fileName); printf("Enter power : "); scanf("%d",&power); resultList = kroneckerProduct(fileName,power); initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal"); length = raiseTo(SUM,power); for(i=0;i<length;i++){ putpixel(resultList[i].row,resultList[i].col,15); } getch(); closegraph(); return 0; }
package main import "fmt" type matrix [][]int func (m1 matrix) kroneckerProduct(m2 matrix) matrix { m := len(m1) n := len(m1[0]) p := len(m2) q := len(m2[0]) rtn := m * p ctn := n * q r := make(matrix, rtn) for i := range r { r[i] = make([]int, ctn) } for i := 0; i < m; i++ { for j := 0; j < n; j++ { for k := 0; k < p; k++ { for l := 0; l < q; l++ { r[p*i+k][q*j+l] = m1[i][j] * m2[k][l] } } } } return r } func (m matrix) kroneckerPower(n int) matrix { pow := m for i := 1; i < n; i++ { pow = pow.kroneckerProduct(m) } return pow } func (m matrix) print(text string) { fmt.Println(text, "fractal :\n") for i := range m { for j := range m[0] { if m[i][j] == 1 { fmt.Print("*") } else { fmt.Print(" ") } } fmt.Println() } fmt.Println() } func main() { m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}} m1.kroneckerPower(4).print("Vivsek") m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}} m2.kroneckerPower(4).print("Sierpinski carpet") }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si("FULLNAME", this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, "Sorry, something went wrong :-(\n"); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value("YES", 0); if (populate_configs(&confs)) { return 1; } printf( "Full name: %s\n" "Favorite fruit: %s\n" "Need spelling: %s\n" "Seeds removed: %s\n", confs.fullname, confs.favouritefruit, confs.needspeeling ? "True" : "False", confs.seedsremoved ? "True" : "False" ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); } #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
Port the provided C code into Go while preserving the original functionality.
#include <stdlib.h> #include <string.h> #include <strings.h> int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
Convert the following code from C to Go, ensuring the logic remains intact.
#include <stdlib.h> #include <string.h> #include <strings.h> int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
Write the same algorithm in Go as shown in this C implementation.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } uint32_t cycle(uint32_t n) { uint32_t m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } bool is_circular_prime(uint32_t p) { if (!is_prime(p)) return false; uint32_t p2 = cycle(p); while (p2 != p) { if (p2 < p || !is_prime(p2)) return false; p2 = cycle(p2); } return true; } void test_repunit(uint32_t digits) { char* str = malloc(digits + 1); if (str == 0) { fprintf(stderr, "Out of memory\n"); exit(1); } memset(str, '1', digits); str[digits] = 0; mpz_t bignum; mpz_init_set_str(bignum, str, 10); free(str); if (mpz_probab_prime_p(bignum, 10)) printf("R(%u) is probably prime.\n", digits); else printf("R(%u) is not prime.\n", digits); mpz_clear(bignum); } int main() { uint32_t p = 2; printf("First 19 circular primes:\n"); for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) printf(", "); printf("%u", p); ++count; } } printf("\n"); printf("Next 4 circular primes:\n"); uint32_t repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; mpz_t bignum; mpz_init_set_ui(bignum, repunit); for (int count = 0; count < 4; ) { if (mpz_probab_prime_p(bignum, 15)) { if (count > 0) printf(", "); printf("R(%u)", digits); ++count; } ++digits; mpz_mul_ui(bignum, bignum, 10); mpz_add_ui(bignum, bignum, 1); } mpz_clear(bignum); printf("\n"); test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func repunit(n int) *big.Int { ones := strings.Repeat("1", n) b, _ := new(big.Int).SetString(ones, 10) return b } var circs = []int{} func alreadyFound(n int) bool { for _, i := range circs { if i == n { return true } } return false } func isCircular(n int) bool { nn := n pow := 1 for nn > 0 { pow *= 10 nn /= 10 } nn = n for { nn *= 10 f := nn / pow nn += f * (1 - pow) if alreadyFound(nn) { return false } if nn == n { break } if !isPrime(nn) { return false } } return true } func main() { fmt.Println("The first 19 circular primes are:") digits := [4]int{1, 3, 7, 9} q := []int{1, 2, 3, 5, 7, 9} fq := []int{1, 2, 3, 5, 7, 9} count := 0 for { f := q[0] fd := fq[0] if isPrime(f) && isCircular(f) { circs = append(circs, f) count++ if count == 19 { break } } copy(q, q[1:]) q = q[:len(q)-1] copy(fq, fq[1:]) fq = fq[:len(fq)-1] if f == 2 || f == 5 { continue } for _, d := range digits { if d >= fd { q = append(q, f*10+d) fq = append(fq, fd) } } } fmt.Println(circs) fmt.Println("\nThe next 4 circular primes, in repunit format, are:") count = 0 var rus []string for i := 7; count < 4; i++ { if repunit(i).ProbablyPrime(10) { count++ rus = append(rus, fmt.Sprintf("R(%d)", i)) } } fmt.Println(rus) fmt.Println("\nThe following repunits are probably circular primes:") for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} { fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10)) } }
Change the following C code into Go without altering its purpose.
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r = malloc(l+1); for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++) r[j] = t[i]; r[l] = 0; return r; } gboolean scroll_it(gpointer data) { if ( direction > 0 ) cx = (cx + 1) % slen; else cx = (cx + slen - 1 ) % slen; gchar *scrolled = rotateby(hello, cx, slen); gtk_label_set_text(label, scrolled); free(scrolled); return TRUE; } int main(int argc, char **argv) { GtkWidget *win; GtkButton *button; PangoFontDescription *pd; gtk_init(&argc, &argv); win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(win), "Basic Animation"); g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL); label = (GtkLabel *)gtk_label_new(hello); pd = pango_font_description_new(); pango_font_description_set_family(pd, "monospace"); gtk_widget_modify_font(GTK_WIDGET(label), pd); button = (GtkButton *)gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button)); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL); slen = strlen(hello); g_timeout_add(125, scroll_it, NULL); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
package main import ( "log" "time" "github.com/gdamore/tcell" ) const ( msg = "Hello World! " x0, y0 = 8, 3 shiftsPerSecond = 4 clicksToExit = 5 ) func main() { s, err := tcell.NewScreen() if err != nil { log.Fatal(err) } if err = s.Init(); err != nil { log.Fatal(err) } s.Clear() s.EnableMouse() tick := time.Tick(time.Second / shiftsPerSecond) click := make(chan bool) go func() { for { em, ok := s.PollEvent().(*tcell.EventMouse) if !ok || em.Buttons()&0xFF == tcell.ButtonNone { continue } mx, my := em.Position() if my == y0 && mx >= x0 && mx < x0+len(msg) { click <- true } } }() for inc, shift, clicks := 1, 0, 0; ; { select { case <-tick: shift = (shift + inc) % len(msg) for i, r := range msg { s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0) } s.Show() case <-click: clicks++ if clicks == clicksToExit { s.Fini() return } inc = len(msg) - inc } } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r = malloc(l+1); for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++) r[j] = t[i]; r[l] = 0; return r; } gboolean scroll_it(gpointer data) { if ( direction > 0 ) cx = (cx + 1) % slen; else cx = (cx + slen - 1 ) % slen; gchar *scrolled = rotateby(hello, cx, slen); gtk_label_set_text(label, scrolled); free(scrolled); return TRUE; } int main(int argc, char **argv) { GtkWidget *win; GtkButton *button; PangoFontDescription *pd; gtk_init(&argc, &argv); win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(win), "Basic Animation"); g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL); label = (GtkLabel *)gtk_label_new(hello); pd = pango_font_description_new(); pango_font_description_set_family(pd, "monospace"); gtk_widget_modify_font(GTK_WIDGET(label), pd); button = (GtkButton *)gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button)); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL); slen = strlen(hello); g_timeout_add(125, scroll_it, NULL); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
package main import ( "log" "time" "github.com/gdamore/tcell" ) const ( msg = "Hello World! " x0, y0 = 8, 3 shiftsPerSecond = 4 clicksToExit = 5 ) func main() { s, err := tcell.NewScreen() if err != nil { log.Fatal(err) } if err = s.Init(); err != nil { log.Fatal(err) } s.Clear() s.EnableMouse() tick := time.Tick(time.Second / shiftsPerSecond) click := make(chan bool) go func() { for { em, ok := s.PollEvent().(*tcell.EventMouse) if !ok || em.Buttons()&0xFF == tcell.ButtonNone { continue } mx, my := em.Position() if my == y0 && mx >= x0 && mx < x0+len(msg) { click <- true } } }() for inc, shift, clicks := 1, 0, 0; ; { select { case <-tick: shift = (shift + inc) % len(msg) for i, r := range msg { s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0) } s.Show() case <-click: clicks++ if clicks == clicksToExit { s.Fini() return } inc = len(msg) - inc } } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <limits.h> #include <stdlib.h> #include <time.h> #define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) #define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); static void swap(unsigned *a, unsigned *b) { unsigned tmp = *a; *a = *b; *b = tmp; } static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) { if (!bit || to < from + 1) return; unsigned *ll = from, *rr = to - 1; for (;;) { while (ll < rr && !(*ll & bit)) ll++; while (ll < rr && (*rr & bit)) rr--; if (ll >= rr) break; swap(ll, rr); } if (!(bit & *ll) && ll < to) ll++; bit >>= 1; rad_sort_u(from, ll, bit); rad_sort_u(ll, to, bit); } static void radix_sort(int *a, const size_t len) { size_t i; unsigned *x = (unsigned*) a; for (i = 0; i < len; i++) x[i] ^= INT_MIN; rad_sort_u(x, x + len, INT_MIN); for (i = 0; i < len; i++) x[i] ^= INT_MIN; } int main(void) { srand(time(NULL)); int x[16]; for (size_t i = 0; i < ARR_LEN(x); i++) x[i] = RAND_RNG(-128,127) radix_sort(x, ARR_LEN(x)); for (size_t i = 0; i < ARR_LEN(x); i++) printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); }
package main import ( "bytes" "encoding/binary" "fmt" ) type word int32 const wordLen = 4 const highBit = -1 << 31 var data = []word{170, 45, 75, -90, -802, 24, 2, 66} func main() { buf := bytes.NewBuffer(nil) ds := make([][]byte, len(data)) for i, x := range data { binary.Write(buf, binary.LittleEndian, x^highBit) b := make([]byte, wordLen) buf.Read(b) ds[i] = b } bins := make([][][]byte, 256) for i := 0; i < wordLen; i++ { for _, b := range ds { bins[b[i]] = append(bins[b[i]], b) } j := 0 for k, bs := range bins { copy(ds[j:], bs) j += len(bs) bins[k] = bs[:0] } } fmt.Println("original:", data) var w word for i, b := range ds { buf.Write(b) binary.Read(buf, binary.LittleEndian, &w) data[i] = w^highBit } fmt.Println("sorted: ", data) }
Please provide an equivalent version of this C code in Go.
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
package main import "fmt" type ( seq []int sofs []seq ) func newSeq(start, end int) seq { if end < start { end = start } s := make(seq, end-start+1) for i := 0; i < len(s); i++ { s[i] = start + i } return s } func newSofs() sofs { return sofs{seq{}} } func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs { var s2 sofs for _, t := range expr(s, in) { if pred(t) { s2 = append(s2, t) } } return s2 } func (s sofs) build(t seq) sofs { var u sofs for _, ss := range s { for _, tt := range t { uu := make(seq, len(ss)) copy(uu, ss) uu = append(uu, tt) u = append(u, uu) } } return u } func main() { pt := newSofs() in := newSeq(1, 20) expr := func(s sofs, t seq) sofs { return s.build(t).build(t).build(t) } pred := func(t seq) bool { if len(t) != 3 { return false } return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2] } pt = pt.listComp(in, expr, pred) fmt.Println(pt) }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> void selection_sort (int *a, int n) { int i, j, m, t; for (i = 0; i < n; i++) { for (j = i, m = i; j < n; j++) { if (a[j] < a[m]) { m = j; } } t = a[i]; a[i] = a[m]; a[m] = t; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); selection_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) selectionSort(a) fmt.Println("after: ", a) } func selectionSort(a []int) { last := len(a) - 1 for i := 0; i < last; i++ { aMin := a[i] iMin := i for j := i + 1; j < len(a); j++ { if a[j] < aMin { aMin = a[j] iMin = j } } a[i], a[iMin] = aMin, a[i] } }
Keep all operations the same but rewrite the snippet in Go.
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
Produce a functionally identical Go code for the snippet given in C.
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
Convert this C snippet to Go and keep its semantics consistent.
#ifndef CALLBACK_H #define CALLBACK_H void map(int* array, int len, void(*callback)(int,int)); #endif
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
Write a version of this C function in Go with identical behavior.
#ifndef SILLY_H #define SILLY_H extern void JumpOverTheDog( int numberOfTimes); extern int PlayFetchWithDog( float weightOfStick); #endif
package main import ( "log" "math/rand" "sync" "time" ) var ( instance string once sync.Once ) func claim(color string, w *sync.WaitGroup) { time.Sleep(time.Duration(rand.Intn(1e8))) log.Println("trying to claim", color) once.Do(func() { instance = color }) log.Printf("tried %s. instance: %s", color, instance) w.Done() } func main() { rand.Seed(time.Now().Unix()) var w sync.WaitGroup w.Add(2) go claim("red", &w) go claim("blue", &w) w.Wait() log.Println("after trying both, instance =", instance) }
Generate an equivalent Go version of this C code.
#include <fenv.h> #include <stdio.h> void safe_add(volatile double interval[2], volatile double a, volatile double b) { #pragma STDC FENV_ACCESS ON unsigned int orig; orig = fegetround(); fesetround(FE_DOWNWARD); interval[0] = a + b; fesetround(FE_UPWARD); interval[1] = a + b; fesetround(orig); } int main() { const double nums[][2] = { {1, 2}, {0.1, 0.2}, {1e100, 1e-100}, {1e308, 1e308}, }; double ival[2]; int i; for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) { safe_add(ival, nums[i][0], nums[i][1]); printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]); printf(" [%.17g, %.17g]\n", ival[0], ival[1]); printf(" size %.17g\n\n", ival[1] - ival[0]); } return 0; }
package main import ( "fmt" "math" ) type interval struct { lower, upper float64 } func stepAway(x float64) interval { return interval { math.Nextafter(x, math.Inf(-1)), math.Nextafter(x, math.Inf(1))} } func safeAdd(a, b float64) interval { return stepAway(a + b) } func main() { a, b := 1.2, .03 fmt.Println(a, b, safeAdd(a, b)) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> static const char *dog = "Benjamin"; static const char *Dog = "Samba"; static const char *DOG = "Bernie"; int main() { printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG); return 0; }
package dogs import "fmt" var dog = "Salt" var Dog = "Pepper" var DOG = "Mustard" func PackageSees() map[*string]int { fmt.Println("Package sees:", dog, Dog, DOG) return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1} }
Generate a Go translation of this C snippet without changing its computational steps.
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
for i := 10; i >= 0; i-- { fmt.Println(i) }
Generate an equivalent Go version of this C code.
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
for i := 10; i >= 0; i-- { fmt.Println(i) }
Convert this C snippet to Go and keep its semantics consistent.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.", freopen("sample.txt","wb",stdout)); }
import "io/ioutil" func main() { ioutil.WriteFile("path/to/your.file", []byte("data"), 0644) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) putchar('*'); puts(""); }
package main import "fmt" func main() { for i := 1; i <= 5; i++ { for j := 1; j <= i; j++ { fmt.Printf("*") } fmt.Printf("\n") } }
Keep all operations the same but rewrite the snippet in Go.
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Write a version of this C function in Go with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Write the same algorithm in Go as shown in this C implementation.
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; int p; for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPrime(sum) { c++ fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum)) } } fmt.Println() fmt.Println(c, "such prime sums found") }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; int p; for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPrime(sum) { c++ fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum)) } } fmt.Println() fmt.Println(c, "such prime sums found") }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define COUNTOF(a) (sizeof(a)/sizeof(a[0])) 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; } int icompare(const void* p1, const void* p2) { const int* ip1 = p1; const int* ip2 = p2; return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0); } size_t unique(int* array, size_t len) { size_t out_index = 0; int prev; for (size_t i = 0; i < len; ++i) { if (i == 0 || prev != array[i]) array[out_index++] = array[i]; prev = array[i]; } return out_index; } int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) { size_t len = 0; for (size_t i = 0; i < count; ++i) len += lengths[i]; int* array = xmalloc(len * sizeof(int)); for (size_t i = 0, offset = 0; i < count; ++i) { memcpy(array + offset, arrays[i], lengths[i] * sizeof(int)); offset += lengths[i]; } qsort(array, len, sizeof(int), icompare); *size = unique(array, len); return array; } void print(const int* array, size_t len) { printf("["); for (size_t i = 0; i < len; ++i) { if (i > 0) printf(", "); printf("%d", array[i]); } printf("]\n"); } int main() { const int a[] = {5, 1, 3, 8, 9, 4, 8, 7}; const int b[] = {3, 5, 9, 8, 4}; const int c[] = {1, 3, 7, 9}; size_t len = 0; const int* arrays[] = {a, b, c}; size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)}; int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len); print(sorted, len); free(sorted); return 0; }
package main import ( "fmt" "sort" ) func distinctSortedUnion(ll [][]int) []int { var res []int for _, l := range ll { res = append(res, l...) } set := make(map[int]bool) for _, e := range res { set[e] = true } res = res[:0] for key := range set { res = append(res, key) } sort.Ints(res) return res } func main() { ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}} fmt.Println("Distinct sorted union of", ll, "is:") fmt.Println(distinctSortedUnion(ll)) }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define COUNTOF(a) (sizeof(a)/sizeof(a[0])) 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; } int icompare(const void* p1, const void* p2) { const int* ip1 = p1; const int* ip2 = p2; return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0); } size_t unique(int* array, size_t len) { size_t out_index = 0; int prev; for (size_t i = 0; i < len; ++i) { if (i == 0 || prev != array[i]) array[out_index++] = array[i]; prev = array[i]; } return out_index; } int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) { size_t len = 0; for (size_t i = 0; i < count; ++i) len += lengths[i]; int* array = xmalloc(len * sizeof(int)); for (size_t i = 0, offset = 0; i < count; ++i) { memcpy(array + offset, arrays[i], lengths[i] * sizeof(int)); offset += lengths[i]; } qsort(array, len, sizeof(int), icompare); *size = unique(array, len); return array; } void print(const int* array, size_t len) { printf("["); for (size_t i = 0; i < len; ++i) { if (i > 0) printf(", "); printf("%d", array[i]); } printf("]\n"); } int main() { const int a[] = {5, 1, 3, 8, 9, 4, 8, 7}; const int b[] = {3, 5, 9, 8, 4}; const int c[] = {1, 3, 7, 9}; size_t len = 0; const int* arrays[] = {a, b, c}; size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)}; int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len); print(sorted, len); free(sorted); return 0; }
package main import ( "fmt" "sort" ) func distinctSortedUnion(ll [][]int) []int { var res []int for _, l := range ll { res = append(res, l...) } set := make(map[int]bool) for _, e := range res { set[e] = true } res = res[:0] for key := range set { res = append(res, key) } sort.Ints(res) return res } func main() { ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}} fmt.Println("Distinct sorted union of", ll, "is:") fmt.Println(distinctSortedUnion(ll)) }
Keep all operations the same but rewrite the snippet in Go.
#include <assert.h> #include <stdio.h> int main(int c, char **v) { unsigned int n = 1 << (c - 1), i = n, j, k; assert(n); while (i--) { if (!(i & (i + (i & -(int)i)))) continue; for (j = n, k = 1; j >>= 1; k++) if (i & j) printf("%s ", v[k]); putchar('\n'); } return 0; }
package main import "fmt" const ( m = iota c cm cmc ) func ncs(s []int) [][]int { if len(s) < 3 { return nil } return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...) } var skip = []int{m, cm, cm, cmc} var incl = []int{c, c, cmc, cmc} func n2(ss, tail []int, seq int) [][]int { if len(tail) == 0 { if seq != cmc { return nil } return [][]int{ss} } return append(n2(append([]int{}, ss...), tail[1:], skip[seq]), n2(append(ss, tail[0]), tail[1:], incl[seq])...) } func main() { ss := ncs([]int{1, 2, 3, 4}) fmt.Println(len(ss), "non-continuous subsequences:") for _, s := range ss { fmt.Println(" ", s) } }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> int main(void) { puts( "%!PS-Adobe-3.0 EPSF\n" "%%BoundingBox: -10 -10 400 565\n" "/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n" "/b{a 90 rotate}def"); char i; for (i = 'c'; i <= 'z'; i++) printf("/%c{%c %c}def\n", i, i-1, i-2); puts("0 setlinewidth z showpage\n%%EOF"); return 0; }
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >= 1; j-- { tmp := f2.String() f2.WriteString(f1.String()) f1.Reset() f1.WriteString(tmp) } return f2.String() } func draw(dc *gg.Context, x, y, dx, dy float64, wf string) { for i, c := range wf { dc.DrawLine(x, y, x+dx, y+dy) x += dx y += dy if c == '0' { tx := dx dx = dy if i%2 == 0 { dx = -dy } dy = -tx if i%2 == 0 { dy = tx } } } } func main() { dc := gg.NewContext(450, 620) dc.SetRGB(0, 0, 0) dc.Clear() wf := wordFractal(23) draw(dc, 20, 20, 1, 0, wf) dc.SetRGB(0, 1, 0) dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("fib_wordfractal.png") }
Write the same algorithm in Go as shown in this C implementation.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> bool isPrime(int64_t n) { int64_t i; if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; if (n % 7 == 0) return n == 7; if (n % 11 == 0) return n == 11; if (n % 13 == 0) return n == 13; if (n % 17 == 0) return n == 17; if (n % 19 == 0) return n == 19; for (i = 23; i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } int countTwinPrimes(int limit) { int count = 0; int64_t p3 = true, p2 = true, p1 = false; int64_t i; for (i = 5; i <= limit; i++) { p3 = p2; p2 = p1; p1 = isPrime(i); if (p3 && p1) { count++; } } return count; } void test(int limit) { int count = countTwinPrimes(limit); printf("Number of twin prime pairs less than %d is %d\n", limit, count); } int main() { test(10); test(100); test(1000); test(10000); test(100000); test(1000000); test(10000000); test(100000000); return 0; }
package main import "fmt" func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { c := sieve(1e10 - 1) limit := 10 start := 3 twins := 0 for i := 1; i < 11; i++ { for i := start; i < limit; i += 2 { if !c[i] && !c[i-2] { twins++ } } fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins)) start = limit + 1 limit *= 10 } }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> #include <math.h> int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i; for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a), s = sin(a); if (c) printf("%.2g", c); printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s); printf(i == n - 1 ?"\n":", "); } return 0; }
package main import ( "fmt" "math" "math/cmplx" ) func main() { for n := 2; n <= 5; n++ { fmt.Printf("%d roots of 1:\n", n) for _, r := range roots(n) { fmt.Printf(" %18.15f\n", r) } } } func roots(n int) []complex128 { r := make([]complex128, n) for i := 0; i < n; i++ { r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n)) } return r }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #include <string.h> void longmulti(const char *a, const char *b, char *c) { int i = 0, j = 0, k = 0, n, carry; int la, lb; if (!strcmp(a, "0") || !strcmp(b, "0")) { c[0] = '0', c[1] = '\0'; return; } if (a[0] == '-') { i = 1; k = !k; } if (b[0] == '-') { j = 1; k = !k; } if (i || j) { if (k) c[0] = '-'; longmulti(a + i, b + j, c + k); return; } la = strlen(a); lb = strlen(b); memset(c, '0', la + lb); c[la + lb] = '\0'; # define I(a) (a - '0') for (i = la - 1; i >= 0; i--) { for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) { n = I(a[i]) * I(b[j]) + I(c[k]) + carry; carry = n / 10; c[k] = (n % 10) + '0'; } c[k] += carry; } # undef I if (c[0] == '0') memmove(c, c + 1, la + lb); return; } int main() { char c[1024]; longmulti("-18446744073709551616", "-18446744073709551616", c); printf("%s\n", c); return 0; }
package main import "fmt" func d(b byte) byte { if b < '0' || b > '9' { panic("digit 0-9 expected") } return b - '0' } func add(x, y string) string { if len(y) > len(x) { x, y = y, x } b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { if i <= len(y) { c += d(y[len(y)-i]) } s := d(x[len(x)-i]) + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mulDigit(x string, y byte) string { if y == '0' { return "0" } y = d(y) b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { s := d(x[len(x)-i])*y + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mul(x, y string) string { result := mulDigit(x, y[len(y)-1]) for i, zeros := 2, ""; i <= len(y); i++ { zeros += "0" result = add(result, mulDigit(x, y[len(y)-i])+zeros) } return result } const n = "18446744073709551616" func main() { fmt.Println(mul(n, n)) }
Write the same code in Go as shown below in C.
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { return makePair(1, 0); } else { int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } } return makePair(a, b); } } void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); } int main() { test(61); test(109); test(181); test(277); return 0; }
package main import ( "fmt" "math/big" ) var big1 = new(big.Int).SetUint64(1) func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1) e1 := new(big.Int).SetUint64(1) e2 := new(big.Int) f1 := new(big.Int) f2 := new(big.Int).SetUint64(1) t := new(big.Int) u := new(big.Int) a := new(big.Int) b := new(big.Int) for { t.Mul(r, z) y.Sub(t, y) t.Mul(y, y) t.Sub(n, t) z.Quo(t, z) t.Add(x, y) r.Quo(t, z) u.Set(e1) e1.Set(e2) t.Mul(r, e2) e2.Add(t, u) u.Set(f1) f1.Set(f2) t.Mul(r, f2) f2.Add(t, u) t.Mul(x, f2) a.Add(e2, t) b.Set(f2) t.Mul(a, a) u.Mul(n, b) u.Mul(u, b) t.Sub(t, u) if t.Cmp(big1) == 0 { return a, b } } } func main() { ns := []uint64{61, 109, 181, 277} for _, n := range ns { x, y := solvePell(n) fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y) } }
Ensure the translated Go code behaves exactly like the original C snippet.
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { return makePair(1, 0); } else { int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } } return makePair(a, b); } } void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); } int main() { test(61); test(109); test(181); test(277); return 0; }
package main import ( "fmt" "math/big" ) var big1 = new(big.Int).SetUint64(1) func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1) e1 := new(big.Int).SetUint64(1) e2 := new(big.Int) f1 := new(big.Int) f2 := new(big.Int).SetUint64(1) t := new(big.Int) u := new(big.Int) a := new(big.Int) b := new(big.Int) for { t.Mul(r, z) y.Sub(t, y) t.Mul(y, y) t.Sub(n, t) z.Quo(t, z) t.Add(x, y) r.Quo(t, z) u.Set(e1) e1.Set(e2) t.Mul(r, e2) e2.Add(t, u) u.Set(f1) f1.Set(f2) t.Mul(r, f2) f2.Add(t, u) t.Mul(x, f2) a.Add(e2, t) b.Set(f2) t.Mul(a, a) u.Mul(n, b) u.Mul(u, b) t.Sub(t, u) if t.Cmp(big1) == 0 { return a, b } } } func main() { ns := []uint64{61, 109, 181, 277} for _, n := range ns { x, y := solvePell(n) fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y) } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdbool.h> #include <curses.h> #include <string.h> #define MAX_NUM_TRIES 72 #define LINE_BEGIN 7 #define LAST_LINE 18 int yp=LINE_BEGIN, xp=0; char number[5]; char guess[5]; #define MAX_STR 256 void mvaddstrf(int y, int x, const char *fmt, ...) { va_list args; char buf[MAX_STR]; va_start(args, fmt); vsprintf(buf, fmt, args); move(y, x); clrtoeol(); addstr(buf); va_end(args); } void ask_for_a_number() { int i=0; char symbols[] = "123456789"; move(5,0); clrtoeol(); addstr("Enter four digits: "); while(i<4) { int c = getch(); if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) { addch(c); symbols[c-'1'] = 0; guess[i++] = c; } } } void choose_the_number() { int i=0, j; char symbols[] = "123456789"; while(i<4) { j = rand() % 9; if ( symbols[j] != 0 ) { number[i++] = symbols[j]; symbols[j] = 0; } } }
package main import ( "bufio" "bytes" "fmt" "math/rand" "os" "strings" "time" ) func main() { fmt.Println(`Cows and Bulls Guess four digit number of unique digits in the range 1 to 9. A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bull.`) pat := make([]byte, 4) rand.Seed(time.Now().Unix()) r := rand.Perm(9) for i := range pat { pat[i] = '1' + byte(r[i]) } valid := []byte("123456789") guess: for in := bufio.NewReader(os.Stdin); ; { fmt.Print("Guess: ") guess, err := in.ReadString('\n') if err != nil { fmt.Println("\nSo, bye.") return } guess = strings.TrimSpace(guess) if len(guess) != 4 { fmt.Println("Please guess a four digit number.") continue } var cows, bulls int for ig, cg := range guess { if strings.IndexRune(guess[:ig], cg) >= 0 { fmt.Printf("Repeated digit: %c\n", cg) continue guess } switch bytes.IndexByte(pat, byte(cg)) { case -1: if bytes.IndexByte(valid, byte(cg)) == -1 { fmt.Printf("Invalid digit: %c\n", cg) continue guess } default: cows++ case ig: bulls++ } } fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) if bulls == 4 { fmt.Println("You got it.") return } } }
Change the following C code into Go without altering its purpose.
#include <stdio.h> void bubble_sort (int *a, int n) { int i, t, j = n, s = 1; while (s) { s = 0; for (i = 1; i < j; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } j--; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); bubble_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
package main import "fmt" func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) bubblesort(list) fmt.Println("sorted! ", list) } func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
Ensure the translated Go code behaves exactly like the original C snippet.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
Convert this C snippet to Go and keep its semantics consistent.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> int main(int argc, char **argv) { FILE *in, *out; int c; in = fopen("input.txt", "r"); if (!in) { fprintf(stderr, "Error opening input.txt for reading.\n"); return 1; } out = fopen("output.txt", "w"); if (!out) { fprintf(stderr, "Error opening output.txt for writing.\n"); fclose(in); return 1; } while ((c = fgetc(in)) != EOF) { fputc(c, out); } fclose(out); fclose(in); return 0; }
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
Convert the following code from C to Go, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a, b; if (argc < 3) exit(1); b = atoi(argv[--argc]); if (b == 0) exit(2); a = atoi(argv[--argc]); printf("a+b = %d\n", a+b); printf("a-b = %d\n", a-b); printf("a*b = %d\n", a*b); printf("a/b = %d\n", a/b); printf("a%%b = %d\n", a%b); return 0; }
package main import "fmt" func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d + %d = %d\n", a, b, a+b) fmt.Printf("%d - %d = %d\n", a, b, a-b) fmt.Printf("%d * %d = %d\n", a, b, a*b) fmt.Printf("%d / %d = %d\n", a, b, a/b) fmt.Printf("%d %% %d = %d\n", a, b, a%b) }
Ensure the translated Go code behaves exactly like the original C snippet.
#include <stdio.h> void transpose(void *dest, void *src, int src_h, int src_w) { int i, j; double (*d)[src_h] = dest, (*s)[src_w] = src; for (i = 0; i < src_h; i++) for (j = 0; j < src_w; j++) d[j][i] = s[i][j]; } int main() { int i, j; double a[3][5] = {{ 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 1, 0, 0, 0, 42}}; double b[5][3]; transpose(b, a, 3, 5); for (i = 0; i < 5; i++) for (j = 0; j < 3; j++) printf("%g%c", b[i][j], j == 2 ? '\n' : ' '); return 0; }
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { m := mat.NewDense(2, 3, []float64{ 1, 2, 3, 4, 5, 6, }) fmt.Println(mat.Formatted(m)) fmt.Println() fmt.Println(mat.Formatted(m.T())) }
Produce a language-to-language conversion: from C to Go, same semantics.
#include <stdio.h> #include <stdlib.h> typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG; int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; } int eval(ARG* a) { return a->fn(a); } #define MAKE_ARG(...) (&(ARG){__VA_ARGS__}) #define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__) int A(ARG*); int B(ARG* a) { int k = *a->k -= 1; return A(FUN(a, a->x1, a->x2, a->x3, a->x4)); } int A(ARG* a) { return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a); } int main(int argc, char **argv) { int k = argc == 2 ? strtol(argv[1], 0, 0) : 10; printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1), MAKE_ARG(f1), MAKE_ARG(f0)))); return 0; }
package main import "fmt" func a(k int, x1, x2, x3, x4, x5 func() int) int { var b func() int b = func() int { k-- return a(k, b, x1, x2, x3, x4) } if k <= 0 { return x4() + x5() } return b() } func main() { x := func(i int) func() int { return func() int { return i } } fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0))) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdbool.h> bool a(bool in) { printf("I am a\n"); return in; } bool b(bool in) { printf("I am b\n"); return in; } #define TEST(X,Y,O) \ do { \ x = a(X) O b(Y); \ printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \ } while(false); int main() { bool x; TEST(false, true, &&); TEST(true, false, ||); TEST(true, false, &&); TEST(false, false, ||); return 0; }
package main import "fmt" func a(v bool) bool { fmt.Print("a") return v } func b(v bool) bool { fmt.Print("b") return v } func test(i, j bool) { fmt.Printf("Testing a(%t) && b(%t)\n", i, j) fmt.Print("Trace: ") fmt.Println("\nResult:", a(i) && b(j)) fmt.Printf("Testing a(%t) || b(%t)\n", i, j) fmt.Print("Trace: ") fmt.Println("\nResult:", a(i) || b(j)) fmt.Println("") } func main() { test(false, false) test(false, true) test(true, false) test(true, true) }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
package main import ( "flag" "fmt" "runtime/debug" ) func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) } func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
package main import ( "flag" "fmt" "runtime/debug" ) func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) } func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
Preserve the algorithm and functionality while converting the code from C to Go.
#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))) return 0; return 1; } } void carmichael3(int p1) { if (!is_prime(p1)) return; int h3, d, p2, p3; for (h3 = 1; h3 < p1; ++h3) { for (d = 1; d < h3 + p1; ++d) { if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) { p2 = 1 + ((p1 - 1) * (h3 + p1)/d); if (!is_prime(p2)) continue; p3 = 1 + (p1 * p2 / h3); if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue; printf("%d %d %d\n", p1, p2, p3); } } } } int main(void) { int p1; for (p1 = 2; p1 < 62; ++p1) carmichael3(p1); return 0; }
package main import "fmt" func mod(n, m int) int { return ((n % m) + m) % m } func isPrime(n int) bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } d := 5 for d * d <= n { if n % d == 0 { return false } d += 2 if n % d == 0 { return false } d += 4 } return true } func carmichael(p1 int) { for h3 := 2; h3 < p1; h3++ { for d := 1; d < h3 + p1; d++ { if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 { p2 := 1 + (p1 - 1) * (h3 + p1) / d if !isPrime(p2) { continue } p3 := 1 + p1 * p2 / h3 if !isPrime(p3) { continue } if p2 * p3 % (p1 - 1) != 1 { continue } c := p1 * p2 * p3 fmt.Printf("%2d %4d %5d %d\n", p1, p2, p3, c) } } } } func main() { fmt.Println("The following are Carmichael munbers for p1 <= 61:\n") fmt.Println("p1 p2 p3 product") fmt.Println("== == == =======") for p1 := 2; p1 <= 61; p1++ { if isPrime(p1) { carmichael(p1) } } }
Generate a Go translation of this C snippet without changing its computational steps.
#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; divisor_sum += power; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1, sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { ++count; sum += power; } divisor_count *= count; divisor_sum *= sum; } if (n > 1) { divisor_count *= 2; divisor_sum *= n + 1; } *pcount = divisor_count; *psum = divisor_sum; } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, &divisor_count, &divisor_sum); if (divisor_sum % divisor_count != 0) continue; ++arithmetic_count; if (divisor_count > 2) ++composite_count; if (arithmetic_count <= 100) { printf("%3u ", n); if (arithmetic_count % 10 == 0) printf("\n"); } if (arithmetic_count == 1000 || arithmetic_count == 10000 || arithmetic_count == 100000 || arithmetic_count == 1000000) { printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
package main import ( "fmt" "math" "rcu" "sort" ) func main() { arithmetic := []int{1} primes := []int{} limit := int(1e6) for n := 3; len(arithmetic) < limit; n++ { divs := rcu.Divisors(n) if len(divs) == 2 { primes = append(primes, n) arithmetic = append(arithmetic, n) } else { mean := float64(rcu.SumInts(divs)) / float64(len(divs)) if mean == math.Trunc(mean) { arithmetic = append(arithmetic, n) } } } fmt.Println("The first 100 arithmetic numbers are:") rcu.PrintTable(arithmetic[0:100], 10, 3, false) for _, x := range []int{1e3, 1e4, 1e5, 1e6} { last := arithmetic[x-1] lastc := rcu.Commatize(last) fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc) pcount := sort.SearchInts(primes, last) + 1 if !rcu.IsPrime(last) { pcount-- } comp := x - pcount - 1 compc := rcu.Commatize(comp) fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc) } }
Port the following code from C to Go with equivalent syntax and logic.
#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; divisor_sum += power; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1, sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { ++count; sum += power; } divisor_count *= count; divisor_sum *= sum; } if (n > 1) { divisor_count *= 2; divisor_sum *= n + 1; } *pcount = divisor_count; *psum = divisor_sum; } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, &divisor_count, &divisor_sum); if (divisor_sum % divisor_count != 0) continue; ++arithmetic_count; if (divisor_count > 2) ++composite_count; if (arithmetic_count <= 100) { printf("%3u ", n); if (arithmetic_count % 10 == 0) printf("\n"); } if (arithmetic_count == 1000 || arithmetic_count == 10000 || arithmetic_count == 100000 || arithmetic_count == 1000000) { printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
package main import ( "fmt" "math" "rcu" "sort" ) func main() { arithmetic := []int{1} primes := []int{} limit := int(1e6) for n := 3; len(arithmetic) < limit; n++ { divs := rcu.Divisors(n) if len(divs) == 2 { primes = append(primes, n) arithmetic = append(arithmetic, n) } else { mean := float64(rcu.SumInts(divs)) / float64(len(divs)) if mean == math.Trunc(mean) { arithmetic = append(arithmetic, n) } } } fmt.Println("The first 100 arithmetic numbers are:") rcu.PrintTable(arithmetic[0:100], 10, 3, false) for _, x := range []int{1e3, 1e4, 1e5, 1e6} { last := arithmetic[x-1] lastc := rcu.Commatize(last) fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc) pcount := sort.SearchInts(primes, last) + 1 if !rcu.IsPrime(last) { pcount-- } comp := x - pcount - 1 compc := rcu.Commatize(comp) fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc) } }
Write the same code in Go as shown below in C.
#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; printf("- fps: %g\n", (float) frames / (float) el_time); t_acc = 0; frames = 0; } last_t = t; } void blit_noise(SDL_Surface *surf) { unsigned int i; long dim = surf->w * surf->h; while (1) { SDL_LockSurface(surf); for (i=0; i < dim; ++i) { ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0); } SDL_UnlockSurface(surf); SDL_Flip(surf); ++frames; print_fps(); } } int main(void) { SDL_Surface *surf = NULL; srand((unsigned int)time(NULL)); SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE); blit_noise(surf); }
package main import ( "code.google.com/p/x-go-binding/ui/x11" "fmt" "image" "image/color" "image/draw" "log" "os" "time" ) var randcol = genrandcol() func genrandcol() <-chan color.Color { c := make(chan color.Color) go func() { for { select { case c <- image.Black: case c <- image.White: } } }() return c } func gennoise(screen draw.Image) { for y := 0; y < 240; y++ { for x := 0; x < 320; x++ { screen.Set(x, y, <-randcol) } } } func fps() chan<- bool { up := make(chan bool) go func() { var frames int64 var lasttime time.Time var totaltime time.Duration for { <-up frames++ now := time.Now() totaltime += now.Sub(lasttime) if totaltime > time.Second { fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds()) frames = 0 totaltime = 0 } lasttime = now } }() return up } func main() { win, err := x11.NewWindow() if err != nil { fmt.Println(err) os.Exit(1) } defer win.Close() go func() { upfps := fps() screen := win.Screen() for { gennoise(screen) win.FlushImage() upfps <- true } }() for _ = range win.EventChan() { } }
Change the following C code into Go without altering its purpose.
#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); tcsetattr(STDIN_FILENO, TCSANOW, &new); } int get_key(int no_timeout) { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0; FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv); if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; } int main() { int c; while(1) { set_mode(1); while (get_key(0)); printf("Prompt again [Y/N]? "); fflush(stdout); c = get_key(1); if (c == 'Y' || c == 'y') { printf("\n"); continue; } if (c == 'N' || c == 'n') { printf("\nDone\n"); break; } printf("\nYes or no?\n"); } return 0; }
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() var k gc.Key for { gc.FlushInput() s.MovePrint(20, 0, "Press y/n ") s.Refresh() switch k = s.GetChar(); k { default: continue case 'y', 'Y', 'n', 'N': } break } s.Printf("\nThanks for the %c!\n", k) s.Refresh() s.GetChar() }
Convert the following code from C to Go, ensuring the logic remains intact.
#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); tcsetattr(STDIN_FILENO, TCSANOW, &new); } int get_key(int no_timeout) { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0; FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv); if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; } int main() { int c; while(1) { set_mode(1); while (get_key(0)); printf("Prompt again [Y/N]? "); fflush(stdout); c = get_key(1); if (c == 'Y' || c == 'y') { printf("\n"); continue; } if (c == 'N' || c == 'n') { printf("\nDone\n"); break; } printf("\nYes or no?\n"); } return 0; }
package main import ( "log" gc "code.google.com/p/goncurses" ) func main() { s, err := gc.Init() if err != nil { log.Fatal("init:", err) } defer gc.End() var k gc.Key for { gc.FlushInput() s.MovePrint(20, 0, "Press y/n ") s.Refresh() switch k = s.GetChar(); k { default: continue case 'y', 'Y', 'n', 'N': } break } s.Printf("\nThanks for the %c!\n", k) s.Refresh() s.GetChar() }
Transform the following C implementation into Go, maintaining the same output and logic.
#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; } int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf("%d\n", n); return 0; }
package main import "fmt" func computePerfect(n int64) bool { var sum int64 for i := int64(1); i < n; i++ { if n%i == 0 { sum += i } } return sum == n } func isPerfect(n int64) bool { switch n { case 6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128: return true } return false } func main() { for n := int64(1); ; n++ { if isPerfect(n) != computePerfect(n) { panic("bug") } if n%1e3 == 0 { fmt.Println("tested", n) } } }
Convert this C snippet to Go and keep its semantics consistent.
#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 (b.cols * sizeof (complex)); for (j = 0; j < b.cols; j++) { b.z[i][j] = conj (a.z[j][i]); } } return b; } int isHermitian (matrix a) { int i, j; matrix b = transpose (a); if (b.rows == a.rows && b.cols == a.cols) { for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if (b.z[i][j] != a.z[i][j]) return 0; } } } else return 0; return 1; } matrix multiply (matrix a, matrix b) { matrix c; int i, j; if (a.cols == b.rows) { c.rows = a.rows; c.cols = b.cols; c.z = malloc (c.rows * (sizeof (complex *))); for (i = 0; i < c.rows; i++) { c.z[i] = malloc (c.cols * sizeof (complex)); c.z[i][j] = 0 + 0 * I; for (j = 0; j < b.cols; j++) { c.z[i][j] += a.z[i][j] * b.z[j][i]; } } } return c; } int isNormal (matrix a) { int i, j; matrix a_ah, ah_a; if (a.rows != a.cols) return 0; a_ah = multiply (a, transpose (a)); ah_a = multiply (transpose (a), a); for (i = 0; i < a.rows; i++) { for (j = 0; j < a.cols; j++) { if (a_ah.z[i][j] != ah_a.z[i][j]) return 0; } } return 1; } int isUnitary (matrix a) { matrix b; int i, j; if (isNormal (a) == 1) { b = multiply (a, transpose(a)); for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0)) return 0; } } return 1; } return 0; } int main () { complex z = 3 + 4 * I; matrix a, aT; int i, j; printf ("Enter rows and columns :"); scanf ("%d%d", &a.rows, &a.cols); a.z = malloc (a.rows * sizeof (complex *)); printf ("Randomly Generated Complex Matrix A is : "); for (i = 0; i < a.rows; i++) { printf ("\n"); a.z[i] = malloc (a.cols * sizeof (complex)); for (j = 0; j < a.cols; j++) { a.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j])); } } aT = transpose (a); printf ("\n\nTranspose of Complex Matrix A is : "); for (i = 0; i < aT.rows; i++) { printf ("\n"); aT.z[i] = malloc (aT.cols * sizeof (complex)); for (j = 0; j < aT.cols; j++) { aT.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j])); } } printf ("\n\nComplex Matrix A %s hermitian", isHermitian (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s unitary", isUnitary (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s normal", isNormal (a) == 1 ? "is" : "is not"); return 0; }
package main import ( "fmt" "math" "math/cmplx" ) type matrix struct { ele []complex128 cols int } func (m *matrix) conjTranspose() *matrix { r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} rx := 0 for _, e := range m.ele { r.ele[rx] = cmplx.Conj(e) rx += r.cols if rx >= len(r.ele) { rx -= len(r.ele) - 1 } } return r } func main() { show("h", matrixFromRows([][]complex128{ {3, 2 + 1i}, {2 - 1i, 1}})) show("n", matrixFromRows([][]complex128{ {1, 1, 0}, {0, 1, 1}, {1, 0, 1}})) show("u", matrixFromRows([][]complex128{ {math.Sqrt2 / 2, math.Sqrt2 / 2, 0}, {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0}, {0, 0, 1i}})) } func show(name string, m *matrix) { m.print(name) ct := m.conjTranspose() ct.print(name + "_ct") fmt.Println("Hermitian:", m.equal(ct, 1e-14)) mct := m.mult(ct) ctm := ct.mult(m) fmt.Println("Normal:", mct.equal(ctm, 1e-14)) i := eye(m.cols) fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14)) } func matrixFromRows(rows [][]complex128) *matrix { m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])} for rx, row := range rows { copy(m.ele[rx*m.cols:(rx+1)*m.cols], row) } return m } func eye(n int) *matrix { r := &matrix{make([]complex128, n*n), n} n++ for x := 0; x < len(r.ele); x += n { r.ele[x] = 1 } return r } func (m *matrix) print(heading string) { fmt.Print("\n", heading, "\n") for e := 0; e < len(m.ele); e += m.cols { fmt.Printf("%6.3f ", m.ele[e:e+m.cols]) fmt.Println() } } func (a *matrix) equal(b *matrix, ε float64) bool { for x, aEle := range a.ele { if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε || math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε { return false } } return true } func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) { m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols} for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols { for m2r0 := 0; m2r0 < m2.cols; m2r0++ { for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols { m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] m1x++ } m3x++ } } return m3 }
Preserve the algorithm and functionality while converting the code from C to Go.
#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 (b.cols * sizeof (complex)); for (j = 0; j < b.cols; j++) { b.z[i][j] = conj (a.z[j][i]); } } return b; } int isHermitian (matrix a) { int i, j; matrix b = transpose (a); if (b.rows == a.rows && b.cols == a.cols) { for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if (b.z[i][j] != a.z[i][j]) return 0; } } } else return 0; return 1; } matrix multiply (matrix a, matrix b) { matrix c; int i, j; if (a.cols == b.rows) { c.rows = a.rows; c.cols = b.cols; c.z = malloc (c.rows * (sizeof (complex *))); for (i = 0; i < c.rows; i++) { c.z[i] = malloc (c.cols * sizeof (complex)); c.z[i][j] = 0 + 0 * I; for (j = 0; j < b.cols; j++) { c.z[i][j] += a.z[i][j] * b.z[j][i]; } } } return c; } int isNormal (matrix a) { int i, j; matrix a_ah, ah_a; if (a.rows != a.cols) return 0; a_ah = multiply (a, transpose (a)); ah_a = multiply (transpose (a), a); for (i = 0; i < a.rows; i++) { for (j = 0; j < a.cols; j++) { if (a_ah.z[i][j] != ah_a.z[i][j]) return 0; } } return 1; } int isUnitary (matrix a) { matrix b; int i, j; if (isNormal (a) == 1) { b = multiply (a, transpose(a)); for (i = 0; i < b.rows; i++) { for (j = 0; j < b.cols; j++) { if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0)) return 0; } } return 1; } return 0; } int main () { complex z = 3 + 4 * I; matrix a, aT; int i, j; printf ("Enter rows and columns :"); scanf ("%d%d", &a.rows, &a.cols); a.z = malloc (a.rows * sizeof (complex *)); printf ("Randomly Generated Complex Matrix A is : "); for (i = 0; i < a.rows; i++) { printf ("\n"); a.z[i] = malloc (a.cols * sizeof (complex)); for (j = 0; j < a.cols; j++) { a.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j])); } } aT = transpose (a); printf ("\n\nTranspose of Complex Matrix A is : "); for (i = 0; i < aT.rows; i++) { printf ("\n"); aT.z[i] = malloc (aT.cols * sizeof (complex)); for (j = 0; j < aT.cols; j++) { aT.z[i][j] = rand () % 10 + rand () % 10 * I; printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j])); } } printf ("\n\nComplex Matrix A %s hermitian", isHermitian (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s unitary", isUnitary (a) == 1 ? "is" : "is not"); printf ("\n\nComplex Matrix A %s normal", isNormal (a) == 1 ? "is" : "is not"); return 0; }
package main import ( "fmt" "math" "math/cmplx" ) type matrix struct { ele []complex128 cols int } func (m *matrix) conjTranspose() *matrix { r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols} rx := 0 for _, e := range m.ele { r.ele[rx] = cmplx.Conj(e) rx += r.cols if rx >= len(r.ele) { rx -= len(r.ele) - 1 } } return r } func main() { show("h", matrixFromRows([][]complex128{ {3, 2 + 1i}, {2 - 1i, 1}})) show("n", matrixFromRows([][]complex128{ {1, 1, 0}, {0, 1, 1}, {1, 0, 1}})) show("u", matrixFromRows([][]complex128{ {math.Sqrt2 / 2, math.Sqrt2 / 2, 0}, {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0}, {0, 0, 1i}})) } func show(name string, m *matrix) { m.print(name) ct := m.conjTranspose() ct.print(name + "_ct") fmt.Println("Hermitian:", m.equal(ct, 1e-14)) mct := m.mult(ct) ctm := ct.mult(m) fmt.Println("Normal:", mct.equal(ctm, 1e-14)) i := eye(m.cols) fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14)) } func matrixFromRows(rows [][]complex128) *matrix { m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])} for rx, row := range rows { copy(m.ele[rx*m.cols:(rx+1)*m.cols], row) } return m } func eye(n int) *matrix { r := &matrix{make([]complex128, n*n), n} n++ for x := 0; x < len(r.ele); x += n { r.ele[x] = 1 } return r } func (m *matrix) print(heading string) { fmt.Print("\n", heading, "\n") for e := 0; e < len(m.ele); e += m.cols { fmt.Printf("%6.3f ", m.ele[e:e+m.cols]) fmt.Println() } } func (a *matrix) equal(b *matrix, ε float64) bool { for x, aEle := range a.ele { if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε || math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε { return false } } return true } func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) { m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols} for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols { for m2r0 := 0; m2r0 < m2.cols; m2r0++ { for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols { m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] m1x++ } m3x++ } } return m3 }
Translate this program into Go but keep the logic exactly as in C.
#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_t a; mpz_init(a); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(a, 1); if (n % 2) mpz_neg(a, a); mpz_add(r, r, a); } int main() { int i, count; mpz_t jac[30], j; printf("First 30 Jacobsthal numbers:\n"); for (i = 0; i < 30; ++i) { mpz_init(jac[i]); jacobsthal(jac[i], i); gmp_printf("%9Zd ", jac[i]); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 30 Jacobsthal-Lucas numbers:\n"); mpz_init(j); for (i = 0; i < 30; ++i) { jacobsthal_lucas(j, i); gmp_printf("%9Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal oblong numbers:\n"); for (i = 0; i < 20; ++i) { mpz_mul(j, jac[i], jac[i+1]); gmp_printf("%11Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal primes:\n"); for (i = 0, count = 0; count < 20; ++i) { jacobsthal(j, i); if (mpz_probab_prime_p(j, 15) > 0) { gmp_printf("%Zd\n", j); ++count; } } return 0; }
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
Generate a Go translation of this C snippet without changing its computational steps.
#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_t a; mpz_init(a); mpz_set_ui(r, 1); mpz_mul_2exp(r, r, n); mpz_set_ui(a, 1); if (n % 2) mpz_neg(a, a); mpz_add(r, r, a); } int main() { int i, count; mpz_t jac[30], j; printf("First 30 Jacobsthal numbers:\n"); for (i = 0; i < 30; ++i) { mpz_init(jac[i]); jacobsthal(jac[i], i); gmp_printf("%9Zd ", jac[i]); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 30 Jacobsthal-Lucas numbers:\n"); mpz_init(j); for (i = 0; i < 30; ++i) { jacobsthal_lucas(j, i); gmp_printf("%9Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal oblong numbers:\n"); for (i = 0; i < 20; ++i) { mpz_mul(j, jac[i], jac[i+1]); gmp_printf("%11Zd ", j); if (!((i+1)%5)) printf("\n"); } printf("\nFirst 20 Jacobsthal primes:\n"); for (i = 0, count = 0; count < 20; ++i) { jacobsthal(j, i); if (mpz_probab_prime_p(j, 15) > 0) { gmp_printf("%Zd\n", j); ++count; } } return 0; }
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
Keep all operations the same but rewrite the snippet in Go.
#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++) BEAD(i, j) = 1; for (j = 0; j < max; j++) { for (sum = i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } for (i = len - sum; i < len; i++) BEAD(i, j) = 1; } for (i = 0; i < len; i++) { for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; } free(beads); } int main() { int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(x)/sizeof(x[0]); bead_sort(x, len); for (i = 0; i < len; i++) printf("%d\n", x[i]); return 0; }
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, aMax) for pole, space := 0, all; pole < aMax; pole++ { abacus[pole] = space[:len(a)] space = space[len(a):] } var wg sync.WaitGroup wg.Add(len(a)) for row, n := range a { go func(row, n int) { for pole := 0; pole < n; pole++ { abacus[pole][row] = bead } wg.Done() }(row, n) } wg.Wait() wg.Add(aMax) for _, pole := range abacus { go func(pole []byte) { top := 0 for row, space := range pole { if space == bead { pole[row] = 0 pole[top] = bead top++ } } wg.Done() }(pole) } wg.Wait() for row := range a { x := 0 for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ { x++ } a[len(a)-1-row] = x } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#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++) BEAD(i, j) = 1; for (j = 0; j < max; j++) { for (sum = i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } for (i = len - sum; i < len; i++) BEAD(i, j) = 1; } for (i = 0; i < len; i++) { for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; } free(beads); } int main() { int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(x)/sizeof(x[0]); bead_sort(x, len); for (i = 0; i < len; i++) printf("%d\n", x[i]); return 0; }
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, aMax) for pole, space := 0, all; pole < aMax; pole++ { abacus[pole] = space[:len(a)] space = space[len(a):] } var wg sync.WaitGroup wg.Add(len(a)) for row, n := range a { go func(row, n int) { for pole := 0; pole < n; pole++ { abacus[pole][row] = bead } wg.Done() }(row, n) } wg.Wait() wg.Add(aMax) for _, pole := range abacus { go func(pole []byte) { top := 0 for row, space := range pole { if space == bead { pole[row] = 0 pole[top] = bead top++ } } wg.Done() }(pole) } wg.Wait() for row := range a { x := 0 for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ { x++ } a[len(a)-1-row] = x } }
Produce a language-to-language conversion: from C to Go, same semantics.
#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) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } } void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); } int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999); return 0; }
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
Port the provided C code into Go while preserving the original functionality.
#include <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) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } } void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); } int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999); return 0; }
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
Change the programming language of this snippet from C to Go without modifying what it does.
#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...%s\n", s, s + len - 20); return 0; }
package main import ( "fmt" "math/big" ) func main() { x := big.NewInt(2) x = x.Exp(big.NewInt(3), x, nil) x = x.Exp(big.NewInt(4), x, nil) x = x.Exp(big.NewInt(5), x, nil) str := x.String() fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n", len(str), str[:20], str[len(str)-20:], ) }
Translate this program into Go but keep the logic exactly as in C.
#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(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } } int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4); return 0; }
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Convert the following code from C to Go, ensuring the logic remains intact.
#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(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } } int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4); return 0; }
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } func drawSphere(r int, k, amb float64, dir *vector) *image.Gray { w, h := r*4, r*3 img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2)) vec := new(vector) for x := -r; x < r; x++ { for y := -r; y < r; y++ { if z := r*r - x*x - y*y; z >= 0 { vec[0] = float64(x) vec[1] = float64(y) vec[2] = math.Sqrt(float64(z)) normalize(vec) s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } } return img } func main() { dir := &vector{-30, -30, 50} normalize(dir) img := drawSphere(200, 1.5, .2, dir) f, err := os.Create("sphere.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#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), 1); } #define find_word(r, w) trie_trav(r, w, 1) trie trie_trav(trie root, const char * str, int no_create) { int c; while (root) { if ((c = str[0]) == '\0') { if (!root->eow && no_create) return 0; break; } if (! (c = chr_idx[c]) ) { str++; continue; } if (!root->next[c]) { if (no_create) return 0; root->next[c] = trie_new(); } root = root->next[c]; str++; } return root; } int trie_all(trie root, char path[], int depth, int (*callback)(char *)) { int i; if (root->eow && !callback(path)) return 0; for (i = 1; i < sizeof(chr_legal); i++) { if (!root->next[i]) continue; path[depth] = idx_chr[i]; path[depth + 1] = '\0'; if (!trie_all(root->next[i], path, depth + 1, callback)) return 0; } return 1; } void add_index(trie root, const char *word, const char *fname) { trie x = trie_trav(root, word, 0); x->eow = 1; if (!x->next[FNAME]) x->next[FNAME] = trie_new(); x = trie_trav(x->next[FNAME], fname, 0); x->eow = 1; } int print_path(char *path) { printf(" %s", path); return 1; } const char *files[] = { "f1.txt", "source/f2.txt", "other_file" }; const char *text[][5] ={{ "it", "is", "what", "it", "is" }, { "what", "is", "it", 0 }, { "it", "is", "a", "banana", 0 }}; trie init_tables() { int i, j; trie root = trie_new(); for (i = 0; i < sizeof(chr_legal); i++) { chr_idx[(int)chr_legal[i]] = i + 1; idx_chr[i + 1] = chr_legal[i]; } #define USE_ADVANCED_FILE_HANDLING 0 #if USE_ADVANCED_FILE_HANDLING void read_file(const char * fname) { char cmd[1024]; char word[1024]; sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname); FILE *in = popen(cmd, "r"); while (!feof(in)) { fscanf(in, "%1000s", word); add_index(root, word, fname); } pclose(in); }; read_file("f1.txt"); read_file("source/f2.txt"); read_file("other_file"); #else for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) { if (!text[i][j]) break; add_index(root, text[i][j], files[i]); } } #endif return root; } void search_index(trie root, const char *word) { char path[1024]; printf("Search for \"%s\": ", word); trie found = find_word(root, word); if (!found) printf("not found\n"); else { trie_all(found->next[FNAME], path, 0, print_path); printf("\n"); } } int main() { trie root = init_tables(); search_index(root, "what"); search_index(root, "is"); search_index(root, "banana"); search_index(root, "boo"); return 0; }
package main import ( "bufio" "bytes" "errors" "fmt" "io" "os" ) var index map[string][]int var indexed []doc type doc struct { file string title string } func main() { index = make(map[string][]int) if err := indexDir("docs"); err != nil { fmt.Println(err) return } ui() } func indexDir(dir string) error { df, err := os.Open(dir) if err != nil { return err } fis, err := df.Readdir(-1) if err != nil { return err } if len(fis) == 0 { return errors.New(fmt.Sprintf("no files in %s", dir)) } indexed := 0 for _, fi := range fis { if !fi.IsDir() { if indexFile(dir + "/" + fi.Name()) { indexed++ } } } return nil } func indexFile(fn string) bool { f, err := os.Open(fn) if err != nil { fmt.Println(err) return false } x := len(indexed) indexed = append(indexed, doc{fn, fn}) pdoc := &indexed[x] r := bufio.NewReader(f) lines := 0 for { b, isPrefix, err := r.ReadLine() switch { case err == io.EOF: return true case err != nil: fmt.Println(err) return true case isPrefix: fmt.Printf("%s: unexpected long line\n", fn) return true case lines < 20 && bytes.HasPrefix(b, []byte("Title:")): pdoc.title = string(b[7:]) } wordLoop: for _, bword := range bytes.Fields(b) { bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@") if len(bword) > 0 { word := string(bword) dl := index[word] for _, d := range dl { if d == x { continue wordLoop } } index[word] = append(dl, x) } } } return true } func ui() { fmt.Println(len(index), "words indexed in", len(indexed), "files") fmt.Println("enter single words to search for") fmt.Println("enter a blank line when done") var word string for { fmt.Print("search word: ") wc, _ := fmt.Scanln(&word) if wc == 0 { return } switch dl := index[word]; len(dl) { case 0: fmt.Println("no match") case 1: fmt.Println("one match:") fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title) default: fmt.Println(len(dl), "matches:") for _, d := range dl { fmt.Println(" ", indexed[d].file, indexed[d].title) } } } }
Ensure the translated Go code behaves exactly like the original C snippet.
#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), 1); } #define find_word(r, w) trie_trav(r, w, 1) trie trie_trav(trie root, const char * str, int no_create) { int c; while (root) { if ((c = str[0]) == '\0') { if (!root->eow && no_create) return 0; break; } if (! (c = chr_idx[c]) ) { str++; continue; } if (!root->next[c]) { if (no_create) return 0; root->next[c] = trie_new(); } root = root->next[c]; str++; } return root; } int trie_all(trie root, char path[], int depth, int (*callback)(char *)) { int i; if (root->eow && !callback(path)) return 0; for (i = 1; i < sizeof(chr_legal); i++) { if (!root->next[i]) continue; path[depth] = idx_chr[i]; path[depth + 1] = '\0'; if (!trie_all(root->next[i], path, depth + 1, callback)) return 0; } return 1; } void add_index(trie root, const char *word, const char *fname) { trie x = trie_trav(root, word, 0); x->eow = 1; if (!x->next[FNAME]) x->next[FNAME] = trie_new(); x = trie_trav(x->next[FNAME], fname, 0); x->eow = 1; } int print_path(char *path) { printf(" %s", path); return 1; } const char *files[] = { "f1.txt", "source/f2.txt", "other_file" }; const char *text[][5] ={{ "it", "is", "what", "it", "is" }, { "what", "is", "it", 0 }, { "it", "is", "a", "banana", 0 }}; trie init_tables() { int i, j; trie root = trie_new(); for (i = 0; i < sizeof(chr_legal); i++) { chr_idx[(int)chr_legal[i]] = i + 1; idx_chr[i + 1] = chr_legal[i]; } #define USE_ADVANCED_FILE_HANDLING 0 #if USE_ADVANCED_FILE_HANDLING void read_file(const char * fname) { char cmd[1024]; char word[1024]; sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname); FILE *in = popen(cmd, "r"); while (!feof(in)) { fscanf(in, "%1000s", word); add_index(root, word, fname); } pclose(in); }; read_file("f1.txt"); read_file("source/f2.txt"); read_file("other_file"); #else for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) { if (!text[i][j]) break; add_index(root, text[i][j], files[i]); } } #endif return root; } void search_index(trie root, const char *word) { char path[1024]; printf("Search for \"%s\": ", word); trie found = find_word(root, word); if (!found) printf("not found\n"); else { trie_all(found->next[FNAME], path, 0, print_path); printf("\n"); } } int main() { trie root = init_tables(); search_index(root, "what"); search_index(root, "is"); search_index(root, "banana"); search_index(root, "boo"); return 0; }
package main import ( "bufio" "bytes" "errors" "fmt" "io" "os" ) var index map[string][]int var indexed []doc type doc struct { file string title string } func main() { index = make(map[string][]int) if err := indexDir("docs"); err != nil { fmt.Println(err) return } ui() } func indexDir(dir string) error { df, err := os.Open(dir) if err != nil { return err } fis, err := df.Readdir(-1) if err != nil { return err } if len(fis) == 0 { return errors.New(fmt.Sprintf("no files in %s", dir)) } indexed := 0 for _, fi := range fis { if !fi.IsDir() { if indexFile(dir + "/" + fi.Name()) { indexed++ } } } return nil } func indexFile(fn string) bool { f, err := os.Open(fn) if err != nil { fmt.Println(err) return false } x := len(indexed) indexed = append(indexed, doc{fn, fn}) pdoc := &indexed[x] r := bufio.NewReader(f) lines := 0 for { b, isPrefix, err := r.ReadLine() switch { case err == io.EOF: return true case err != nil: fmt.Println(err) return true case isPrefix: fmt.Printf("%s: unexpected long line\n", fn) return true case lines < 20 && bytes.HasPrefix(b, []byte("Title:")): pdoc.title = string(b[7:]) } wordLoop: for _, bword := range bytes.Fields(b) { bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@") if len(bword) > 0 { word := string(bword) dl := index[word] for _, d := range dl { if d == x { continue wordLoop } } index[word] = append(dl, x) } } } return true } func ui() { fmt.Println(len(index), "words indexed in", len(indexed), "files") fmt.Println("enter single words to search for") fmt.Println("enter a blank line when done") var word string for { fmt.Print("search word: ") wc, _ := fmt.Scanln(&word) if wc == 0 { return } switch dl := index[word]; len(dl) { case 0: fmt.Println("no match") case 1: fmt.Println("one match:") fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title) default: fmt.Println(len(dl), "matches:") for _, d := range dl { fmt.Println(" ", indexed[d].file, indexed[d].title) } } } }
Write the same code in Go as shown below in C.
#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; }
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)) }
Keep all operations the same but rewrite the snippet in Go.
#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; }
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)) }
Write the same algorithm in Go as shown in this C implementation.
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; }
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) } }
Write a version of this C function in Go with identical behavior.
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
Convert the following code from C to Go, ensuring the logic remains intact.
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
Convert the following code from C to Go, ensuring the logic remains intact.
#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) return 0; for(i=0;i<size-1;i++){ start:if(i!=size-2 && arr[i]>arr[i+1]){ ref1 = i; for(j=ref1+1;j<size;j++){ if(arr[j]>=arr[ref1]){ ref2 = j; sum += getWater(arr,ref1+1,ref2-1,ref1); i = ref2; goto start; } else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){ marker = j+1; markerSet = 1; } } if(markerSet==1){ sum += getWater(arr,ref1+1,marker-1,marker); i = marker; markerSet = 0; goto start; } } } return sum; } int main(int argC,char* argV[]) { int *arr,i; if(argC==1) printf("Usage : %s <followed by space separated series of integers>"); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<argC;i++) arr[i-1] = atoi(argV[i]); printf("Water collected : %d",netWater(arr,argC-1)); } return 0; }
package main import "fmt" func maxl(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := 0; i < len(hm);i++{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func maxr(hm []int ) []int{ res := make([]int,len(hm)) max := 1 for i := len(hm) - 1 ; i >= 0;i--{ if(hm[i] > max){ max = hm[i] } res[i] = max; } return res } func min(a,b []int) []int { res := make([]int,len(a)) for i := 0; i < len(a);i++{ if a[i] >= b[i]{ res[i] = b[i] }else { res[i] = a[i] } } return res } func diff(hm, min []int) []int { res := make([]int,len(hm)) for i := 0; i < len(hm);i++{ if min[i] > hm[i]{ res[i] = min[i] - hm[i] } } return res } func sum(a []int) int { res := 0 for i := 0; i < len(a);i++{ res += a[i] } return res } func waterCollected(hm []int) int { maxr := maxr(hm) maxl := maxl(hm) min := min(maxr,maxl) diff := diff(hm,min) sum := sum(diff) return sum } func main() { fmt.Println(waterCollected([]int{1, 5, 3, 7, 2})) fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2})) fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1})) fmt.Println(waterCollected([]int{5, 5, 5, 5})) fmt.Println(waterCollected([]int{5, 6, 7, 8})) fmt.Println(waterCollected([]int{8, 7, 7, 6})) fmt.Println(waterCollected([]int{6, 7, 10, 7, 6})) }
Convert this C block to Go, preserving its control flow and logic.
#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; while (1) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
package main import ( "fmt" "rcu" "sort" "strconv" ) func combinations(a []int, k int) [][]int { n := len(a) c := make([]int, k) var combs [][]int var combine func(start, end, index int) combine = func(start, end, index int) { if index == k { t := make([]int, len(c)) copy(t, c) combs = append(combs, t) return } for i := start; i <= end && end-i+1 >= k-index; i++ { c[index] = a[i] combine(i+1, end, index+1) } } combine(0, n-1, 0) return combs } func powerset(a []int) (res [][]int) { if len(a) == 0 { return } for i := 1; i <= len(a); i++ { res = append(res, combinations(a, i)...) } return } func main() { ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) var descPrimes []int for i := 1; i < len(ps); i++ { s := "" for _, e := range ps[i] { s += string(e + '0') } p, _ := strconv.Atoi(s) if rcu.IsPrime(p) { descPrimes = append(descPrimes, p) } } sort.Ints(descPrimes) fmt.Println("There are", len(descPrimes), "descending primes, namely:") for i := 0; i < len(descPrimes); i++ { fmt.Printf("%8d ", descPrimes[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
Generate a Go translation of this C snippet without changing its computational steps.
#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)); primes[0] = 2; count = 1; p = 3; for (;;) { p2 = p * p; if (p2 > limit) break; for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE; for (;;) { p += 2; if (!c[p]) break; } } for (i = 3; i <= limit; i += 2) { if (!c[i]) primes[count++] = i; } *length = count; free(c); } void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) { uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to); uint64 *primes = malloc((limit + 1) * sizeof(uint64)); bool add; sieve(limit, primes, &np); for (i = from; i <= to; ++i) { add = TRUE; for (j = 0; j < np; ++j) { p = primes[j]; p2 = p * p; if (p2 > i) break; if (i % p2 == 0) { add = FALSE; break; } } if (add) results[count++] = i; } *len = count; free(primes); } int main() { uint64 i, *sf, len; sf = malloc(1000000 * sizeof(uint64)); printf("Square-free integers from 1 to 145:\n"); squareFree(1, 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 20 == 0) { printf("\n"); } printf("%4lld", sf[i]); } printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145); squareFree(TRILLION, TRILLION + 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 5 == 0) { printf("\n"); } printf("%14lld", sf[i]); } printf("\n\nNumber of square-free integers:\n"); int a[5] = {100, 1000, 10000, 100000, 1000000}; for (i = 0; i < 5; ++i) { squareFree(1, a[i], sf, &len); printf(" from %d to %d = %lld\n", 1, a[i], len); } free(sf); return 0; }
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } for i := uint64(3); i <= limit; i += 2 { if !c[i] { primes = append(primes, i) } } return primes } func squareFree(from, to uint64) (results []uint64) { limit := uint64(math.Sqrt(float64(to))) primes := sieve(limit) outer: for i := from; i <= to; i++ { for _, p := range primes { p2 := p * p if p2 > i { break } if i%p2 == 0 { continue outer } } results = append(results, i) } return } const trillion uint64 = 1000000000000 func main() { fmt.Println("Square-free integers from 1 to 145:") sf := squareFree(1, 145) for i := 0; i < len(sf); i++ { if i > 0 && i%20 == 0 { fmt.Println() } fmt.Printf("%4d", sf[i]) } fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145) sf = squareFree(trillion, trillion+145) for i := 0; i < len(sf); i++ { if i > 0 && i%5 == 0 { fmt.Println() } fmt.Printf("%14d", sf[i]) } fmt.Println("\n\nNumber of square-free integers:\n") a := [...]uint64{100, 1000, 10000, 100000, 1000000} for _, n := range a { fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n))) } }
Produce a language-to-language conversion: from C to Go, same semantics.
#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)); primes[0] = 2; count = 1; p = 3; for (;;) { p2 = p * p; if (p2 > limit) break; for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE; for (;;) { p += 2; if (!c[p]) break; } } for (i = 3; i <= limit; i += 2) { if (!c[i]) primes[count++] = i; } *length = count; free(c); } void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) { uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to); uint64 *primes = malloc((limit + 1) * sizeof(uint64)); bool add; sieve(limit, primes, &np); for (i = from; i <= to; ++i) { add = TRUE; for (j = 0; j < np; ++j) { p = primes[j]; p2 = p * p; if (p2 > i) break; if (i % p2 == 0) { add = FALSE; break; } } if (add) results[count++] = i; } *len = count; free(primes); } int main() { uint64 i, *sf, len; sf = malloc(1000000 * sizeof(uint64)); printf("Square-free integers from 1 to 145:\n"); squareFree(1, 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 20 == 0) { printf("\n"); } printf("%4lld", sf[i]); } printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145); squareFree(TRILLION, TRILLION + 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 5 == 0) { printf("\n"); } printf("%14lld", sf[i]); } printf("\n\nNumber of square-free integers:\n"); int a[5] = {100, 1000, 10000, 100000, 1000000}; for (i = 0; i < 5; ++i) { squareFree(1, a[i], sf, &len); printf(" from %d to %d = %lld\n", 1, a[i], len); } free(sf); return 0; }
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } for i := uint64(3); i <= limit; i += 2 { if !c[i] { primes = append(primes, i) } } return primes } func squareFree(from, to uint64) (results []uint64) { limit := uint64(math.Sqrt(float64(to))) primes := sieve(limit) outer: for i := from; i <= to; i++ { for _, p := range primes { p2 := p * p if p2 > i { break } if i%p2 == 0 { continue outer } } results = append(results, i) } return } const trillion uint64 = 1000000000000 func main() { fmt.Println("Square-free integers from 1 to 145:") sf := squareFree(1, 145) for i := 0; i < len(sf); i++ { if i > 0 && i%20 == 0 { fmt.Println() } fmt.Printf("%4d", sf[i]) } fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145) sf = squareFree(trillion, trillion+145) for i := 0; i < len(sf); i++ { if i > 0 && i%5 == 0 { fmt.Println() } fmt.Printf("%14d", sf[i]) } fmt.Println("\n\nNumber of square-free integers:\n") a := [...]uint64{100, 1000, 10000, 100000, 1000000} for _, n := range a { fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n))) } }
Port the following code from C to Go with equivalent syntax and logic.
#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); if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0; int match_distance = (int) max(str1_len, str2_len)/2 - 1; int *str1_matches = calloc(str1_len, sizeof(int)); int *str2_matches = calloc(str2_len, sizeof(int)); double matches = 0.0; double transpositions = 0.0; for (int i = 0; i < str1_len; i++) { int start = max(0, i - match_distance); int end = min(i + match_distance + 1, str2_len); for (int k = start; k < end; k++) { if (str2_matches[k]) continue; if (str1[i] != str2[k]) continue; str1_matches[i] = TRUE; str2_matches[k] = TRUE; matches++; break; } } if (matches == 0) { free(str1_matches); free(str2_matches); return 0.0; } int k = 0; for (int i = 0; i < str1_len; i++) { if (!str1_matches[i]) continue; while (!str2_matches[k]) k++; if (str1[i] != str2[k]) transpositions++; k++; } transpositions /= 2.0; free(str1_matches); free(str2_matches); return ((matches / str1_len) + (matches / str2_len) + ((matches - transpositions) / matches)) / 3.0; } int main() { printf("%f\n", jaro("MARTHA", "MARHTA")); printf("%f\n", jaro("DIXON", "DICKSONX")); printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")); }
package main import "fmt" func jaro(str1, str2 string) float64 { if len(str1) == 0 && len(str2) == 0 { return 1 } if len(str1) == 0 || len(str2) == 0 { return 0 } match_distance := len(str1) if len(str2) > match_distance { match_distance = len(str2) } match_distance = match_distance/2 - 1 str1_matches := make([]bool, len(str1)) str2_matches := make([]bool, len(str2)) matches := 0. transpositions := 0. for i := range str1 { start := i - match_distance if start < 0 { start = 0 } end := i + match_distance + 1 if end > len(str2) { end = len(str2) } for k := start; k < end; k++ { if str2_matches[k] { continue } if str1[i] != str2[k] { continue } str1_matches[i] = true str2_matches[k] = true matches++ break } } if matches == 0 { return 0 } k := 0 for i := range str1 { if !str1_matches[i] { continue } for !str2_matches[k] { k++ } if str1[i] != str2[k] { transpositions++ } k++ } transpositions /= 2 return (matches/float64(len(str1)) + matches/float64(len(str2)) + (matches-transpositions)/matches) / 3 } func main() { fmt.Printf("%f\n", jaro("MARTHA", "MARHTA")) fmt.Printf("%f\n", jaro("DIXON", "DICKSONX")) fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")) }
Write the same code in Go as shown below in C.
#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) { if (n == NULL) { return; } (*n)->prev = NULL; (*n)->next = NULL; free(*n); *n = NULL; } typedef struct list_t { node *head; node *tail; } list; list make_list() { list lst = { NULL, NULL }; return lst; } void append_node(list *const lst, int x, int y) { if (lst == NULL) { return; } node *n = new_node(x, y); if (lst->head == NULL) { lst->head = n; lst->tail = n; } else { n->prev = lst->tail; lst->tail->next = n; lst->tail = n; } } void remove_node(list *const lst, const node *const n) { if (lst == NULL || n == NULL) { return; } if (n->prev != NULL) { n->prev->next = n->next; if (n->next != NULL) { n->next->prev = n->prev; } else { lst->tail = n->prev; } } else { if (n->next != NULL) { n->next->prev = NULL; lst->head = n->next; } } free_node(&n); } void free_list(list *const lst) { node *ptr; if (lst == NULL) { return; } ptr = lst->head; while (ptr != NULL) { node *nxt = ptr->next; free_node(&ptr); ptr = nxt; } lst->head = NULL; lst->tail = NULL; } void print_list(const list *lst) { node *it; if (lst == NULL) { return; } for (it = lst->head; it != NULL; it = it->next) { int sum = it->x + it->y; int prod = it->x * it->y; printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod); } } void print_count(const list *const lst) { node *it; int c = 0; if (lst == NULL) { return; } for (it = lst->head; it != NULL; it = it->next) { c++; } if (c == 0) { printf("no candidates\n"); } else if (c == 1) { printf("one candidate\n"); } else { printf("%d candidates\n", c); } } void setup(list *const lst) { int x, y; if (lst == NULL) { return; } for (x = 2; x <= 98; x++) { for (y = x + 1; y <= 98; y++) { if (x + y <= 100) { append_node(lst, x, y); } } } } void remove_by_sum(list *const lst, const int sum) { node *it; if (lst == NULL) { return; } it = lst->head; while (it != NULL) { int s = it->x + it->y; if (s == sum) { remove_node(lst, it); it = lst->head; } else { it = it->next; } } } void remove_by_prod(list *const lst, const int prod) { node *it; if (lst == NULL) { return; } it = lst->head; while (it != NULL) { int p = it->x * it->y; if (p == prod) { remove_node(lst, it); it = lst->head; } else { it = it->next; } } } void statement1(list *const lst) { short *unique = calloc(100000, sizeof(short)); node *it, *nxt; for (it = lst->head; it != NULL; it = it->next) { int prod = it->x * it->y; unique[prod]++; } it = lst->head; while (it != NULL) { int prod = it->x * it->y; nxt = it->next; if (unique[prod] == 1) { remove_by_sum(lst, it->x + it->y); it = lst->head; } else { it = nxt; } } free(unique); } void statement2(list *const candidates) { short *unique = calloc(100000, sizeof(short)); node *it, *nxt; for (it = candidates->head; it != NULL; it = it->next) { int prod = it->x * it->y; unique[prod]++; } it = candidates->head; while (it != NULL) { int prod = it->x * it->y; nxt = it->next; if (unique[prod] > 1) { remove_by_prod(candidates, prod); it = candidates->head; } else { it = nxt; } } free(unique); } void statement3(list *const candidates) { short *unique = calloc(100, sizeof(short)); node *it, *nxt; for (it = candidates->head; it != NULL; it = it->next) { int sum = it->x + it->y; unique[sum]++; } it = candidates->head; while (it != NULL) { int sum = it->x + it->y; nxt = it->next; if (unique[sum] > 1) { remove_by_sum(candidates, sum); it = candidates->head; } else { it = nxt; } } free(unique); } int main() { list candidates = make_list(); setup(&candidates); print_count(&candidates); statement1(&candidates); print_count(&candidates); statement2(&candidates); print_count(&candidates); statement3(&candidates); print_count(&candidates); print_list(&candidates); free_list(&candidates); return 0; }
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all) var sPairs []pair pairs: for _, p := range all { s := p.x + p.y for a := 2; a < s/2+s&1; a++ { b := s - a if products[a*b] == 1 { continue pairs } } sPairs = append(sPairs, p) } fmt.Println("S starts with", len(sPairs), "possible pairs.") sProducts := countProducts(sPairs) var pPairs []pair for _, p := range sPairs { if sProducts[p.x*p.y] == 1 { pPairs = append(pPairs, p) } } fmt.Println("P then has", len(pPairs), "possible pairs.") pSums := countSums(pPairs) var final []pair for _, p := range pPairs { if pSums[p.x+p.y] == 1 { final = append(final, p) } } switch len(final) { case 1: fmt.Println("Answer:", final[0].x, "and", final[0].y) case 0: fmt.Println("No possible answer.") default: fmt.Println(len(final), "possible answers:", final) } } func countProducts(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x*p.y]++ } return m } func countSums(list []pair) map[int]int { m := make(map[int]int) for _, p := range list { m[p.x+p.y]++ } return m } func decomposeSum(s int) []pair { pairs := make([]pair, 0, s/2) for a := 2; a < s/2+s&1; a++ { pairs = append(pairs, pair{a, s - a}) } return pairs }
Change the programming language of this snippet from C to Go without modifying what it does.
#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++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { int *cnt = calloc(base, sizeof(int)); int i, minTurn, maxTurn, portion; if (NULL == cnt) { printf("Failed to allocate space to determine the spread of turns.\n"); return; } for (i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } minTurn = INT_MAX; maxTurn = INT_MIN; portion = 0; for (i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } free(cnt); } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } return res } func turns(n int, fss []int) string { m := make(map[int]int) for _, fs := range fss { m[fs]++ } m2 := make(map[int]int) for _, v := range m { m2[v]++ } res := []int{} sum := 0 for k, v := range m2 { sum += v res = append(res, k) } if sum != n { return fmt.Sprintf("only %d have a turn", sum) } sort.Ints(res) res2 := make([]string, len(res)) for i := range res { res2[i] = strconv.Itoa(res[i]) } return strings.Join(res2, " or ") } func main() { for _, base := range []int{2, 3, 5, 11} { fmt.Printf("%2d : %2d\n", base, fairshare(25, base)) } fmt.Println("\nHow many times does each get a turn in 50000 iterations?") for _, base := range []int{191, 1377, 49999, 50000, 50001} { t := turns(base, fairshare(50000, base)) fmt.Printf(" With %d people: %s\n", base, t) } }
Please provide an equivalent version of this C code in Go.
#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]; } cylinder[0] = t; } static void unload() { int i; for (i = 0; i < 6; i++) { cylinder[i] = false; } } static void load() { while (cylinder[0]) { rshift(); } cylinder[0] = true; rshift(); } static void spin() { int lim = nextInt(6) + 1; int i; for (i = 1; i < lim; i++) { rshift(); } } static bool fire() { bool shot = cylinder[0]; rshift(); return shot; } static int method(const char *s) { unload(); for (; *s != '\0'; s++) { switch (*s) { case 'L': load(); break; case 'S': spin(); break; case 'F': if (fire()) { return 1; } break; } } return 0; } static void append(char *out, const char *txt) { if (*out != '\0') { strcat(out, ", "); } strcat(out, txt); } static void mstring(const char *s, char *out) { for (; *s != '\0'; s++) { switch (*s) { case 'L': append(out, "load"); break; case 'S': append(out, "spin"); break; case 'F': append(out, "fire"); break; } } } static void test(char *src) { char buffer[41] = ""; const int tests = 100000; int sum = 0; int t; double pc; for (t = 0; t < tests; t++) { sum += method(src); } mstring(src, buffer); pc = 100.0 * sum / tests; printf("%-40s produces %6.3f%% deaths.\n", buffer, pc); } int main() { srand(time(0)); test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF"); return 0; }
package main import ( "fmt" "math/rand" "strings" "time" ) var cylinder = [6]bool{} func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t } func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } func load() { for cylinder[0] { rshift() } cylinder[0] = true rshift() } func spin() { var lim = 1 + rand.Intn(6) for i := 1; i < lim; i++ { rshift() } } func fire() bool { shot := cylinder[0] rshift() return shot } func method(s string) int { unload() for _, c := range s { switch c { case 'L': load() case 'S': spin() case 'F': if fire() { return 1 } } } return 0 } func mstring(s string) string { var l []string for _, c := range s { switch c { case 'L': l = append(l, "load") case 'S': l = append(l, "spin") case 'F': l = append(l, "fire") } } return strings.Join(l, ", ") } func main() { rand.Seed(time.Now().UnixNano()) tests := 100000 for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} { sum := 0 for t := 1; t <= tests; t++ { sum += method(m) } pc := float64(sum) * 100 / float64(tests) fmt.Printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc) } }
Preserve the algorithm and functionality while converting the code from C to Go.
#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}, {"^\\*\\*", A_R, 3}, {"^\\^", A_R, 3}, {"^\\*", A_L, 2}, {"^/", A_L, 2}, {"^\\+", A_L, 1}, {"^-", A_L, 1}, {0} }; pat_t pat_arg[] = { {"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"}, {"^[a-zA-Z_][a-zA-Z_0-9]*"}, {"^\\(", A_L, -1}, {0} }; str_tok_t stack[256]; str_tok_t queue[256]; int l_queue, l_stack; #define qpush(x) queue[l_queue++] = x #define spush(x) stack[l_stack++] = x #define spop() stack[--l_stack] void display(const char *s) { int i; printf("\033[1;1H\033[JText | %s", s); printf("\nStack| "); for (i = 0; i < l_stack; i++) printf("%.*s ", stack[i].len, stack[i].s); printf("\nQueue| "); for (i = 0; i < l_queue; i++) printf("%.*s ", queue[i].len, queue[i].s); puts("\n\n<press enter>"); getchar(); } int prec_booster; #define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;} int init(void) { int i; pat_t *p; for (i = 0, p = pat_ops; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); for (i = 0, p = pat_arg; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); return 1; } pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e) { int i; regmatch_t m; while (*s == ' ') s++; *e = s; if (!*s) return &pat_eos; for (i = 0; p[i].str; i++) { if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL)) continue; t->s = s; *e = s + (t->len = m.rm_eo - m.rm_so); return p + i; } return 0; } int parse(const char *s) { pat_t *p; str_tok_t *t, tok; prec_booster = l_queue = l_stack = 0; display(s); while (*s) { p = match(s, pat_arg, &tok, &s); if (!p || p == &pat_eos) fail("parse arg", s); if (p->prec == -1) { prec_booster += 100; continue; } qpush(tok); display(s); re_op: p = match(s, pat_ops, &tok, &s); if (!p) fail("parse op", s); tok.assoc = p->assoc; tok.prec = p->prec; if (p->prec > 0) tok.prec = p->prec + prec_booster; else if (p->prec == -1) { if (prec_booster < 100) fail("unmatched )", s); tok.prec = prec_booster; } while (l_stack) { t = stack + l_stack - 1; if (!(t->prec == tok.prec && t->assoc == A_L) && t->prec <= tok.prec) break; qpush(spop()); display(s); } if (p->prec == -1) { prec_booster -= 100; goto re_op; } if (!p->prec) { display(s); if (prec_booster) fail("unmatched (", s); return 1; } spush(tok); display(s); } if (p->prec > 0) fail("unexpected eol", s); return 1; } int main() { int i; const char *tests[] = { "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3", "123", "3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14", "(((((((1+2+3**(4 + 5))))))", "a^(b + c/d * .1e5)!", "(1**2)**3", "2 + 2 *", 0 }; if (!init()) return 1; for (i = 0; tests[i]; i++) { printf("Testing string `%s' <enter>\n", tests[i]); getchar(); printf("string `%s': %s\n\n", tests[i], parse(tests[i]) ? "Ok" : "Error"); } return 0; }
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) case ")": var op string for { op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break } rpn += " " + op } default: if o1, isOp := opa[tok]; isOp { for len(stack) > 0 { op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } stack = stack[:len(stack)-1] rpn += " " + op } stack = append(stack, tok) } else { if rpn > "" { rpn += " " } rpn += tok } } } for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
Produce a language-to-language conversion: from C to Go, same semantics.
#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}, {"^\\*\\*", A_R, 3}, {"^\\^", A_R, 3}, {"^\\*", A_L, 2}, {"^/", A_L, 2}, {"^\\+", A_L, 1}, {"^-", A_L, 1}, {0} }; pat_t pat_arg[] = { {"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"}, {"^[a-zA-Z_][a-zA-Z_0-9]*"}, {"^\\(", A_L, -1}, {0} }; str_tok_t stack[256]; str_tok_t queue[256]; int l_queue, l_stack; #define qpush(x) queue[l_queue++] = x #define spush(x) stack[l_stack++] = x #define spop() stack[--l_stack] void display(const char *s) { int i; printf("\033[1;1H\033[JText | %s", s); printf("\nStack| "); for (i = 0; i < l_stack; i++) printf("%.*s ", stack[i].len, stack[i].s); printf("\nQueue| "); for (i = 0; i < l_queue; i++) printf("%.*s ", queue[i].len, queue[i].s); puts("\n\n<press enter>"); getchar(); } int prec_booster; #define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;} int init(void) { int i; pat_t *p; for (i = 0, p = pat_ops; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); for (i = 0, p = pat_arg; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); return 1; } pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e) { int i; regmatch_t m; while (*s == ' ') s++; *e = s; if (!*s) return &pat_eos; for (i = 0; p[i].str; i++) { if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL)) continue; t->s = s; *e = s + (t->len = m.rm_eo - m.rm_so); return p + i; } return 0; } int parse(const char *s) { pat_t *p; str_tok_t *t, tok; prec_booster = l_queue = l_stack = 0; display(s); while (*s) { p = match(s, pat_arg, &tok, &s); if (!p || p == &pat_eos) fail("parse arg", s); if (p->prec == -1) { prec_booster += 100; continue; } qpush(tok); display(s); re_op: p = match(s, pat_ops, &tok, &s); if (!p) fail("parse op", s); tok.assoc = p->assoc; tok.prec = p->prec; if (p->prec > 0) tok.prec = p->prec + prec_booster; else if (p->prec == -1) { if (prec_booster < 100) fail("unmatched )", s); tok.prec = prec_booster; } while (l_stack) { t = stack + l_stack - 1; if (!(t->prec == tok.prec && t->assoc == A_L) && t->prec <= tok.prec) break; qpush(spop()); display(s); } if (p->prec == -1) { prec_booster -= 100; goto re_op; } if (!p->prec) { display(s); if (prec_booster) fail("unmatched (", s); return 1; } spush(tok); display(s); } if (p->prec > 0) fail("unexpected eol", s); return 1; } int main() { int i; const char *tests[] = { "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3", "123", "3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14", "(((((((1+2+3**(4 + 5))))))", "a^(b + c/d * .1e5)!", "(1**2)**3", "2 + 2 *", 0 }; if (!init()) return 1; for (i = 0; tests[i]; i++) { printf("Testing string `%s' <enter>\n", tests[i]); getchar(); printf("string `%s': %s\n\n", tests[i], parse(tests[i]) ? "Ok" : "Error"); } return 0; }
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) case ")": var op string for { op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break } rpn += " " + op } default: if o1, isOp := opa[tok]; isOp { for len(stack) > 0 { op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } stack = stack[:len(stack)-1] rpn += " " + op } stack = append(stack, tok) } else { if rpn > "" { rpn += " " } rpn += tok } } } for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
Convert this C block to Go, preserving its control flow and logic.
#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, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0}; return isprime[n]; } void swap(unsigned int* a, size_t i, size_t j) { unsigned int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } bool prime_triangle_row(unsigned int* a, size_t length) { if (length == 2) return is_prime(a[0] + a[1]); for (size_t i = 1; i + 1 < length; i += 2) { if (is_prime(a[0] + a[i])) { swap(a, i, 1); if (prime_triangle_row(a + 1, length - 1)) return true; swap(a, i, 1); } } return false; } int prime_triangle_count(unsigned int* a, size_t length) { int count = 0; if (length == 2) { if (is_prime(a[0] + a[1])) ++count; } else { for (size_t i = 1; i + 1 < length; i += 2) { if (is_prime(a[0] + a[i])) { swap(a, i, 1); count += prime_triangle_count(a + 1, length - 1); swap(a, i, 1); } } } return count; } void print(unsigned int* a, size_t length) { if (length == 0) return; printf("%2u", a[0]); for (size_t i = 1; i < length; ++i) printf(" %2u", a[i]); printf("\n"); } int main() { clock_t start = clock(); for (unsigned int n = 2; n < 21; ++n) { unsigned int a[n]; for (unsigned int i = 0; i < n; ++i) a[i] = i + 1; if (prime_triangle_row(a, n)) print(a, n); } printf("\n"); for (unsigned int n = 2; n < 21; ++n) { unsigned int a[n]; for (unsigned int i = 0; i < n; ++i) a[i] = i + 1; if (n > 2) printf(" "); printf("%d", prime_triangle_count(a, n)); } printf("\n"); clock_t end = clock(); double duration = (end - start + 0.0) / CLOCKS_PER_SEC; printf("\nElapsed time: %f seconds\n", duration); return 0; }
package main import "fmt" var canFollow [][]bool var arrang []int var bFirst = true var pmap = make(map[int]bool) func init() { for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} { pmap[i] = true } } func ptrs(res, n, done int) int { ad := arrang[done-1] if n-done <= 1 { if canFollow[ad-1][n-1] { if bFirst { for _, e := range arrang { fmt.Printf("%2d ", e) } fmt.Println() bFirst = false } res++ } } else { done++ for i := done - 1; i <= n-2; i += 2 { ai := arrang[i] if canFollow[ad-1][ai-1] { arrang[i], arrang[done-1] = arrang[done-1], arrang[i] res = ptrs(res, n, done) arrang[i], arrang[done-1] = arrang[done-1], arrang[i] } } } return res } func primeTriangle(n int) int { canFollow = make([][]bool, n) for i := 0; i < n; i++ { canFollow[i] = make([]bool, n) for j := 0; j < n; j++ { _, ok := pmap[i+j+2] canFollow[i][j] = ok } } bFirst = true arrang = make([]int, n) for i := 0; i < n; i++ { arrang[i] = i + 1 } return ptrs(0, n, 1) } func main() { counts := make([]int, 19) for i := 2; i <= 20; i++ { counts[i-2] = primeTriangle(i) } fmt.Println() for i := 0; i < 19; i++ { fmt.Printf("%d ", counts[i]) } fmt.Println() }
Produce a language-to-language conversion: from C to Go, same semantics.
#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--) { result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3); printf ("\nf(%lf) = "); if (result > check) { printf ("Overflow!"); } else { printf ("%lf", result); } } return 0; }
package main import ( "fmt" "log" "math" ) func main() { fmt.Print("Enter 11 numbers: ") var s [11]float64 for i := 0; i < 11; { if n, _ := fmt.Scan(&s[i]); n > 0 { i++ } } for i, item := range s[:5] { s[i], s[10-i] = s[10-i], item } for _, item := range s { if result, overflow := f(item); overflow { log.Printf("f(%g) overflow", item) } else { fmt.Printf("f(%g) = %g\n", item, result) } } } func f(x float64) (float64, bool) { result := math.Sqrt(math.Abs(x)) + 5*x*x*x return result, result > 400 }
Ensure the translated Go code behaves exactly like the original C snippet.
#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, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, 1234567890}; int i; char *m; for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) { if (!(m = mid3(x[i]))) m = "error"; printf("%d: %s\n", x[i], m); } return 0; }
package m3 import ( "errors" "strconv" ) var ( ErrorLT3 = errors.New("N of at least three digits required.") ErrorEven = errors.New("N with odd number of digits required.") ) func Digits(i int) (string, error) { if i < 0 { i = -i } if i < 100 { return "", ErrorLT3 } s := strconv.Itoa(i) if len(s)%2 == 0 { return "", ErrorEven } m := len(s) / 2 return s[m-1 : m+2], nil }
Translate this program into Go but keep the logic exactly as in C.
#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] * smallPrimes[j] <= p) { if (p % smallPrimes[j] == 0) { p += 2; break; } } else { smallPrimes[i++] = p; p += 2; break; } } } } static bool is_prime(uint64_t n) { uint64_t i; for (i = 0; i < LIMIT; i++) { if (n % smallPrimes[i] == 0) { return n == smallPrimes[i]; } } i = smallPrimes[LIMIT - 1] + 2; for (; i * i <= n; i += 2) { if (n % i == 0) { return false; } } return true; } static uint64_t divisor_count(uint64_t n) { uint64_t count = 1; uint64_t d; while (n % 2 == 0) { n /= 2; count++; } for (d = 3; d * d <= n; d += 2) { uint64_t q = n / d; uint64_t r = n % d; uint64_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { return count *= 2; } return count; } static uint64_t OEISA073916(size_t n) { uint64_t count = 0; uint64_t result = 0; size_t i; if (is_prime(n)) { return (uint64_t)pow(smallPrimes[n - 1], n - 1); } for (i = 1; count < n; i++) { if (n % 2 == 1) { uint64_t root = (uint64_t)sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { size_t n; sieve(); for (n = 1; n <= LIMIT; n++) { if (n == 13) { printf("A073916(%lu) = One more bit needed to represent result.\n", n); } else { printf("A073916(%lu) = %llu\n", n, OEISA073916(n)); } } return 0; }
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if isPrime(i) { primes[count] = i count++ } } return primes } func countDivisors(n int) int { count := 1 for n%2 == 0 { n >>= 1 count++ } for d := 3; d*d <= n; d += 2 { q, r := n/d, n%d if r == 0 { dc := 0 for r == 0 { dc += count n = q q, r = n/d, n%d } count += dc } } if n != 1 { count *= 2 } return count } func main() { const max = 33 primes := generateSmallPrimes(max) z := new(big.Int) p := new(big.Int) fmt.Println("The first", max, "terms in the sequence are:") for i := 1; i <= max; i++ { if isPrime(i) { z.SetUint64(uint64(primes[i-1])) p.SetUint64(uint64(i - 1)) z.Exp(z, p, nil) fmt.Printf("%2d : %d\n", i, z) } else { count := 0 for j := 1; ; j++ { if i%2 == 1 { sq := int(math.Sqrt(float64(j))) if sq*sq != j { continue } } if countDivisors(j) == i { count++ if count == i { fmt.Printf("%2d : %d\n", i, j) break } } } } } }
Convert this C snippet to Go and keep its semantics consistent.
#include <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]; for (i = 0; i < MAX; ++i) seq[i] = 0; printf("The first %d terms of the sequence are:\n", MAX); for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) printf("%d ", seq[i]); printf("\n"); return 0; }
package main import "fmt" func countDivisors(n int) int { count := 0 for i := 1; i*i <= n; i++ { if n%i == 0 { if i == n/i { count++ } else { count += 2 } } } return count } func main() { const max = 15 seq := make([]int, max) fmt.Println("The first", max, "terms of the sequence are:") for i, n := 1, 0; n < max; i++ { if k := countDivisors(i); k <= max && seq[k-1] == 0 { seq[k-1] = i n++ } } fmt.Println(seq) }
Port the provided C code into Go while preserving the original functionality.
#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; printf("p(%2d) = %2d ", n, pancake(n)); } printf("\n"); } return 0; }
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) = %2d ", n, pancake(n)) } fmt.Println() } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <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; printf("p(%2d) = %2d ", n, pancake(n)); } printf("\n"); } return 0; }
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) = %2d ", n, pancake(n)) } fmt.Println() } }
Maintain the same structure and functionality when rewriting this code in Go.
#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() % 8; if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) { grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; return; } } } void placePieces(const char *pieces, bool isPawn) { int n, r, c; int numToPlace = rand() % strlen(pieces); for (n = 0; n < numToPlace; ++n) { do { r = rand() % 8; c = rand() % 8; } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces[n]; } } void toFen() { char fen[80], ch; int r, c, countEmpty = 0, index = 0; for (r = 0; r < 8; ++r) { for (c = 0; c < 8; ++c) { ch = grid[r][c]; printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++] = ch; } } if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++]= '/'; printf("\n"); } strcpy(fen + index, " w - - 0 1"); printf("%s\n", fen); } char *createFen() { placeKings(); placePieces("PPPPPPPP", TRUE); placePieces("pppppppp", TRUE); placePieces("RNBQBNR", FALSE); placePieces("rnbqbnr", FALSE); toFen(); } int main() { srand(time(NULL)); createFen(); return 0; }
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) placePieces("RNBQBNR", false) placePieces("rnbqbnr", false) return toFen() } func placeKings() { for { r1 := rand.Intn(8) c1 := rand.Intn(8) r2 := rand.Intn(8) c2 := rand.Intn(8) if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 { grid[r1][c1] = 'K' grid[r2][c2] = 'k' return } } } func placePieces(pieces string, isPawn bool) { numToPlace := rand.Intn(len(pieces)) for n := 0; n < numToPlace; n++ { var r, c int for { r = rand.Intn(8) c = rand.Intn(8) if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) { break } } grid[r][c] = pieces[n] } } func toFen() string { var fen strings.Builder countEmpty := 0 for r := 0; r < 8; r++ { for c := 0; c < 8; c++ { ch := grid[r][c] if ch == '\000' { ch = '.' } fmt.Printf("%2c ", ch) if ch == '.' { countEmpty++ } else { if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteByte(ch) } } if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteString("/") fmt.Println() } fen.WriteString(" w - - 0 1") return fen.String() } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(createFen()) }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> #include <string.h> #include <locale.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 char as_digit(int d) { return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a'; } void revstr(char *str) { int i, len = strlen(str); char t; for (i = 0; i < len/2; ++i) { t = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = t; } } char* to_base(char s[], ull n, int b) { int i = 0; while (n) { s[i++] = as_digit(n % b); n /= b; } s[i] = '\0'; revstr(s); return s; } ull uabs(ull a, ull b) { return a > b ? a - b : b - a; } bool is_esthetic(ull n, int b) { int i, j; if (!n) return FALSE; i = n % b; n /= b; while (n) { j = n % b; if (uabs(i, j) != 1) return FALSE; n /= b; i = j; } return TRUE; } ull esths[45000]; int le = 0; void dfs(ull n, ull m, ull i) { ull d, i1, i2; if (i >= n && i <= m) esths[le++] = i; if (i == 0 || i > m) return; d = i % 10; i1 = i * 10 + d - 1; i2 = i1 + 2; if (d == 0) { dfs(n, m, i2); } else if (d == 9) { dfs(n, m, i1); } else { dfs(n, m, i1); dfs(n, m, i2); } } void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) { int i; le = 0; for (i = 0; i < 10; ++i) { dfs(n2, m2, i); } printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m); if (all) { for (i = 0; i < le; ++i) { printf("%llu ", esths[i]); if (!(i+1)%per_line) printf("\n"); } } else { for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]); printf("\n............\n"); for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]); } printf("\n\n"); } int main() { ull n; int b, c; char ch[15] = {0}; for (b = 2; b <= 16; ++b) { printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b); for (n = 1, c = 0; c < 6 * b; ++n) { if (is_esthetic(n, b)) { if (++c >= 4 * b) printf("%s ", to_base(ch, n, b)); } } printf("\n\n"); } char *oldLocale = setlocale(LC_NUMERIC, NULL); setlocale(LC_NUMERIC, ""); list_esths(1000, 1010, 9999, 9898, 16, TRUE); list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE); list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE); list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE); list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE); setlocale(LC_NUMERIC, oldLocale); return 0; }
package main import ( "fmt" "strconv" ) func uabs(a, b uint64) uint64 { if a > b { return a - b } return b - a } func isEsthetic(n, b uint64) bool { if n == 0 { return false } i := n % b n /= b for n > 0 { j := n % b if uabs(i, j) != 1 { return false } n /= b i = j } return true } var esths []uint64 func dfs(n, m, i uint64) { if i >= n && i <= m { esths = append(esths, i) } if i == 0 || i > m { return } d := i % 10 i1 := i*10 + d - 1 i2 := i1 + 2 if d == 0 { dfs(n, m, i2) } else if d == 9 { dfs(n, m, i1) } else { dfs(n, m, i1) dfs(n, m, i2) } } func listEsths(n, n2, m, m2 uint64, perLine int, all bool) { esths = esths[:0] for i := uint64(0); i < 10; i++ { dfs(n2, m2, i) } le := len(esths) fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n", commatize(uint64(le)), commatize(n), commatize(m)) if all { for c, esth := range esths { fmt.Printf("%d ", esth) if (c+1)%perLine == 0 { fmt.Println() } } } else { for i := 0; i < perLine; i++ { fmt.Printf("%d ", esths[i]) } fmt.Println("\n............\n") for i := le - perLine; i < le; i++ { fmt.Printf("%d ", esths[i]) } } fmt.Println("\n") } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { for b := uint64(2); b <= 16; b++ { fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b) for n, c := uint64(1), uint64(0); c < 6*b; n++ { if isEsthetic(n, b) { c++ if c >= 4*b { fmt.Printf("%s ", strconv.FormatUint(n, int(b))) } } } fmt.Println("\n") } listEsths(1000, 1010, 9999, 9898, 16, true) listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true) listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false) listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false) listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false) }