Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KeyType const char * #define ValType int #define HASH_SIZE 4096 unsigned strhashkey( const char * key, int max) { unsigned h=0; unsigned hl, hr; while(*key) { h += *key; hl= 0x5C5 ^ (h&0xfff00000 )>>18; hr =(h&0x000fffff ); h = hl ^ hr ^ *key++; } return h % max; } typedef struct sHme { KeyType key; ValType value; struct sHme *link; } *MapEntry; typedef struct he { MapEntry first, last; } HashElement; HashElement hash[HASH_SIZE]; typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc); typedef void (*ValCopyF)(ValType *vdest, ValType vsrc); typedef unsigned (*KeyHashF)( KeyType key, int upperBound ); typedef int (*KeyCmprF)(KeyType key1, KeyType key2); void HashAddH( KeyType key, ValType value, KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { (*copyVal)(&m_ent->value, value); } else { MapEntry last; MapEntry hme = malloc(sizeof(struct sHme)); (*copyKey)(&hme->key, key); (*copyVal)(&hme->value, value); hme->link = NULL; last = hash[hix].last; if (last) { last->link = hme; } else hash[hix].first = hme; hash[hix].last = hme; } } int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { *val = m_ent->value; } return (m_ent != NULL); } void copyStr(const char**dest, const char *src) { *dest = strdup(src); } void copyInt( int *dest, int src) { *dest = src; } int strCompare( const char *key1, const char *key2) { return strcmp(key1, key2) == 0; } void HashAdd( KeyType key, ValType value ) { HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare); } int HashGet(ValType *val, KeyType key) { return HashGetH( val, key, &strhashkey, &strCompare); } int main() { static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" }; static int valuList[] = {1,43,640, 747, 42, 42}; int ix; for (ix=0; ix<6; ix++) { HashAdd(keyList[ix], valuList[ix]); } return 0; }
package main import "fmt" func main() { keys := []string{"a", "b", "c"} vals := []int{1, 2, 3} hash := map[string]int{} for i, key := range keys { hash[key] = vals[i] } fmt.Println(hash) }
Write a version of this C function in Go with identical behavior.
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
package main import ( "fmt" "sort" ) func getBins(limits, data []int) []int { n := len(limits) bins := make([]int, n+1) for _, d := range data { index := sort.SearchInts(limits, d) if index < len(limits) && d == limits[index] { index++ } bins[index]++ } return bins } func printBins(limits, bins []int) { n := len(limits) fmt.Printf(" < %3d = %2d\n", limits[0], bins[0]) for i := 1; i < n; i++ { fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i]) } fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n]) fmt.Println() } func main() { limitsList := [][]int{ {23, 37, 43, 53, 67, 83}, {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}, } dataList := [][]int{ { 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55, }, { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749, }, } for i := 0; i < len(limitsList); i++ { fmt.Println("Example", i+1, "\b\n") bins := getBins(limitsList[i], dataList[i]) printBins(limitsList[i], bins) } }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
package main import ( "fmt" "sort" ) func getBins(limits, data []int) []int { n := len(limits) bins := make([]int, n+1) for _, d := range data { index := sort.SearchInts(limits, d) if index < len(limits) && d == limits[index] { index++ } bins[index]++ } return bins } func printBins(limits, bins []int) { n := len(limits) fmt.Printf(" < %3d = %2d\n", limits[0], bins[0]) for i := 1; i < n; i++ { fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i]) } fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n]) fmt.Println() } func main() { limitsList := [][]int{ {23, 37, 43, 53, 67, 83}, {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}, } dataList := [][]int{ { 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55, }, { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749, }, } for i := 0; i < len(limitsList); i++ { fmt.Println("Example", i+1, "\b\n") bins := getBins(limitsList[i], dataList[i]) printBins(limitsList[i], bins) } }
Port the following code from C to Go with equivalent syntax and logic.
#include <SDL/SDL.h> #ifdef WITH_CAIRO #include <cairo.h> #else #include <SDL/sge.h> #endif #include <cairo.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifdef WITH_CAIRO #define PI 3.1415926535 #endif #define SIZE 800 #define SCALE 5 #define BRANCHES 14 #define ROTATION_SCALE 0.75 #define INITIAL_LENGTH 50 double rand_fl(){ return (double)rand() / (double)RAND_MAX; } void draw_tree(SDL_Surface * surface, double offsetx, double offsety, double directionx, double directiony, double size, double rotation, int depth) { #ifdef WITH_CAIRO cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels, CAIRO_FORMAT_RGB24, surface->w, surface->h, surface->pitch ); cairo_t *ct = cairo_create(surf); cairo_set_line_width(ct, 1); cairo_set_source_rgba(ct, 0,0,0,1); cairo_move_to(ct, (int)offsetx, (int)offsety); cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size)); cairo_stroke(ct); #else sge_AALine(surface, (int)offsetx, (int)offsety, (int)(offsetx + directionx * size), (int)(offsety + directiony * size), SDL_MapRGB(surface->format, 0, 0, 0)); #endif if (depth > 0){ draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(rotation) + directiony * sin(rotation), directionx * -sin(rotation) + directiony * cos(rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(-rotation) + directiony * sin(-rotation), directionx * -sin(-rotation) + directiony * cos(-rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); } } void render(SDL_Surface * surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); draw_tree(surface, surface->w / 2.0, surface->h - 10.0, 0.0, -1.0, INITIAL_LENGTH, PI / 8, BRANCHES); SDL_UpdateRect(surface, 0, 0, 0, 0); } int main(){ SDL_Surface * screen; SDL_Event evt; SDL_Init(SDL_INIT_VIDEO); srand((unsigned)time(NULL)); screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE); render(screen); while(1){ if (SDL_PollEvent(&evt)){ if(evt.type == SDL_QUIT) break; } SDL_Delay(1); } SDL_Quit(); return 0; }
package main import ( "math" "raster" ) const ( width = 400 height = 300 depth = 8 angle = 12 length = 50 frac = .8 ) func main() { g := raster.NewGrmap(width, height) ftree(g, width/2, height*9/10, length, 0, depth) g.Bitmap().WritePpmFile("ftree.ppm") } func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) { x2 := x + distance*math.Sin(direction*math.Pi/180) y2 := y - distance*math.Cos(direction*math.Pi/180) g.AaLine(x, y, x2, y2) if depth > 0 { ftree(g, x2, y2, distance*frac, direction-angle, depth-1) ftree(g, x2, y2, distance*frac, direction+angle, depth-1) } }
Convert this C block to Go, preserving its control flow and logic.
#include<graphics.h> #include<conio.h> #define sections 4 int main() { int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1; initgraph(&d,&m,"c:/turboc3/bgi"); maxX = getmaxx(); maxY = getmaxy(); for(y=0;y<maxY;y+=maxY/sections) { for(x=0;x<maxX;x+=increment) { setfillstyle(SOLID_FILL,(colour++)%16); bar(x,y,x+increment,y+maxY/sections); } increment++; colour = 0; } getch(); closegraph(); return 0; }
package main import "github.com/fogleman/gg" var palette = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 4 for b := 1; b <= 4; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { dc.SetHexColor(palette[ci%8]) y := h * (b - 1) dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h)) dc.Fill() } } } func main() { dc := gg.NewContext(900, 600) pinstripe(dc) dc.SavePNG("color_pinstripe.png") }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} func main() { dates := []string{ "1800-01-06", "1875-03-29", "1915-12-07", "1970-12-23", "2043-05-14", "2077-02-12", "2101-04-02", } fmt.Println("Days of week given by Doomsday rule:") for _, date := range dates { y, _ := strconv.Atoi(date[0:4]) m, _ := strconv.Atoi(date[5:7]) m-- d, _ := strconv.Atoi(date[8:10]) a := anchorDay(y) f := firstDaysCommon[m] if isLeapYear(y) { f = firstDaysLeap[m] } w := d - f if w < 0 { w = 7 + w } dow := (a + w) % 7 fmt.Printf("%s -> %s\n", date, days[dow]) } }
Produce a language-to-language conversion: from C to Go, same semantics.
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} func main() { dates := []string{ "1800-01-06", "1875-03-29", "1915-12-07", "1970-12-23", "2043-05-14", "2077-02-12", "2101-04-02", } fmt.Println("Days of week given by Doomsday rule:") for _, date := range dates { y, _ := strconv.Atoi(date[0:4]) m, _ := strconv.Atoi(date[5:7]) m-- d, _ := strconv.Atoi(date[8:10]) a := anchorDay(y) f := firstDaysCommon[m] if isLeapYear(y) { f = firstDaysLeap[m] } w := d - f if w < 0 { w = 7 + w } dow := (a + w) % 7 fmt.Printf("%s -> %s\n", date, days[dow]) } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <string.h> void swap(char* p1, char* p2, size_t size) { for (; size-- > 0; ++p1, ++p2) { char tmp = *p1; *p1 = *p2; *p2 = tmp; } } void cocktail_shaker_sort(void* base, size_t count, size_t size, int (*cmp)(const void*, const void*)) { char* begin = base; char* end = base + size * count; if (end == begin) return; for (end -= size; begin < end; ) { char* new_begin = end; char* new_end = begin; for (char* p = begin; p < end; p += size) { char* q = p + size; if (cmp(p, q) > 0) { swap(p, q, size); new_end = p; } } end = new_end; for (char* p = end; p > begin; p -= size) { char* q = p - size; if (cmp(q, p) > 0) { swap(p, q, size); new_begin = p; } } begin = new_begin; } } int string_compare(const void* p1, const void* p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } void print(const char** a, size_t len) { for (size_t i = 0; i < len; ++i) printf("%s ", a[i]); printf("\n"); } int main() { const char* a[] = { "one", "two", "three", "four", "five", "six", "seven", "eight" }; const size_t len = sizeof(a)/sizeof(a[0]); printf("before: "); print(a, len); cocktail_shaker_sort(a, len, sizeof(char*), string_compare); printf("after: "); print(a, len); return 0; }
package main import ( "fmt" "math/rand" "time" ) func cocktailShakerSort(a []int) { var begin = 0 var end = len(a) - 2 for begin <= end { newBegin := end newEnd := begin for i := begin; i <= end; i++ { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newEnd = i } } end = newEnd - 1 for i := end; i >= begin; i-- { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newBegin = i } } begin = newBegin + 1 } } func cocktailSort(a []int) { last := len(a) - 1 for { swapped := false for i := 0; i < last; i++ { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } swapped = false for i := last - 1; i >= 0; i-- { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } } } func main() { a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170} fmt.Println("Original array:", a) b := make([]int, len(a)) copy(b, a) cocktailSort(a) fmt.Println("Cocktail sort :", a) cocktailShakerSort(b) fmt.Println("C/Shaker sort :", b) rand.Seed(time.Now().UnixNano()) fmt.Println("\nRelative speed of the two sorts") fmt.Println(" N x faster (CSS v CS)") fmt.Println("----- -------------------") const runs = 10 for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} { sum := 0.0 for i := 1; i <= runs; i++ { nums := make([]int, n) for i := 0; i < n; i++ { rn := rand.Intn(100000) if i%2 == 1 { rn = -rn } nums[i] = rn } nums2 := make([]int, n) copy(nums2, nums) start := time.Now() cocktailSort(nums) elapsed := time.Since(start) start2 := time.Now() cocktailShakerSort(nums2) elapsed2 := time.Since(start2) sum += float64(elapsed) / float64(elapsed2) } fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs) } }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdlib.h> #include <math.h> #include <GL/glut.h> #include <GL/gl.h> #include <sys/time.h> #define length 5 #define g 9.8 double alpha, accl, omega = 0, E; struct timeval tv; double elappsed() { struct timeval now; gettimeofday(&now, 0); int ret = (now.tv_sec - tv.tv_sec) * 1000000 + now.tv_usec - tv.tv_usec; tv = now; return ret / 1.e6; } void resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); } void render() { double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha); resize(640, 320); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_LINES); glVertex2d(320, 0); glVertex2d(x, y); glEnd(); glFlush(); double us = elappsed(); alpha += (omega + us * accl / 2) * us; omega += accl * us; if (length * g * (1 - cos(alpha)) >= E) { alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g); omega = 0; } accl = -g / length * sin(alpha); } void init_gfx(int *c, char **v) { glutInit(c, v); glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(640, 320); glutIdleFunc(render); glutCreateWindow("Pendulum"); } int main(int c, char **v) { alpha = 4 * atan2(1, 1) / 2.1; E = length * g * (1 - cos(alpha)); accl = -g / length * sin(alpha); omega = 0; gettimeofday(&tv, 0); init_gfx(&c, v); glutMainLoop(); return 0; }
package main import ( "github.com/google/gxui" "github.com/google/gxui/drivers/gl" "github.com/google/gxui/math" "github.com/google/gxui/themes/dark" omath "math" "time" ) const ( ANIMATION_WIDTH int = 480 ANIMATION_HEIGHT int = 320 BALL_RADIUS float32 = 25.0 METER_PER_PIXEL float64 = 1.0 / 20.0 PHI_ZERO float64 = omath.Pi * 0.5 ) var ( l float64 = float64(ANIMATION_HEIGHT) * 0.5 freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL)) ) type Pendulum interface { GetPhi() float64 } type mathematicalPendulum struct { start time.Time } func (p *mathematicalPendulum) GetPhi() float64 { if (p.start == time.Time{}) { p.start = time.Now() } t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9) return PHI_ZERO * omath.Cos(t*freq) } type numericalPendulum struct { currentPhi float64 angAcc float64 angVel float64 lastTime time.Time } func (p *numericalPendulum) GetPhi() float64 { dt := 0.0 if (p.lastTime != time.Time{}) { dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9) } p.lastTime = time.Now() p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi) p.angVel += p.angAcc * dt p.currentPhi += p.angVel * dt return p.currentPhi } func draw(p Pendulum, canvas gxui.Canvas, x, y int) { attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y} phi := p.GetPhi() ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))} line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}} canvas.DrawLines(line, gxui.DefaultPen) m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)} rect := math.Rect{ball.Sub(m), ball.Add(m)} canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow)) } func appMain(driver gxui.Driver) { theme := dark.CreateTheme(driver) window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum") window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50)) image := theme.CreateImage() ticker := time.NewTicker(time.Millisecond * 15) pendulum := &mathematicalPendulum{} pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}} go func() { for _ = range ticker.C { canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT}) canvas.Clear(gxui.White) draw(pendulum, canvas, 0, 0) draw(pendulum2, canvas, 0, ANIMATION_HEIGHT) canvas.Complete() driver.Call(func() { image.SetCanvas(canvas) }) } }() window.AddChild(image) window.OnClose(ticker.Stop) window.OnClose(driver.Terminate) } func main() { gl.StartDriver(appMain) }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
Write a version of this C function in Go with identical behavior.
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
Convert this C snippet to Go and keep its semantics consistent.
#include<stdio.h> int main() { FILE* fp = fopen("TAPE.FILE","w"); fprintf(fp,"This code should be able to write a file to magnetic tape.\n"); fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n"); fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n"); fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n"); fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n"); fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n"); fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n"); fprintf(fp,"EOF"); fclose(fp); return 0; }
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)") gzipFlag := flag.Bool("gzip", false, "use gzip compression") flag.Parse() var w io.Writer = os.Stdout if *outfile != "" { f, err := os.Create(*outfile) if err != nil { log.Fatalf("opening/creating %q: %v", *outfile, err) } defer f.Close() w = f } if *gzipFlag { zw := gzip.NewWriter(w) defer zw.Close() w = zw } tw := tar.NewWriter(w) defer tw.Close() w = tw tw.WriteHeader(&tar.Header{ Name: *filename, Mode: 0660, Size: int64(len(*data)), ModTime: time.Now(), Typeflag: tar.TypeReg, Uname: "guest", Gname: "guest", }) _, err := w.Write([]byte(*data)) if err != nil { log.Fatal("writing data:", err) } }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> int max (int *a, int n, int i, int j, int k) { int m = i; if (j < n && a[j] > a[m]) { m = j; } if (k < n && a[k] > a[m]) { m = k; } return m; } void downheap (int *a, int n, int i) { while (1) { int j = max(a, n, i, 2 * i + 1, 2 * i + 2); if (j == i) { break; } int t = a[i]; a[i] = a[j]; a[j] = t; i = j; } } void heapsort (int *a, int n) { int i; for (i = (n - 2) / 2; i >= 0; i--) { downheap(a, n, i); } for (i = 0; i < n; i++) { int t = a[n - i - 1]; a[n - i - 1] = a[0]; a[0] = t; downheap(a, n - i - 1, 0); } } 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" : " "); heapsort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
package main import ( "sort" "container/heap" "fmt" ) type HeapHelper struct { container sort.Interface length int } func (self HeapHelper) Len() int { return self.length } func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) } func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) } func (self *HeapHelper) Push(x interface{}) { panic("impossible") } func (self *HeapHelper) Pop() interface{} { self.length-- return nil } func heapSort(a sort.Interface) { helper := HeapHelper{ a, a.Len() } heap.Init(&helper) for helper.length > 0 { heap.Pop(&helper) } } func main() { a := []int{170, 45, 75, -90, -802, 24, 2, 66} fmt.Println("before:", a) heapSort(sort.IntSlice(a)) fmt.Println("after: ", a) }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #include <locale.h> int locale_ok = 0; wchar_t s_suits[] = L"♠♥♦♣"; const char *s_suits_ascii[] = { "S", "H", "D", "C" }; const char *s_nums[] = { "WHAT", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "OVERFLOW" }; typedef struct { int suit, number, _s; } card_t, *card; typedef struct { int n; card_t cards[52]; } deck_t, *deck; void show_card(card c) { if (locale_ok) printf(" %lc%s", s_suits[c->suit], s_nums[c->number]); else printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]); } deck new_deck() { int i, j, k; deck d = malloc(sizeof(deck_t)); d->n = 52; for (i = k = 0; i < 4; i++) for (j = 1; j <= 13; j++, k++) { d->cards[k].suit = i; d->cards[k].number = j; } return d; } void show_deck(deck d) { int i; printf("%d cards:", d->n); for (i = 0; i < d->n; i++) show_card(d->cards + i); printf("\n"); } int cmp_card(const void *a, const void *b) { int x = ((card)a)->_s, y = ((card)b)->_s; return x < y ? -1 : x > y; } card deal_card(deck d) { if (!d->n) return 0; return d->cards + --d->n; } void shuffle_deck(deck d) { int i; for (i = 0; i < d->n; i++) d->cards[i]._s = rand(); qsort(d->cards, d->n, sizeof(card_t), cmp_card); } int main() { int i, j; deck d = new_deck(); locale_ok = (0 != setlocale(LC_CTYPE, "")); printf("New deck, "); show_deck(d); printf("\nShuffle and deal to three players:\n"); shuffle_deck(d); for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) show_card(deal_card(d)); printf("\n"); } printf("Left in deck "); show_deck(d); return 0; }
package cards import ( "math/rand" ) type Suit uint8 const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 ) func (s Suit) String() string { const suites = "CDHS" return suites[s : s+1] } type Rank uint8 const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Five Rank = 5 Six Rank = 6 Seven Rank = 7 Eight Rank = 8 Nine Rank = 9 Ten Rank = 10 Jack Rank = 11 Queen Rank = 12 King Rank = 13 ) func (r Rank) String() string { const ranks = "A23456789TJQK" return ranks[r-1 : r] } type Card uint8 func NewCard(r Rank, s Suit) Card { return Card(13*uint8(s) + uint8(r-1)) } func (c Card) RankSuit() (Rank, Suit) { return Rank(c%13 + 1), Suit(c / 13) } func (c Card) Rank() Rank { return Rank(c%13 + 1) } func (c Card) Suit() Suit { return Suit(c / 13) } func (c Card) String() string { return c.Rank().String() + c.Suit().String() } type Deck []Card func NewDeck() Deck { d := make(Deck, 52) for i := range d { d[i] = Card(i) } return d } func (d Deck) String() string { s := "" for i, c := range d { switch { case i == 0: case i%13 == 0: s += "\n" default: s += " " } s += c.String() } return s } func (d Deck) Shuffle() { for i := range d { j := rand.Intn(i + 1) d[i], d[j] = d[j], d[i] } } func (d Deck) Contains(tc Card) bool { for _, c := range d { if c == tc { return true } } return false } func (d *Deck) AddDeck(decks ...Deck) { for _, o := range decks { *d = append(*d, o...) } } func (d *Deck) AddCard(c Card) { *d = append(*d, c) } func (d *Deck) Draw(n int) Deck { old := *d *d = old[n:] return old[:n:n] } func (d *Deck) DrawCard() (Card, bool) { if len(*d) == 0 { return 0, false } old := *d *d = old[1:] return old[0], true } func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) { for i := 0; i < cards; i++ { for j := range hands { if len(*d) == 0 { return hands, false } hands[j] = append(hands[j], (*d)[0]) *d = (*d)[1:] } } return hands, true }
Preserve the algorithm and functionality while converting the code from C to Go.
char foo() { char array[5] = {3,6,9,12,15}; return array[2]; }
package main import ( "fmt" ) func main() { var a [5]int fmt.Println("len(a) =", len(a)) fmt.Println("a =", a) a[0] = 3 fmt.Println("a =", a) fmt.Println("a[0] =", a[0]) s := a[:4] fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) s = s[:5] fmt.Println("s =", s) a[0] = 22 fmt.Println("a =", a) fmt.Println("s =", s) s = append(s, 4, 5, 6) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) a[4] = -1 fmt.Println("a =", a) fmt.Println("s =", s) s = make([]int, 8) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> int main() { int i, j, dim, d; int depth = 3; for (i = 0, dim = 1; i < depth; i++, dim *= 3); for (i = 0; i < dim; i++) { for (j = 0; j < dim; j++) { for (d = dim / 3; d; d /= 3) if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1) break; printf(d ? " " : "##"); } printf("\n"); } return 0; }
package main import ( "fmt" "strings" "unicode/utf8" ) var order = 3 var grain = "#" func main() { carpet := []string{grain} for ; order > 0; order-- { hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0])) middle := make([]string, len(carpet)) for i, s := range carpet { middle[i] = s + hole + s carpet[i] = strings.Repeat(s, 3) } carpet = append(append(carpet, middle...), carpet...) } for _, r := range carpet { fmt.Println(r) } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> bool is_sorted(int *a, int n) { while ( --n >= 1 ) { if ( a[n] < a[n-1] ) return false; } return true; } void shuffle(int *a, int n) { int i, t, r; for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } } void bogosort(int *a, int n) { while ( !is_sorted(a, n) ) shuffle(a, n); } int main() { int numbers[] = { 1, 10, 9, 7, 3, 0 }; int i; bogosort(numbers, 6); for (i=0; i < 6; i++) printf("%d ", numbers[i]); printf("\n"); }
package main import ( "fmt" "math/rand" "sort" "time" ) func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} rand.Seed(time.Now().UnixNano()) fmt.Println("unsorted:", list) temp := make([]int, len(list)) copy(temp, list) for !sort.IntsAreSorted(temp) { for i, v := range rand.Perm(len(list)) { temp[i] = list[v] } } fmt.Println("sorted! ", temp) }
Write the same code in Go as shown below in C.
#include <ctime> #include <cstdint> extern "C" { int64_t from date(const char* string) { struct tm tmInfo = {0}; strptime(string, "%Y-%m-%d", &tmInfo); return mktime(&tmInfo); } }
package main import ( "fmt" "math" "sort" ) type Patient struct { id int lastName string } var patientDir = make(map[int]string) var patientIds []int func patientNew(id int, lastName string) Patient { patientDir[id] = lastName patientIds = append(patientIds, id) sort.Ints(patientIds) return Patient{id, lastName} } type DS struct { dates []string scores []float64 } type Visit struct { id int date string score float64 } var visitDir = make(map[int]DS) func visitNew(id int, date string, score float64) Visit { if date == "" { date = "0000-00-00" } v, ok := visitDir[id] if ok { v.dates = append(v.dates, date) v.scores = append(v.scores, score) visitDir[id] = DS{v.dates, v.scores} } else { visitDir[id] = DS{[]string{date}, []float64{score}} } return Visit{id, date, score} } type Merge struct{ id int } func (m Merge) lastName() string { return patientDir[m.id] } func (m Merge) dates() []string { return visitDir[m.id].dates } func (m Merge) scores() []float64 { return visitDir[m.id].scores } func (m Merge) lastVisit() string { dates := m.dates() dates2 := make([]string, len(dates)) copy(dates2, dates) sort.Strings(dates2) return dates2[len(dates2)-1] } func (m Merge) scoreSum() float64 { sum := 0.0 for _, score := range m.scores() { if score != -1 { sum += score } } return sum } func (m Merge) scoreAvg() float64 { count := 0 for _, score := range m.scores() { if score != -1 { count++ } } return m.scoreSum() / float64(count) } func mergePrint(merges []Merge) { fmt.Println("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |") f := "| %d | %-7s | %s | %4s | %4s |\n" for _, m := range merges { _, ok := visitDir[m.id] if ok { lv := m.lastVisit() if lv == "0000-00-00" { lv = " " } scoreSum := m.scoreSum() ss := fmt.Sprintf("%4.1f", scoreSum) if scoreSum == 0 { ss = " " } scoreAvg := m.scoreAvg() sa := " " if !math.IsNaN(scoreAvg) { sa = fmt.Sprintf("%4.2f", scoreAvg) } fmt.Printf(f, m.id, m.lastName(), lv, ss, sa) } else { fmt.Printf(f, m.id, m.lastName(), " ", " ", " ") } } } func main() { patientNew(1001, "Hopper") patientNew(4004, "Wirth") patientNew(3003, "Kemeny") patientNew(2002, "Gosling") patientNew(5005, "Kurtz") visitNew(2002, "2020-09-10", 6.8) visitNew(1001, "2020-09-17", 5.5) visitNew(4004, "2020-09-24", 8.4) visitNew(2002, "2020-10-08", -1) visitNew(1001, "", 6.6) visitNew(3003, "2020-11-12", -1) visitNew(4004, "2020-11-05", 7.0) visitNew(1001, "2020-11-19", 5.3) merges := make([]Merge, len(patientIds)) for i, id := range patientIds { merges[i] = Merge{id} } mergePrint(merges) }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <math.h> typedef double (*deriv_f)(double, double); #define FMT " %7.3f" void ivp_euler(deriv_f f, double y, int step, int end_t) { int t = 0; printf(" Step %2d: ", (int)step); do { if (t % 10 == 0) printf(FMT, y); y += step * f(t, y); } while ((t += step) <= end_t); printf("\n"); } void analytic() { double t; printf(" Time: "); for (t = 0; t <= 100; t += 10) printf(" %7g", t); printf("\nAnalytic: "); for (t = 0; t <= 100; t += 10) printf(FMT, 20 + 80 * exp(-0.07 * t)); printf("\n"); } double cooling(double t, double temp) { return -0.07 * (temp - 20); } int main() { analytic(); ivp_euler(cooling, 100, 2, 100); ivp_euler(cooling, 100, 5, 100); ivp_euler(cooling, 100, 10, 100); return 0; }
package main import ( "fmt" "math" ) type fdy func(float64, float64) float64 func eulerStep(f fdy, x, y, h float64) float64 { return y + h*f(x, y) } func newCoolingRate(k float64) func(float64) float64 { return func(deltaTemp float64) float64 { return -k * deltaTemp } } func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 { return func(time float64) float64 { return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time) } } func newCoolingRateDy(k, ambientTemp float64) fdy { crf := newCoolingRate(k) return func(_, objectTemp float64) float64 { return crf(objectTemp - ambientTemp) } } func main() { k := .07 tempRoom := 20. tempObject := 100. fcr := newCoolingRateDy(k, tempRoom) analytic := newTempFunc(k, tempRoom, tempObject) for _, deltaTime := range []float64{2, 5, 10} { fmt.Printf("Step size = %.1f\n", deltaTime) fmt.Println(" Time Euler's Analytic") temp := tempObject for time := 0.; time <= 100; time += deltaTime { fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time)) temp = eulerStep(fcr, time, temp, deltaTime) } fmt.Println() } }
Write a version of this C function in Go with identical behavior.
#include <math.h> #include <stdio.h> #include <assert.h> int nonsqr(int n) { return n + (int)(0.5 + sqrt(n)); } int main() { int i; for (i = 1; i < 23; i++) printf("%d ", nonsqr(i)); printf("\n"); for (i = 1; i < 1000000; i++) { double j = sqrt(nonsqr(i)); assert(j != floor(j)); } return 0; }
package main import ( "fmt" "math" ) func remarkable(n int) int { return n + int(.5+math.Sqrt(float64(n))) } func main() { fmt.Println(" n r(n)") fmt.Println("--- ---") for n := 1; n <= 22; n++ { fmt.Printf("%3d %3d\n", n, remarkable(n)) } const limit = 1e6 fmt.Println("\nChecking for squares for n <", limit) next := 2 nextSq := 4 for n := 1; n < limit; n++ { r := remarkable(n) switch { case r == nextSq: panic(n) case r > nextSq: fmt.Println(nextSq, "didn't occur") next++ nextSq = next * next } } fmt.Println("No squares occur for n <", limit) }
Ensure the translated Go code behaves exactly like the original C snippet.
#include <math.h> #include <stdio.h> #include <assert.h> int nonsqr(int n) { return n + (int)(0.5 + sqrt(n)); } int main() { int i; for (i = 1; i < 23; i++) printf("%d ", nonsqr(i)); printf("\n"); for (i = 1; i < 1000000; i++) { double j = sqrt(nonsqr(i)); assert(j != floor(j)); } return 0; }
package main import ( "fmt" "math" ) func remarkable(n int) int { return n + int(.5+math.Sqrt(float64(n))) } func main() { fmt.Println(" n r(n)") fmt.Println("--- ---") for n := 1; n <= 22; n++ { fmt.Printf("%3d %3d\n", n, remarkable(n)) } const limit = 1e6 fmt.Println("\nChecking for squares for n <", limit) next := 2 nextSq := 4 for n := 1; n < limit; n++ { r := remarkable(n) switch { case r == nextSq: panic(n) case r > nextSq: fmt.Println(nextSq, "didn't occur") next++ nextSq = next * next } } fmt.Println("No squares occur for n <", limit) }
Write the same algorithm in Go as shown in this C implementation.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); } int main(void) { char string[] = "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)." int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = "encodings"; putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n'); return EXIT_SUCCESS; }
package main import ( "fmt" "strings" ) func main() { s := "ABCDEFGH" n, m := 2, 3 fmt.Println("Index: ", "01234567") fmt.Println("String:", s) fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m]) fmt.Printf("Start %d, to end: %s\n", n, s[n:]) fmt.Printf("All but last: %s\n", s[:len(s)-1]) dx := strings.IndexByte(s, 'D') fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m]) sx := strings.Index(s, "DE") fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m]) }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> int number_of_digits(int x){ int NumberOfDigits; for(NumberOfDigits=0;x!=0;NumberOfDigits++){ x=x/10; } return NumberOfDigits; } int* convert_array(char array[], int NumberOfElements) { int *convertedArray=malloc(NumberOfElements*sizeof(int)); int originalElement, convertedElement; for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++) { convertedArray[convertedElement]=atoi(&array[originalElement]); originalElement+=number_of_digits(convertedArray[convertedElement])+1; } return convertedArray; } int isSorted(int array[], int numberOfElements){ int sorted=1; for(int counter=0;counter<numberOfElements;counter++){ if(counter!=0 && array[counter-1]>array[counter]) sorted--; } return sorted; } int main(int argc, char* argv[]) { int* convertedArray; convertedArray=convert_array(*(argv+1), argc-1); if(isSorted(convertedArray, argc-1)==1) printf("Did you forgot to turn on your brain?! This array is already sorted!\n"); else if(argc-1<=10) printf("Am I really supposed to sort this? Sort it by yourself!\n"); else printf("Am I really supposed to sort this? Bhahahaha!\n"); free(convertedArray); return 0; }
package main import ( "log" "sort" ) func main() { log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) log.Println(jortSort([]int{0, 1, 0, 0, 0, 0})) log.Println(jortSort([]int{1, 2, 4, 11, 22, 22})) log.Println(jortSort([]int{0, 0, 0, 1, 2, 2})) } func jortSort(a []int) bool { c := make([]int, len(a)) copy(c, a) sort.Ints(a) for k, v := range c { if v == a[k] { continue } else { return false } } return true }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> int is_leap_year(unsigned year) { return !(year & (year % 100 ? 3 : 15)); } int main(void) { const unsigned test_case[] = { 1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100 }; const unsigned n = sizeof test_case / sizeof test_case[0]; for (unsigned i = 0; i != n; ++i) { unsigned year = test_case[i]; printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not "); } return 0; }
func isLeap(year int) bool { return year%400 == 0 || year%4 == 0 && year%100 != 0 }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <gmp.h> void perm(mpz_t out, int n, int k) { mpz_set_ui(out, 1); k = n - k; while (n > k) mpz_mul_ui(out, out, n--); } void comb(mpz_t out, int n, int k) { perm(out, n, k); while (k) mpz_divexact_ui(out, out, k--); } int main(void) { mpz_t x; mpz_init(x); perm(x, 1000, 969); gmp_printf("P(1000,969) = %Zd\n", x); comb(x, 1000, 969); gmp_printf("C(1000,969) = %Zd\n", x); return 0; }
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n < 61; n += 10 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of permutations from 5 to 15000:\n") nArr := [...]int64{5, 50, 500, 1000, 5000, 15000} for _, n = range nArr { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 100 to 1000:\n") for n = 100; n < 1001; n += 100 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } } func fact(n *big.Int) *big.Int { if n.Sign() < 1 { return big.NewInt(0) } r := big.NewInt(1) i := big.NewInt(2) for i.Cmp(n) < 1 { r.Mul(r, i) i.Add(i, big.NewInt(1)) } return r } func perm(n, k *big.Int) *big.Int { r := fact(n) r.Div(r, fact(n.Sub(n, k))) return r } func comb(n, r *big.Int) *big.Int { if r.Cmp(n) == 1 { return big.NewInt(0) } if r.Cmp(n) == 0 { return big.NewInt(1) } c := fact(n) den := fact(n.Sub(n, r)) den.Mul(den, fact(r)) c.Div(c, den) return c }
Ensure the translated Go code behaves exactly like the original C snippet.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int compareStrings(const void *a, const void *b) { const char **aa = (const char **)a; const char **bb = (const char **)b; return strcmp(*aa, *bb); } void lexOrder(int n, int *ints) { char **strs; int i, first = 1, last = n, k = n, len; if (n < 1) { first = n; last = 1; k = 2 - n; } strs = malloc(k * sizeof(char *)); for (i = first; i <= last; ++i) { if (i >= 1) len = (int)log10(i) + 2; else if (i == 0) len = 2; else len = (int)log10(-i) + 3; strs[i-first] = malloc(len); sprintf(strs[i-first], "%d", i); } qsort(strs, k, sizeof(char *), compareStrings); for (i = 0; i < k; ++i) { ints[i] = atoi(strs[i]); free(strs[i]); } free(strs); } int main() { int i, j, k, n, *ints; int numbers[5] = {0, 5, 13, 21, -22}; printf("In lexicographical order:\n\n"); for (i = 0; i < 5; ++i) { k = n = numbers[i]; if (k < 1) k = 2 - k; ints = malloc(k * sizeof(int)); lexOrder(n, ints); printf("%3d: [", n); for (j = 0; j < k; ++j) { printf("%d ", ints[j]); } printf("\b]\n"); free(ints); } return 0; }
package main import ( "fmt" "sort" "strconv" ) func lexOrder(n int) []int { first, last, k := 1, n, n if n < 1 { first, last, k = n, 1, 2-n } strs := make([]string, k) for i := first; i <= last; i++ { strs[i-first] = strconv.Itoa(i) } sort.Strings(strs) ints := make([]int, k) for i := 0; i < k; i++ { ints[i], _ = strconv.Atoi(strs[i]) } return ints } func main() { fmt.Println("In lexicographical order:\n") for _, n := range []int{0, 5, 13, 21, -22} { fmt.Printf("%3d: %v\n", n, lexOrder(n)) } }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> #include <string.h> const char *ones[] = { 0, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char *tens[] = { 0, "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const char *llions[] = { 0, "thousand", "million", "billion", "trillion", }; const int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3; int say_hundred(const char *s, int len, int depth, int has_lead) { int c[3], i; for (i = -3; i < 0; i++) { if (len + i >= 0) c[i + 3] = s[len + i] - '0'; else c[i + 3] = 0; } if (!(c[0] + c[1] + c[2])) return 0; if (c[0]) { printf("%s hundred", ones[c[0]]); has_lead = 1; } if (has_lead && (c[1] || c[2])) printf((!depth || c[0]) && (!c[0] || !c[1]) ? "and " : c[0] ? " " : ""); if (c[1] < 2) { if (c[1] || c[2]) printf("%s", ones[c[1] * 10 + c[2]]); } else { if (c[1]) { printf("%s", tens[c[1]]); if (c[2]) putchar('-'); } if (c[2]) printf("%s", ones[c[2]]); } return 1; } int say_maxillion(const char *s, int len, int depth, int has_lead) { int n = len / 3, r = len % 3; if (!r) { n--; r = 3; } const char *e = s + r; do { if (say_hundred(s, r, n, has_lead) && n) { has_lead = 1; printf(" %s", llions[n]); if (!depth) printf(", "); else printf(" "); } s = e; e += 3; } while (r = 3, n--); return 1; } void say_number(const char *s) { int len, i, got_sign = 0; while (*s == ' ') s++; if (*s < '0' || *s > '9') { if (*s == '-') got_sign = -1; else if (*s == '+') got_sign = 1; else goto nan; s++; } else got_sign = 1; while (*s == '0') { s++; if (*s == '\0') { printf("zero\n"); return; } } len = strlen(s); if (!len) goto nan; for (i = 0; i < len; i++) { if (s[i] < '0' || s[i] > '9') { printf("(not a number)"); return; } } if (got_sign == -1) printf("minus "); int n = len / maxillion; int r = len % maxillion; if (!r) { r = maxillion; n--; } const char *end = s + len - n * maxillion; int has_lead = 0; do { if ((has_lead = say_maxillion(s, r, n, has_lead))) { for (i = 0; i < n; i++) printf(" %s", llions[maxillion / 3]); if (n) printf(", "); } n--; r = maxillion; s = end; end += r; } while (n >= 0); printf("\n"); return; nan: printf("not a number\n"); return; } int main() { say_number("-42"); say_number("1984"); say_number("10000"); say_number("1024"); say_number("1001001001001"); say_number("123456789012345678901234567890123456789012345678900000001"); return 0; }
package main import "fmt" func main() { for _, n := range []int64{12, 1048576, 9e18, -2, 0} { fmt.Println(say(n)) } } var small = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} var tens = [...]string{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} var illions = [...]string{"", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"} func say(n int64) string { var t string if n < 0 { t = "negative " n = -n } switch { case n < 20: t += small[n] case n < 100: t += tens[n/10] s := n % 10 if s > 0 { t += "-" + small[s] } case n < 1000: t += small[n/100] + " hundred" s := n % 100 if s > 0 { t += " " + say(s) } default: sx := "" for i := 0; n > 0; i++ { p := n % 1000 n /= 1000 if p > 0 { ix := say(p) + illions[i] if sx != "" { ix += " " + sx } sx = ix } } t += sx } return t }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const int* a, const int* b) { return *b - *a; } void compareAndReportStringsLength(const char* strings[], const int n) { if (n > 0) { char* has_length = "has length"; char* predicate_max = "and is the longest string"; char* predicate_min = "and is the shortest string"; char* predicate_ave = "and is neither the longest nor the shortest string"; int* si = malloc(2 * n * sizeof(int)); if (si != NULL) { for (int i = 0; i < n; i++) { si[2 * i] = strlen(strings[i]); si[2 * i + 1] = i; } qsort(si, n, 2 * sizeof(int), cmp); int max = si[0]; int min = si[2 * (n - 1)]; for (int i = 0; i < n; i++) { int length = si[2 * i]; char* string = strings[si[2 * i + 1]]; char* predicate; if (length == max) predicate = predicate_max; else if (length == min) predicate = predicate_min; else predicate = predicate_ave; printf("\"%s\" %s %d %s\n", string, has_length, length, predicate); } free(si); } else { fputs("unable allocate memory buffer", stderr); } } } int main(int argc, char* argv[]) { char* list[] = { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(list, 4); return EXIT_SUCCESS; }
package main import ( "fmt" "os" "sort" ) func main() { if len(os.Args) == 1 { compareStrings("abcd", "123456789", "abcdef", "1234567") } else { strings := os.Args[1:] compareStrings(strings...) } } func compareStrings(strings ...string) { sort.SliceStable(strings, func(i, j int) bool { return len(strings[i]) > len(strings[j]) }) for _, s := range strings { fmt.Printf("%d: %s\n", len(s), s) } }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> void shell_sort (int *a, int n) { int h, i, j, t; for (h = n; h /= 2;) { for (i = h; i < n; i++) { t = a[i]; for (j = i; j >= h && t < a[j - h]; j -= h) { a[j] = a[j - h]; } a[j] = t; } } } int main (int ac, char **av) { 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" : " "); shell_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) for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { for i := inc; i < len(a); i++ { j, temp := i, a[i] for ; j >= inc && a[j-inc] > temp; j -= inc { a[j] = a[j-inc] } a[j] = temp } } fmt.Println("after: ", a) }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdlib.h> struct List { struct MNode *head; struct MNode *tail; struct MNode *tail_pred; }; struct MNode { struct MNode *succ; struct MNode *pred; }; typedef struct MNode *NODE; typedef struct List *LIST; LIST newList(void); int isEmpty(LIST); NODE getTail(LIST); NODE getHead(LIST); NODE addTail(LIST, NODE); NODE addHead(LIST, NODE); NODE remHead(LIST); NODE remTail(LIST); NODE insertAfter(LIST, NODE, NODE); NODE removeNode(LIST, NODE); LIST newList(void) { LIST tl = malloc(sizeof(struct List)); if ( tl != NULL ) { tl->tail_pred = (NODE)&tl->head; tl->tail = NULL; tl->head = (NODE)&tl->tail; return tl; } return NULL; } int isEmpty(LIST l) { return (l->head->succ == 0); } NODE getHead(LIST l) { return l->head; } NODE getTail(LIST l) { return l->tail_pred; } NODE addTail(LIST l, NODE n) { n->succ = (NODE)&l->tail; n->pred = l->tail_pred; l->tail_pred->succ = n; l->tail_pred = n; return n; } NODE addHead(LIST l, NODE n) { n->succ = l->head; n->pred = (NODE)&l->head; l->head->pred = n; l->head = n; return n; } NODE remHead(LIST l) { NODE h; h = l->head; l->head = l->head->succ; l->head->pred = (NODE)&l->head; return h; } NODE remTail(LIST l) { NODE t; t = l->tail_pred; l->tail_pred = l->tail_pred->pred; l->tail_pred->succ = (NODE)&l->tail; return t; } NODE insertAfter(LIST l, NODE r, NODE n) { n->pred = r; n->succ = r->succ; n->succ->pred = n; r->succ = n; return n; } NODE removeNode(LIST l, NODE n) { n->pred->succ = n->succ; n->succ->pred = n->pred; return n; }
type dlNode struct { int next, prev *dlNode } type dlList struct { members map[*dlNode]int head, tail **dlNode }
Port the following code from C to Go with equivalent syntax and logic.
int frequency[26]; int ch; FILE* txt_file = fopen ("a_text_file.txt", "rt"); for (ch = 0; ch < 26; ch++) frequency[ch] = 0; while (1) { ch = fgetc(txt_file); if (ch == EOF) break; if ('a' <= ch && ch <= 'z') frequency[ch-'a']++; else if ('A' <= ch && ch <= 'Z') frequency[ch-'A']++; }
package main import ( "fmt" "io/ioutil" "sort" "unicode" ) const file = "unixdict.txt" func main() { bs, err := ioutil.ReadFile(file) if err != nil { fmt.Println(err) return } m := make(map[rune]int) for _, r := range string(bs) { m[r]++ } lfs := make(lfList, 0, len(m)) for l, f := range m { lfs = append(lfs, &letterFreq{l, f}) } sort.Sort(lfs) fmt.Println("file:", file) fmt.Println("letter frequency") for _, lf := range lfs { if unicode.IsGraphic(lf.rune) { fmt.Printf(" %c %7d\n", lf.rune, lf.freq) } else { fmt.Printf("%U %7d\n", lf.rune, lf.freq) } } } type letterFreq struct { rune freq int } type lfList []*letterFreq func (lfs lfList) Len() int { return len(lfs) } func (lfs lfList) Less(i, j int) bool { switch fd := lfs[i].freq - lfs[j].freq; { case fd < 0: return false case fd > 0: return true } return lfs[i].rune < lfs[j].rune } func (lfs lfList) Swap(i, j int) { lfs[i], lfs[j] = lfs[j], lfs[i] }
Ensure the translated Go code behaves exactly like the original C snippet.
#include <stdio.h> int data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 }; int pick(int at, int remain, int accu, int treat) { if (!remain) return (accu > treat) ? 1 : 0; return pick(at - 1, remain - 1, accu + data[at - 1], treat) + ( at > remain ? pick(at - 1, remain, accu, treat) : 0 ); } int main() { int treat = 0, i; int le, gt; double total = 1; for (i = 0; i < 9; i++) treat += data[i]; for (i = 19; i > 10; i--) total *= i; for (i = 9; i > 0; i--) total /= i; gt = pick(19, 9, 0, treat); le = total - gt; printf("<= : %f%% %d\n > : %f%% %d\n", 100 * le / total, le, 100 * gt / total, gt); return 0; }
package main import "fmt" var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97} var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98} func main() { all := make([]int, len(tr)+len(ct)) copy(all, tr) copy(all[len(tr):], ct) var sumAll int for _, r := range all { sumAll += r } sd := func(trc []int) int { var sumTr int for _, x := range trc { sumTr += all[x] } return sumTr*len(ct) - (sumAll-sumTr)*len(tr) } a := make([]int, len(tr)) for i, _ := range a { a[i] = i } sdObs := sd(a) var nLe, nGt int comb(len(all), len(tr), func(c []int) { if sd(c) > sdObs { nGt++ } else { nLe++ } }) pc := 100 / float64(nLe+nGt) fmt.Printf("differences <= observed: %f%%\n", float64(nLe)*pc) fmt.Printf("differences > observed: %f%%\n", float64(nGt)*pc) } func comb(n, m int, emit func([]int)) { s := make([]int, m) last := m - 1 var rc func(int, int) rc = func(i, next int) { for j := next; j < n; j++ { s[i] = j if i == last { emit(s) } else { rc(i+1, j+1) } } return } rc(0, 0) }
Port the following code from C to Go with equivalent syntax and logic.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { const int MU_MAX = 1000000; int i, j; int *mu; int sqroot; sqroot = (int)sqrt(MU_MAX); mu = malloc((MU_MAX + 1) * sizeof(int)); for (i = 0; i < MU_MAX;i++) { mu[i] = 1; } for (i = 2; i <= sqroot; i++) { if (mu[i] == 1) { for (j = i; j <= MU_MAX; j += i) { mu[j] *= -i; } for (j = i * i; j <= MU_MAX; j += i * i) { mu[j] = 0; } } } for (i = 2; i <= MU_MAX; i++) { if (mu[i] == i) { mu[i] = 1; } else if (mu[i] == -i) { mu[i] = -1; } else if (mu[i] < 0) { mu[i] = 1; } else if (mu[i] > 0) { mu[i] = -1; } } printf("First 199 terms of the möbius function are as follows:\n "); for (i = 1; i < 200; i++) { printf("%2d ", mu[i]); if ((i + 1) % 20 == 0) { printf("\n"); } } free(mu); return 0; }
package main import "fmt" func möbius(to int) []int { if to < 1 { to = 1 } mobs := make([]int, to+1) primes := []int{2} for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break } if j%p == 0 { j /= p cp++ } if j%p == 0 { spf = true break } } if cp == 0 && i > 2 { cp = 1 primes = append(primes, i) } if !spf { if cp%2 == 0 { mobs[i] = 1 } else { mobs[i] = -1 } } } return mobs } func main() { mobs := möbius(199) fmt.Println("Möbius sequence - First 199 terms:") for i := 0; i < 200; i++ { if i == 0 { fmt.Print(" ") continue } if i%20 == 0 { fmt.Println() } fmt.Printf("  % d", mobs[i]) } }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <string.h> #include <stdlib.h> char * incr(char *s) { int i, begin, tail, len; int neg = (*s == '-'); char tgt = neg ? '0' : '9'; if (!strcmp(s, "-1")) { s[0] = '0', s[1] = '\0'; return s; } len = strlen(s); begin = (*s == '-' || *s == '+') ? 1 : 0; for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--); if (tail < begin && !neg) { if (!begin) s = realloc(s, len + 2); s[0] = '1'; for (i = 1; i <= len - begin; i++) s[i] = '0'; s[len + 1] = '\0'; } else if (tail == begin && neg && s[1] == '1') { for (i = 1; i < len - begin; i++) s[i] = '9'; s[len - 1] = '\0'; } else { for (i = len - 1; i > tail; i--) s[i] = neg ? '9' : '0'; s[tail] += neg ? -1 : 1; } return s; } void string_test(const char *s) { char *ret = malloc(strlen(s)); strcpy(ret, s); printf("text: %s\n", ret); printf(" ->: %s\n", ret = incr(ret)); free(ret); } int main() { string_test("+0"); string_test("-1"); string_test("-41"); string_test("+41"); string_test("999"); string_test("+999"); string_test("109999999999999999999999999999999999999999"); string_test("-100000000000000000000000000000000000000000000"); return 0; }
package main import "fmt" import "strconv" func main() { i, _ := strconv.Atoi("1234") fmt.Println(strconv.Itoa(i + 1)) }
Convert the following code from C to Go, ensuring the logic remains intact.
#include <string.h> #include <stdio.h> #include <stdlib.h> char *strip_chars(const char *string, const char *chars) { char * newstr = malloc(strlen(string) + 1); int counter = 0; for ( ; *string; string++) { if (!strchr(chars, *string)) { newstr[ counter ] = *string; ++ counter; } } newstr[counter] = 0; return newstr; } int main(void) { char *new = strip_chars("She was a soul stripper. She took my heart!", "aei"); printf("%s\n", new); free(new); return 0; }
package main import ( "fmt" "strings" ) func stripchars(str, chr string) string { return strings.Map(func(r rune) rune { if strings.IndexRune(chr, r) < 0 { return r } return -1 }, str) } func main() { fmt.Println(stripchars("She was a soul stripper. She took my heart!", "aei")) }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int(*cmp_func)(const void*, const void*); void perm_sort(void *a, int n, size_t msize, cmp_func _cmp) { char *p, *q, *tmp = malloc(msize); # define A(i) ((char *)a + msize * (i)) # define swap(a, b) {\ memcpy(tmp, a, msize);\ memcpy(a, b, msize);\ memcpy(b, tmp, msize); } while (1) { for (p = A(n - 1); (void*)p > a; p = q) if (_cmp(q = p - msize, p) > 0) break; if ((void*)p <= a) break; for (p = A(n - 1); p > q; p-= msize) if (_cmp(q, p) > 0) break; swap(p, q); for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize) swap(p, q); } free(tmp); } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } int main() { int i; const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" }; perm_sort(strs, 5, sizeof(*strs), scmp); for (i = 0; i < 5; i++) printf("%s\n", strs[i]); return 0; }
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) if len(a) > 1 && !recurse(len(a) - 1) { panic("sorted permutation not found!") } fmt.Println("after: ", a) } func recurse(last int) bool { if last <= 0 { for i := len(a) - 1; a[i] >= a[i-1]; i-- { if i == 1 { return true } } return false } for i := 0; i <= last; i++ { a[i], a[last] = a[last], a[i] if recurse(last - 1) { return true } a[i], a[last] = a[last], a[i] } return false }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; } int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%g", v[i]); printf("] = %g\n", mean(v, len)); } return 0; }
package main import ( "fmt" "math" ) func mean(v []float64) (m float64, ok bool) { if len(v) == 0 { return } var parts []float64 for _, x := range v { var i int for _, p := range parts { sum := p + x var err float64 switch ax, ap := math.Abs(x), math.Abs(p); { case ax < ap: err = x - (sum - p) case ap < ax: err = p - (sum - x) } if err != 0 { parts[i] = err i++ } x = sum } parts = append(parts[:i], x) } var sum float64 for _, x := range parts { sum += x } return sum / float64(len(v)), true } func main() { for _, v := range [][]float64{ []float64{}, []float64{math.Inf(1), math.Inf(1)}, []float64{math.Inf(1), math.Inf(-1)}, []float64{3, 1, 4, 1, 5, 9}, []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20}, []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11}, []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2}, } { fmt.Println("Vector:", v) if m, ok := mean(v); ok { fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m) } else { fmt.Println("Mean undefined\n") } } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } 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; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
Produce a language-to-language conversion: from C to Go, same semantics.
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } 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; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
Generate an equivalent Go version of this C code.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 100 int makehist(unsigned char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ unsigned char S[MAXLEN]; int len,*hist,histlen; double H; scanf("%[^\n]",S); len=strlen(S); hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
package main import ( "fmt" "math" "strings" ) func main(){ fmt.Println(H("1223334444")) } func H(data string) (entropy float64) { if data == "" { return 0 } for i := 0; i < 256; i++ { px := float64(strings.Count(data, string(byte(i)))) / float64(len(data)) if px > 0 { entropy += -px * math.Log2(px) } } return entropy }
Keep all operations the same but rewrite the snippet in Go.
#include <stdlib.h> #include <stdio.h> #define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|" #define SEP '|' #define ESC '^' typedef char* Str; unsigned int ElQ( const char *s, char sep, char esc ); Str *Tokenize( char *s, char sep, char esc, unsigned int *q ); int main() { char s[] = STR_DEMO; unsigned int i, q; Str *list = Tokenize( s, SEP, ESC, &q ); if( list != NULL ) { printf( "\n Original string: %s\n\n", STR_DEMO ); printf( " %d tokens:\n\n", q ); for( i=0; i<q; ++i ) printf( " %4d. %s\n", i+1, list[i] ); free( list ); } return 0; } unsigned int ElQ( const char *s, char sep, char esc ) { unsigned int q, e; const char *p; for( e=0, q=1, p=s; *p; ++p ) { if( *p == esc ) e = !e; else if( *p == sep ) q += !e; else e = 0; } return q; } Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) { Str *list = NULL; *q = ElQ( s, sep, esc ); list = malloc( *q * sizeof(Str) ); if( list != NULL ) { unsigned int e, i; char *p; i = 0; list[i++] = s; for( e=0, p=s; *p; ++p ) { if( *p == esc ) { e = !e; } else if( *p == sep && !e ) { list[i++] = p+1; *p = '\0'; } else { e = 0; } } } return list; }
package main import ( "errors" "fmt" ) func TokenizeString(s string, sep, escape rune) (tokens []string, err error) { var runes []rune inEscape := false for _, r := range s { switch { case inEscape: inEscape = false fallthrough default: runes = append(runes, r) case r == escape: inEscape = true case r == sep: tokens = append(tokens, string(runes)) runes = runes[:0] } } tokens = append(tokens, string(runes)) if inEscape { err = errors.New("invalid terminal escape") } return tokens, err } func main() { const sample = "one^|uno||three^^^^|four^^^|^cuatro|" const separator = '|' const escape = '^' fmt.Printf("Input: %q\n", sample) tokens, err := TokenizeString(sample, separator, escape) if err != nil { fmt.Println("error:", err) } else { fmt.Printf("Tokens: %q\n", tokens) } }
Change the programming language of this snippet from C to Go without modifying what it does.
const hello = "Hello world!\n" print(hello)
package main import "fmt" func main() { fmt.Println("Hello world!") }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #define TRUE 1 #define FALSE 0 typedef unsigned char bool; void sieve(bool *c, int limit) { int i, p = 3, p2; c[0] = TRUE; c[1] = TRUE; 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; } } } } void printHelper(const char *cat, int len, int lim, int n) { const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : ""; const char *verb = (len == 1) ? "is" : "are"; printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len); printf("The last %d %s:\n", n, verb); } void printArray(int *a, int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]"); } int main() { int i, ix, n, lim = 1000035; int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2; int pr = 0, tr = 0, qd = 0, qn = 0, un = 2; int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10; int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5]; int last_un[10]; bool *sv = calloc(lim - 1, sizeof(bool)); setlocale(LC_NUMERIC, ""); sieve(sv, lim); for (i = 3; i < lim; i += 2) { if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) { unsexy++; continue; } if (i < lim-6 && !sv[i] && !sv[i+6]) { pairs++; } else continue; if (i < lim-12 && !sv[i+12]) { trips++; } else continue; if (i < lim-18 && !sv[i+18]) { quads++; } else continue; if (i < lim-24 && !sv[i+24]) { quins++; } } if (pairs < lpr) lpr = pairs; if (trips < ltr) ltr = trips; if (quads < lqd) lqd = quads; if (quins < lqn) lqn = quins; if (unsexy < lun) lun = unsexy; for (i = 3; i < lim; i += 2) { if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) { un++; if (un > unsexy - lun) { last_un[un + lun - 1 - unsexy] = i; } continue; } if (i < lim-6 && !sv[i] && !sv[i+6]) { pr++; if (pr > pairs - lpr) { ix = pr + lpr - 1 - pairs; last_pr[ix][0] = i; last_pr[ix][1] = i + 6; } } else continue; if (i < lim-12 && !sv[i+12]) { tr++; if (tr > trips - ltr) { ix = tr + ltr - 1 - trips; last_tr[ix][0] = i; last_tr[ix][1] = i + 6; last_tr[ix][2] = i + 12; } } else continue; if (i < lim-18 && !sv[i+18]) { qd++; if (qd > quads - lqd) { ix = qd + lqd - 1 - quads; last_qd[ix][0] = i; last_qd[ix][1] = i + 6; last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18; } } else continue; if (i < lim-24 && !sv[i+24]) { qn++; if (qn > quins - lqn) { ix = qn + lqn - 1 - quins; last_qn[ix][0] = i; last_qn[ix][1] = i + 6; last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18; last_qn[ix][4] = i + 24; } } } printHelper("pairs", pairs, lim, lpr); printf(" ["); for (i = 0; i < lpr; ++i) { printArray(last_pr[i], 2); printf("\b] "); } printf("\b]\n\n"); printHelper("triplets", trips, lim, ltr); printf(" ["); for (i = 0; i < ltr; ++i) { printArray(last_tr[i], 3); printf("\b] "); } printf("\b]\n\n"); printHelper("quadruplets", quads, lim, lqd); printf(" ["); for (i = 0; i < lqd; ++i) { printArray(last_qd[i], 4); printf("\b] "); } printf("\b]\n\n"); printHelper("quintuplets", quins, lim, lqn); printf(" ["); for (i = 0; i < lqn; ++i) { printArray(last_qn[i], 5); printf("\b] "); } printf("\b]\n\n"); printHelper("unsexy primes", unsexy, lim, lun); printf(" ["); printArray(last_un, lun); printf("\b]\n"); free(sv); return 0; }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func printHelper(cat string, le, lim, max int) (int, int, string) { cle, clim := commatize(le), commatize(lim) if cat != "unsexy primes" { cat = "sexy prime " + cat } fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle) last := max if le < last { last = le } verb := "are" if last == 1 { verb = "is" } return le, last, verb } func main() { lim := 1000035 sv := sieve(lim - 1) var pairs [][2]int var trips [][3]int var quads [][4]int var quins [][5]int var unsexy = []int{2, 3} for i := 3; i < lim; i += 2 { if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] { unsexy = append(unsexy, i) continue } if i < lim-6 && !sv[i] && !sv[i+6] { pair := [2]int{i, i + 6} pairs = append(pairs, pair) } else { continue } if i < lim-12 && !sv[i+12] { trip := [3]int{i, i + 6, i + 12} trips = append(trips, trip) } else { continue } if i < lim-18 && !sv[i+18] { quad := [4]int{i, i + 6, i + 12, i + 18} quads = append(quads, quad) } else { continue } if i < lim-24 && !sv[i+24] { quin := [5]int{i, i + 6, i + 12, i + 18, i + 24} quins = append(quins, quin) } } le, n, verb := printHelper("pairs", len(pairs), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, pairs[le-n:]) le, n, verb = printHelper("triplets", len(trips), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, trips[le-n:]) le, n, verb = printHelper("quadruplets", len(quads), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quads[le-n:]) le, n, verb = printHelper("quintuplets", len(quins), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quins[le-n:]) le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, unsexy[le-n:]) }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdlib.h> #include <string.h> #include <stdio.h> double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf("%g ", y[i]); putchar('\n'); return 0; }
package main import "fmt" func main() { a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73} fmt.Println(a) fmt.Println(fd(a, 9)) } func fd(a []int, ord int) []int { for i := 0; i < ord; i++ { for j := 0; j < len(a)-i-1; j++ { a[j] = a[j+1] - a[j] } } return a[:len(a)-ord] }
Please provide an equivalent version of this C code in Go.
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
package main import "fmt" import "math/big" func main() { fmt.Println(new(big.Int).Binomial(5, 3)) fmt.Println(new(big.Int).Binomial(60, 30)) }
Translate this program into Go but keep the logic exactly as in C.
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) int ar[10]; ar[0] = 1; ar[1] = 2; int* p; for (p=ar; p<(ar+cSize(ar)); p++) { printf("%d\n",*p); }
package main import "fmt" func main() { var a []interface{} a = append(a, 3) a = append(a, "apples", "oranges") fmt.Println(a) }
Change the following C code into Go without altering its purpose.
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next { fmt.Println(iter) }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Convert this C block to Go, preserving its control flow and logic.
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdio.h> int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
package main import "os" func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs") os.RemoveAll("docs") os.RemoveAll("/docs") }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdlib.h> #include <stdio.h> #include <time.h> #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange") #define season( x ) ((x) == 0 ? "Chaos" :\ (x) == 1 ? "Discord" :\ (x) == 2 ? "Confusion" :\ (x) == 3 ? "Bureaucracy" :\ "The Aftermath") #define date( x ) ((x)%73 == 0 ? 73 : (x)%73) #define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100)) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = malloc( 100 * sizeof( char ) ); if( leap_year( y ) ){ if( d == 60 ){ sprintf( result, "St. Tib's Day, YOLD %d", dyear ); return result; } else if( d >= 60 ){ -- d; } } sprintf( result, "%s, %s %d, YOLD %d", day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear ); return result; } int day_of_year( int y, int m, int d ){ int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; for( ; m > 1; m -- ){ d += month_lengths[ m - 2 ]; if( m == 3 && leap_year( y ) ){ ++ d; } } return d; } int main( int argc, char * argv[] ){ time_t now; struct tm * now_time; int year, doy; if( argc == 1 ){ now = time( NULL ); now_time = localtime( &now ); year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1; } else if( argc == 4 ){ year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) ); } char * result = ddate( year, doy ); puts( result ); free( result ); return 0; }
package ddate import ( "strconv" "strings" "time" ) const ( DefaultFmt = "Pungenday, Discord 5, 3131 YOLD" OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131 Celebrate Mojoday` ) const ( protoLongSeason = "Discord" protoShortSeason = "Dsc" protoLongDay = "Pungenday" protoShortDay = "PD" protoOrdDay = "5" protoCardDay = "5th" protoHolyday = "Mojoday" protoYear = "3131" ) var ( longDay = []string{"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"} shortDay = []string{"SM", "BT", "PD", "PP", "SO"} longSeason = []string{ "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"} shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"} holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"}, {"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}} ) type DiscDate struct { StTibs bool Dayy int Year int } func New(eris time.Time) DiscDate { t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(), eris.Second(), eris.Nanosecond(), eris.Location()) bob := int(eris.Sub(t).Hours()) / 24 raw := eris.Year() hastur := DiscDate{Year: raw + 1166} if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) { if bob > 59 { bob-- } else if bob == 59 { hastur.StTibs = true return hastur } } hastur.Dayy = bob return hastur } func (dd DiscDate) Format(f string) (r string) { var st, snarf string var dateElement bool f6 := func(proto, wibble string) { if !dateElement { snarf = r dateElement = true } if st > "" { r = "" } else { r += wibble } f = f[len(proto):] } f4 := func(proto, wibble string) { if dd.StTibs { st = "St. Tib's Day" } f6(proto, wibble) } season, day := dd.Dayy/73, dd.Dayy%73 for f > "" { switch { case strings.HasPrefix(f, protoLongDay): f4(protoLongDay, longDay[dd.Dayy%5]) case strings.HasPrefix(f, protoShortDay): f4(protoShortDay, shortDay[dd.Dayy%5]) case strings.HasPrefix(f, protoCardDay): funkychickens := "th" if day/10 != 1 { switch day % 10 { case 0: funkychickens = "st" case 1: funkychickens = "nd" case 2: funkychickens = "rd" } } f4(protoCardDay, strconv.Itoa(day+1)+funkychickens) case strings.HasPrefix(f, protoOrdDay): f4(protoOrdDay, strconv.Itoa(day+1)) case strings.HasPrefix(f, protoLongSeason): f6(protoLongSeason, longSeason[season]) case strings.HasPrefix(f, protoShortSeason): f6(protoShortSeason, shortSeason[season]) case strings.HasPrefix(f, protoHolyday): if day == 4 { r += holyday[season][0] } else if day == 49 { r += holyday[season][1] } f = f[len(protoHolyday):] case strings.HasPrefix(f, protoYear): r += strconv.Itoa(dd.Year) f = f[4:] default: r += f[:1] f = f[1:] } } if st > "" { r = snarf + st + r } return }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
Please provide an equivalent version of this C code in Go.
#include <stdio.h> int main() { const char *extra = "little"; printf("Mary had a %s lamb.\n", extra); return 0; }
package main import ( "fmt" ) func main() { str := "Mary had a %s lamb" txt := "little" out := fmt.Sprintf(str, txt) fmt.Println(out) }
Convert the following code from C to Go, ensuring the logic remains intact.
#include<stdlib.h> #include<stdio.h> int* patienceSort(int* arr,int size){ int decks[size][size],i,j,min,pickedRow; int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int)); for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){ decks[j][count[j]] = arr[i]; count[j]++; break; } } } min = decks[0][count[0]-1]; pickedRow = 0; for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]>0 && decks[j][count[j]-1]<min){ min = decks[j][count[j]-1]; pickedRow = j; } } sortedArr[i] = min; count[pickedRow]--; for(j=0;j<size;j++) if(count[j]>0){ min = decks[j][count[j]-1]; pickedRow = j; break; } } free(count); free(decks); return sortedArr; } int main(int argC,char* argV[]) { int *arr, *sortedArr, i; if(argC==0) printf("Usage : %s <integers to be sorted separated by space>"); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<=argC;i++) arr[i-1] = atoi(argV[i]); sortedArr = patienceSort(arr,argC-1); for(i=0;i<argC-1;i++) printf("%d ",sortedArr[i]); } return 0; }
package main import ( "fmt" "container/heap" "sort" ) type IntPile []int func (self IntPile) Top() int { return self[len(self)-1] } func (self *IntPile) Pop() int { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } type IntPilesHeap []IntPile func (self IntPilesHeap) Len() int { return len(self) } func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() } func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] } func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) } func (self *IntPilesHeap) Pop() interface{} { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } func patience_sort (n []int) { var piles []IntPile for _, x := range n { j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x }) if j != len(piles) { piles[j] = append(piles[j], x) } else { piles = append(piles, IntPile{ x }) } } hp := IntPilesHeap(piles) heap.Init(&hp) for i, _ := range n { smallPile := heap.Pop(&hp).(IntPile) n[i] = smallPile.Pop() if len(smallPile) != 0 { heap.Push(&hp, smallPile) } } if len(hp) != 0 { panic("something went wrong") } } func main() { a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1} patience_sort(a) fmt.Println(a) }
Change the following C code into Go without altering its purpose.
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
Write a version of this C function in Go with identical behavior.
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
Generate an equivalent Go version of this C code.
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
Write a version of this C function in Go with identical behavior.
#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; } int main() { const unsigned int limit = 100; unsigned int count = 0; unsigned int n; printf("The first %d tau numbers are:\n", limit); for (n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { printf("%6d", n); ++count; if (count % 10 == 0) { printf("\n"); } } } return 0; }
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } return count } func main() { fmt.Println("The first 100 tau numbers are:") count := 0 i := 1 for count < 100 { tf := countDivisors(i) if i%tf == 0 { fmt.Printf("%4d ", i) count++ if count%10 == 0 { fmt.Println() } } i++ } }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } return sum; } double det(double *in, int n, int perm) { double *m[n]; for (int i = 0; i < n; i++) m[i] = in + (n * i); return det_in(m, n, perm); } int main(void) { double x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; printf("det: %14.12g\n", det(x, 5, 0)); printf("perm: %14.12g\n", det(x, 5, 1)); return 0; }
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } return sum; } double det(double *in, int n, int perm) { double *m[n]; for (int i = 0; i < n; i++) m[i] = in + (n * i); return det_in(m, n, perm); } int main(void) { double x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; printf("det: %14.12g\n", det(x, 5, 0)); printf("perm: %14.12g\n", det(x, 5, 1)); return 0; }
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
Produce a functionally identical Go code for the snippet given in C.
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <gmp.h> mpz_t* partition(uint64_t n) { mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t)); mpz_init_set_ui(pn[0], 1); mpz_init_set_ui(pn[1], 1); for (uint64_t i = 2; i < n + 2; i ++) { mpz_init(pn[i]); for (uint64_t k = 1, penta; ; k++) { penta = k * (3 * k - 1) >> 1; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); penta += k; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); } } mpz_t *tmp = &pn[n + 1]; for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]); free(pn); return tmp; } int main(int argc, char const *argv[]) { clock_t start = clock(); mpz_t *p = partition(6666); gmp_printf("%Zd\n", p); printf("Elapsed time: %.04f seconds\n", (double)(clock() - start) / (double)CLOCKS_PER_SEC); return 0; }
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum } func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
Ensure the translated Go code behaves exactly like the original C snippet.
#define ANIMATE_VT100_POSIX #include <stdio.h> #include <string.h> #ifdef ANIMATE_VT100_POSIX #include <time.h> #endif char world_7x14[2][512] = { { "+-----------+\n" "|tH.........|\n" "|. . |\n" "| ... |\n" "|. . |\n" "|Ht.. ......|\n" "+-----------+\n" } }; void next_world(const char *in, char *out, int w, int h) { int i; for (i = 0; i < w*h; i++) { switch (in[i]) { case ' ': out[i] = ' '; break; case 't': out[i] = '.'; break; case 'H': out[i] = 't'; break; case '.': { int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') + (in[i-1] == 'H') + (in[i+1] == 'H') + (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H'); out[i] = (hc == 1 || hc == 2) ? 'H' : '.'; break; } default: out[i] = in[i]; } } out[i] = in[i]; } int main() { int f; for (f = 0; ; f = 1 - f) { puts(world_7x14[f]); next_world(world_7x14[f], world_7x14[1-f], 14, 7); #ifdef ANIMATE_VT100_POSIX printf("\x1b[%dA", 8); printf("\x1b[%dD", 14); { static const struct timespec ts = { 0, 100000000 }; nanosleep(&ts, 0); } #endif } return 0; }
package main import ( "bytes" "fmt" "io/ioutil" "strings" ) var rows, cols int var rx, cx int var mn []int func main() { src, err := ioutil.ReadFile("ww.config") if err != nil { fmt.Println(err) return } srcRows := bytes.Split(src, []byte{'\n'}) rows = len(srcRows) for _, r := range srcRows { if len(r) > cols { cols = len(r) } } rx, cx = rows+2, cols+2 mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1} odd := make([]byte, rx*cx) even := make([]byte, rx*cx) for ri, r := range srcRows { copy(odd[(ri+1)*cx+1:], r) } for { print(odd) step(even, odd) fmt.Scanln() print(even) step(odd, even) fmt.Scanln() } } func print(grid []byte) { fmt.Println(strings.Repeat("__", cols)) fmt.Println() for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if grid[r*cx+c] == 0 { fmt.Print(" ") } else { fmt.Printf(" %c", grid[r*cx+c]) } } fmt.Println() } } func step(dst, src []byte) { for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { x := r*cx + c dst[x] = src[x] switch dst[x] { case 'H': dst[x] = 't' case 't': dst[x] = '.' case '.': var nn int for _, n := range mn { if src[x+n] == 'H' { nn++ } } if nn == 1 || nn == 2 { dst[x] = 'H' } } } } }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double x, y; } vec; typedef struct { int n; vec* v; } polygon_t, *polygon; #define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;} #define BIN_S(op, r) double v##op(vec a, vec b){ return r; } BIN_V(sub, a.x - b.x, a.y - b.y); BIN_V(add, a.x + b.x, a.y + b.y); BIN_S(dot, a.x * b.x + a.y * b.y); BIN_S(cross, a.x * b.y - a.y * b.x); vec vmadd(vec a, double s, vec b) { vec c; c.x = a.x + s * b.x; c.y = a.y + s * b.y; return c; } int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect) { vec dx = vsub(x1, x0), dy = vsub(y1, y0); double d = vcross(dy, dx), a; if (!d) return 0; a = (vcross(x0, dx) - vcross(y0, dx)) / d; if (sect) *sect = vmadd(y0, a, dy); if (a < -tol || a > 1 + tol) return -1; if (a < tol || a > 1 - tol) return 0; a = (vcross(x0, dy) - vcross(y0, dy)) / d; if (a < 0 || a > 1) return -1; return 1; } double dist(vec x, vec y0, vec y1, double tol) { vec dy = vsub(y1, y0); vec x1, s; int r; x1.x = x.x + dy.y; x1.y = x.y - dy.x; r = intersect(x, x1, y0, y1, tol, &s); if (r == -1) return HUGE_VAL; s = vsub(s, x); return sqrt(vdot(s, s)); } #define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++) int inside(vec v, polygon p, double tol) { int i, k, crosses, intersectResult; vec *pv; double min_x, max_x, min_y, max_y; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; min_x = dist(v, p->v[i], p->v[k], tol); if (min_x < tol) return 0; } min_x = max_x = p->v[0].x; min_y = max_y = p->v[1].y; for_v(i, pv, p) { if (pv->x > max_x) max_x = pv->x; if (pv->x < min_x) min_x = pv->x; if (pv->y > max_y) max_y = pv->y; if (pv->y < min_y) min_y = pv->y; } if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y) return -1; max_x -= min_x; max_x *= 2; max_y -= min_y; max_y *= 2; max_x += max_y; vec e; while (1) { crosses = 0; e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x; e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0); if (!intersectResult) break; if (intersectResult == 1) crosses++; } if (i == p->n) break; } return (crosses & 1) ? 1 : -1; } int main() { vec vsq[] = { {0,0}, {10,0}, {10,10}, {0,10}, {2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}}; polygon_t sq = { 4, vsq }, sq_hole = { 8, vsq }; vec c = { 10, 5 }; vec d = { 5, 5 }; printf("%d\n", inside(c, &sq, 1e-10)); printf("%d\n", inside(c, &sq_hole, 1e-10)); printf("%d\n", inside(d, &sq, 1e-10)); printf("%d\n", inside(d, &sq_hole, 1e-10)); return 0; }
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{ {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10}, {1, 2}, {2, 1}, } func main() { for _, pg := range tpg { fmt.Printf("%s:\n", pg.name) for _, pt := range tpt { fmt.Println(pt, inside(pt, pg)) } } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <math.h> #define C 7 typedef struct { double x, y; } pt; pt zero(void) { return (pt){ INFINITY, INFINITY }; } int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; } pt neg(pt p) { return (pt){ p.x, -p.y }; } pt dbl(pt p) { if (is_zero(p)) return p; pt r; double L = (3 * p.x * p.x) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> #include <math.h> #define C 7 typedef struct { double x, y; } pt; pt zero(void) { return (pt){ INFINITY, INFINITY }; } int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; } pt neg(pt p) { return (pt){ p.x, -p.y }; } pt dbl(pt p) { if (is_zero(p)) return p; pt r; double L = (3 * p.x * p.x) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> #include <string.h> int match(const char *s, const char *p, int overlap) { int c = 0, l = strlen(p); while (*s != '\0') { if (strncmp(s++, p, l)) continue; if (!overlap) s += l - 1; c++; } return c; } int main() { printf("%d\n", match("the three truths", "th", 0)); printf("overlap:%d\n", match("abababababa", "aba", 1)); printf("not: %d\n", match("abababababa", "aba", 0)); return 0; }
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Count("the three truths", "th")) fmt.Println(strings.Count("ababababab", "abab")) }
Write the same algorithm in Go as shown in this C implementation.
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
Write a version of this C function in Go with identical behavior.
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
Maintain the same structure and functionality when rewriting this code in Go.
if (strcmp(a,b)) action_on_equality();
package main import ( "fmt" "strings" ) func main() { c := "cat" d := "dog" if c == d { fmt.Println(c, "is bytewise identical to", d) } if c != d { fmt.Println(c, "is bytewise different from", d) } if c > d { fmt.Println(c, "is lexically bytewise greater than", d) } if c < d { fmt.Println(c, "is lexically bytewise less than", d) } if c >= d { fmt.Println(c, "is lexically bytewise greater than or equal to", d) } if c <= d { fmt.Println(c, "is lexically bytewise less than or equal to", d) } eqf := `when interpreted as UTF-8 and compared under Unicode simple case folding rules.` if strings.EqualFold(c, d) { fmt.Println(c, "equal to", d, eqf) } else { fmt.Println(c, "not equal to", d, eqf) } }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 0; }
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 0; }
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
Write a version of this C function in Go with identical behavior.
#include <stdio.h> #include <string.h> #include <math.h> #define N 32 #define N2 (N * (N - 1) / 2) #define STEP .05 double xval[N], t_sin[N], t_cos[N], t_tan[N]; double r_sin[N2], r_cos[N2], r_tan[N2]; double rho(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } #define i_sin(x) thiele(t_sin, xval, r_sin, x, 0) #define i_cos(x) thiele(t_cos, xval, r_cos, x, 0) #define i_tan(x) thiele(t_tan, xval, r_tan, x, 0) int main() { int i; for (i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = 0/0.; printf("%16.14f\n", 6 * i_sin(.5)); printf("%16.14f\n", 3 * i_cos(.5)); printf("%16.14f\n", 4 * i_tan(1.)); return 0; }
package main import ( "fmt" "math" ) func main() { const nn = 32 const step = .05 xVal := make([]float64, nn) tSin := make([]float64, nn) tCos := make([]float64, nn) tTan := make([]float64, nn) for i := range xVal { xVal[i] = float64(i) * step tSin[i], tCos[i] = math.Sincos(xVal[i]) tTan[i] = tSin[i] / tCos[i] } iSin := thieleInterpolator(tSin, xVal) iCos := thieleInterpolator(tCos, xVal) iTan := thieleInterpolator(tTan, xVal) fmt.Printf("%16.14f\n", 6*iSin(.5)) fmt.Printf("%16.14f\n", 3*iCos(.5)) fmt.Printf("%16.14f\n", 4*iTan(1)) } func thieleInterpolator(x, y []float64) func(float64) float64 { n := len(x) ρ := make([][]float64, n) for i := range ρ { ρ[i] = make([]float64, n-i) ρ[i][0] = y[i] } for i := 0; i < n-1; i++ { ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) } for i := 2; i < n; i++ { for j := 0; j < n-i; j++ { ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] } } ρ0 := ρ[0] return func(xin float64) float64 { var a float64 for i := n - 1; i > 1; i-- { a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) } return y[0] + (xin-x[0])/(ρ0[1]+a) } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <string.h> #include <math.h> #define N 32 #define N2 (N * (N - 1) / 2) #define STEP .05 double xval[N], t_sin[N], t_cos[N], t_tan[N]; double r_sin[N2], r_cos[N2], r_tan[N2]; double rho(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } #define i_sin(x) thiele(t_sin, xval, r_sin, x, 0) #define i_cos(x) thiele(t_cos, xval, r_cos, x, 0) #define i_tan(x) thiele(t_tan, xval, r_tan, x, 0) int main() { int i; for (i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = 0/0.; printf("%16.14f\n", 6 * i_sin(.5)); printf("%16.14f\n", 3 * i_cos(.5)); printf("%16.14f\n", 4 * i_tan(1.)); return 0; }
package main import ( "fmt" "math" ) func main() { const nn = 32 const step = .05 xVal := make([]float64, nn) tSin := make([]float64, nn) tCos := make([]float64, nn) tTan := make([]float64, nn) for i := range xVal { xVal[i] = float64(i) * step tSin[i], tCos[i] = math.Sincos(xVal[i]) tTan[i] = tSin[i] / tCos[i] } iSin := thieleInterpolator(tSin, xVal) iCos := thieleInterpolator(tCos, xVal) iTan := thieleInterpolator(tTan, xVal) fmt.Printf("%16.14f\n", 6*iSin(.5)) fmt.Printf("%16.14f\n", 3*iCos(.5)) fmt.Printf("%16.14f\n", 4*iTan(1)) } func thieleInterpolator(x, y []float64) func(float64) float64 { n := len(x) ρ := make([][]float64, n) for i := range ρ { ρ[i] = make([]float64, n-i) ρ[i][0] = y[i] } for i := 0; i < n-1; i++ { ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) } for i := 2; i < n; i++ { for j := 0; j < n-i; j++ { ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] } } ρ0 := ρ[0] return func(xin float64) float64 { var a float64 for i := n - 1; i > 1; i-- { a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) } return y[0] + (xin-x[0])/(ρ0[1]+a) } }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void print_headings() { printf("%2s", "N"); printf(" %10s", "Length"); printf(" %-20s", "Entropy"); printf(" %-40s", "Word"); printf("\n"); } double calculate_entropy(int ones, int zeros) { double result = 0; int total = ones + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void print_headings() { printf("%2s", "N"); printf(" %10s", "Length"); printf(" %-20s", "Entropy"); printf(" %-40s", "Word"); printf("\n"); } double calculate_entropy(int ones, int zeros) { double result = 0; int total = ones + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
Convert this C block to Go, preserving its control flow and logic.
#define PI 3.141592653589793 #define TWO_PI 6.283185307179586 double normalize2deg(double a) { while (a < 0) a += 360; while (a >= 360) a -= 360; return a; } double normalize2grad(double a) { while (a < 0) a += 400; while (a >= 400) a -= 400; return a; } double normalize2mil(double a) { while (a < 0) a += 6400; while (a >= 6400) a -= 6400; return a; } double normalize2rad(double a) { while (a < 0) a += TWO_PI; while (a >= TWO_PI) a -= TWO_PI; return a; } double deg2grad(double a) {return a * 10 / 9;} double deg2mil(double a) {return a * 160 / 9;} double deg2rad(double a) {return a * PI / 180;} double grad2deg(double a) {return a * 9 / 10;} double grad2mil(double a) {return a * 16;} double grad2rad(double a) {return a * PI / 200;} double mil2deg(double a) {return a * 9 / 160;} double mil2grad(double a) {return a / 16;} double mil2rad(double a) {return a * PI / 3200;} double rad2deg(double a) {return a * 180 / PI;} double rad2grad(double a) {return a * 200 / PI;} double rad2mil(double a) {return a * 3200 / PI;}
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d float64) float64 { return d2d(d) * 400 / 360 } func d2m(d float64) float64 { return d2d(d) * 6400 / 360 } func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 } func g2d(g float64) float64 { return g2g(g) * 360 / 400 } func g2m(g float64) float64 { return g2g(g) * 6400 / 400 } func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 } func m2d(m float64) float64 { return m2m(m) * 360 / 6400 } func m2g(m float64) float64 { return m2m(m) * 400 / 6400 } func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 } func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi } func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi } func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi } func s(f float64) string { wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".") if len(wf) == 1 { return fmt.Sprintf("%7s ", wf[0]) } le := len(wf[1]) if le > 7 { le = 7 } return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le]) } func main() { angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ft := "%s %s %s %s %s\n" fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a))) } fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a))) } fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a))) } fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ") for _, a := range angles { fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))) } }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue; while (pos > 0 && names[0][--pos] != sep); return pos; } } return 0; } int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]); return 0; }
package main import ( "fmt" "os" "path" ) func CommonPrefix(sep byte, paths ...string) string { switch len(paths) { case 0: return "" case 1: return path.Clean(paths[0]) } c := []byte(path.Clean(paths[0])) c = append(c, sep) for _, v := range paths[1:] { v = path.Clean(v) + string(sep) if len(v) < len(c) { c = c[:len(v)] } for i := 0; i < len(c); i++ { if v[i] != c[i] { c = c[:i] break } } } for i := len(c) - 1; i >= 0; i-- { if c[i] == sep { c = c[:i] break } } return string(c) } func main() { c := CommonPrefix(os.PathSeparator, "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", "/home "/home/user1/././tmp/covertly/foo", "/home/bob/../user1/tmp/coved/bar", ) if c == "" { fmt.Println("No common path") } else { fmt.Println("Common path:", c) } }
Write a version of this C function in Go with identical behavior.
#include <stdlib.h> #include <stdio.h> #include <math.h> inline int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; } inline int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; } int check(int (*gen)(), int n, int cnt, double delta) { int i = cnt, *bins = calloc(sizeof(int), n); double ratio; while (i--) bins[gen() - 1]++; for (i = 0; i < n; i++) { ratio = bins[i] * n / (double)cnt - 1; if (ratio > -delta && ratio < delta) continue; printf("bin %d out of range: %d (%g%% vs %g%%), ", i + 1, bins[i], ratio * 100, delta * 100); break; } free(bins); return i == n; } int main() { int cnt = 1; while ((cnt *= 10) <= 1000000) { printf("Count = %d: ", cnt); printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n"); } return 0; }
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
Please provide an equivalent version of this C code in Go.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct stirling_cache_tag { int max; int* values; } stirling_cache; int stirling_number2(stirling_cache* sc, int n, int k) { if (k == n) return 1; if (k == 0 || k > n || n > sc->max) return 0; return sc->values[n*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct stirling_cache_tag { int max; int* values; } stirling_cache; int stirling_number2(stirling_cache* sc, int n, int k) { if (k == n) return 1; if (k == 0 || k > n || n > sc->max) return 0; return sc->values[n*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
Produce a functionally identical Go code for the snippet given in C.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct stirling_cache_tag { int max; int* values; } stirling_cache; int stirling_number2(stirling_cache* sc, int n, int k) { if (k == n) return 1; if (k == 0 || k > n || n > sc->max) return 0; return sc->values[n*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
Write the same algorithm in Go as shown in this C implementation.
#include <stdlib.h> #define SIZEOF_MEMB (sizeof(int)) #define NMEMB 100 int main() { int *ints = malloc(SIZEOF_MEMB*NMEMB); ints = realloc(ints, sizeof(int)*(NMEMB+1)); int *int2 = calloc(NMEMB, SIZEOF_MEMB); free(ints); free(int2); return 0; }
func inc(n int) { x := n + 1 println(x) }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> int b[3][3]; int check_winner() { int i; for (i = 0; i < 3; i++) { if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]; if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]; } if (!b[1][1]) return 0; if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]; if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]; return 0; } void showboard() { const char *t = "X O"; int i, j; for (i = 0; i < 3; i++, putchar('\n')) for (j = 0; j < 3; j++) printf("%c ", t[ b[i][j] + 1 ]); printf("-----\n"); } #define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) int best_i, best_j; int test_move(int val, int depth) { int i, j, score; int best = -1, changed = 0; if ((score = check_winner())) return (score == val) ? 1 : -1; for_ij { if (b[i][j]) continue; changed = b[i][j] = val; score = -test_move(-val, depth + 1); b[i][j] = 0; if (score <= best) continue; if (!depth) { best_i = i; best_j = j; } best = score; } return changed ? best : 0; } const char* game(int user) { int i, j, k, move, win = 0; for_ij b[i][j] = 0; printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n"); printf("You have O, I have X.\n\n"); for (k = 0; k < 9; k++, user = !user) { while(user) { printf("your move: "); if (!scanf("%d", &move)) { scanf("%*s"); continue; } if (--move < 0 || move >= 9) continue; if (b[i = move / 3][j = move % 3]) continue; b[i][j] = 1; break; } if (!user) { if (!k) { best_i = rand() % 3; best_j = rand() % 3; } else test_move(-1, 0); b[best_i][best_j] = -1; printf("My move: %d\n", best_i * 3 + best_j + 1); } showboard(); if ((win = check_winner())) return win == 1 ? "You win.\n\n": "I win.\n\n"; } return "A draw.\n\n"; } int main() { int first = 0; while (1) printf("%s", game(first = !first)); return 0; }
package main import ( "bufio" "fmt" "math/rand" "os" "strings" ) var b []byte func printBoard() { fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9]) } var pScore, cScore int var pMark, cMark byte = 'X', 'O' var in = bufio.NewReader(os.Stdin) func main() { b = make([]byte, 9) fmt.Println("Play by entering a digit.") for { for i := range b { b[i] = '1' + byte(i) } computerStart := cMark == 'X' if computerStart { fmt.Println("I go first, playing X's") } else { fmt.Println("You go first, playing X's") } TakeTurns: for { if !computerStart { if !playerTurn() { return } if gameOver() { break TakeTurns } } computerStart = false computerTurn() if gameOver() { break TakeTurns } } fmt.Println("Score: you", pScore, "me", cScore) fmt.Println("\nLet's play again.") } } func playerTurn() bool { var pm string var err error for i := 0; i < 3; i++ { printBoard() fmt.Printf("%c's move? ", pMark) if pm, err = in.ReadString('\n'); err != nil { fmt.Println(err) return false } pm = strings.TrimSpace(pm) if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] { x := pm[0] - '1' b[x] = pMark return true } } fmt.Println("You're not playing right.") return false } var choices = make([]int, 9) func computerTurn() { printBoard() var x int defer func() { fmt.Println("My move:", x+1) b[x] = cMark }() block := -1 for _, l := range lines { var mine, yours int x = -1 for _, sq := range l { switch b[sq] { case cMark: mine++ case pMark: yours++ default: x = sq } } if mine == 2 && x >= 0 { return } if yours == 2 && x >= 0 { block = x } } if block >= 0 { x = block return } choices = choices[:0] for i, sq := range b { if sq == '1'+byte(i) { choices = append(choices, i) } } x = choices[rand.Intn(len(choices))] } func gameOver() bool { for _, l := range lines { if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] { printBoard() if b[l[0]] == cMark { fmt.Println("I win!") cScore++ pMark, cMark = 'X', 'O' } else { fmt.Println("You win!") pScore++ pMark, cMark = 'O', 'X' } return true } } for i, sq := range b { if sq == '1'+byte(i) { return false } } fmt.Println("Cat game.") pMark, cMark = cMark, pMark return true } var lines = [][]int{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}, }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdio.h> int main() { unsigned int i = 0; while (++i) printf("%u\n", i); return 0; }
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> int main() { unsigned int i = 0; while (++i) printf("%u\n", i); return 0; }
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
package main import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" ) func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) } func entropy(file string) float64 { d, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } var f [256]float64 for _, b := range d { f[b]++ } hm := 0. for _, c := range f { if c > 0 { hm += c * math.Log2(c) } } l := float64(len(d)) return math.Log2(l) - hm/l }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
package main import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" ) func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) } func entropy(file string) float64 { d, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } var f [256]float64 for _, b := range d { f[b]++ } hm := 0. for _, c := range f { if c > 0 { hm += c * math.Log2(c) } } l := float64(len(d)) return math.Log2(l) - hm/l }
Translate the given C code snippet into Go without altering its behavior.
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Change the following C code into Go without altering its purpose.
#include <graphics.h> #include <math.h> void Peano(int x, int y, int lg, int i1, int i2) { if (lg == 1) { lineto(3*x,3*y); return; } lg = lg/3; Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); Peano(x+lg, y+lg, lg, i1, 1-i2); Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); } int main(void) { initwindow(1000,1000,"Peano, Peano"); Peano(0, 0, 1000, 0, 0); getch(); cleardevice(); return 0; }
package main import "github.com/fogleman/gg" var points []gg.Point const width = 81 func peano(x, y, lg, i1, i2 int) { if lg == 1 { px := float64(width-x) * 10 py := float64(width-y) * 10 points = append(points, gg.Point{px, py}) return } lg /= 3 peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2) peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2) peano(x+lg, y+lg, lg, i1, 1-i2) peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2) peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2) peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2) peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2) peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2) peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2) } func main() { peano(0, 0, width, 0, 0) dc := gg.NewContext(820, 820) dc.SetRGB(1, 1, 1) dc.Clear() for _, p := range points { dc.LineTo(p.X, p.Y) } dc.SetRGB(1, 0, 1) dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("peano.png") }
Generate an equivalent Go version of this C code.
int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; } int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; } int main() { printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n"); printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n"); return 0; }
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdbool.h> #include <stdio.h> #include <math.h> int connections[15][2] = { {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, }; int pegs[8]; int num = 0; bool valid() { int i; for (i = 0; i < 15; i++) { if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) { return false; } } return true; } void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } void printSolution() { printf("----- %d -----\n", num++); printf(" %d %d\n", pegs[0], pegs[1]); printf("%d %d %d %d\n", pegs[2], pegs[3], pegs[4], pegs[5]); printf(" %d %d\n", pegs[6], pegs[7]); printf("\n"); } void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { int i; for (i = le; i <= ri; i++) { swap(pegs + le, pegs + i); solution(le + 1, ri); swap(pegs + le, pegs + i); } } } int main() { int i; for (i = 0; i < 8; i++) { pegs[i] = i + 1; } solution(0, 8 - 1); return 0; }
package main import ( "fmt" "strings" ) func main() { p, tests, swaps := Solution() fmt.Println(p) fmt.Println("Tested", tests, "positions and did", swaps, "swaps.") } const conn = ` A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H` var connections = []struct{ a, b int }{ {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, } type pegs [8]int func (p *pegs) Valid() bool { for _, c := range connections { if absdiff(p[c.a], p[c.b]) <= 1 { return false } } return true } func Solution() (p *pegs, tests, swaps int) { var recurse func(int) bool recurse = func(i int) bool { if i >= len(p)-1 { tests++ return p.Valid() } for j := i; j < len(p); j++ { swaps++ p[i], p[j] = p[j], p[i] if recurse(i + 1) { return true } p[i], p[j] = p[j], p[i] } return false } p = &pegs{1, 2, 3, 4, 5, 6, 7, 8} recurse(0) return } func (p *pegs) String() string { return strings.Map(func(r rune) rune { if 'A' <= r && r <= 'H' { return rune(p[r-'A'] + '0') } return r }, conn) } func absdiff(a, b int) int { if a > b { return a - b } return b - a }