Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into Go but keep the logic exactly as in C.
#include<windows.h> #include<string.h> #include<stdio.h> #define MAXORDER 25 int main(int argC, char* argV[]) { char str[MAXORDER],commandString[1000],*startPath; long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max; int i,j,len; double scale; FILE* fp; if(argC==1) printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]); else{ if(strchr(argV[1],' ')!=NULL){ len = strlen(argV[1]); startPath = (char*)malloc((len+2)*sizeof(char)); startPath[0] = '\"'; startPath[len+1]='\"'; strncpy(startPath+1,argV[1],len); startPath[len+2] = argV[1][len]; sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath); } else if(strlen(argV[1])==1 && argV[1][0]=='.') strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1"); else sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]); fp = popen(commandString,"r"); while(fgets(str,100,fp)!=NULL){ if(str[0]=='0') fileSizeLog[0]++; else fileSizeLog[strlen(str)]++; } if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){ for(i=0;i<MAXORDER;i++){ printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]); } } else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){ CONSOLE_SCREEN_BUFFER_INFO csbi; int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi); if(val) { max = fileSizeLog[0]; for(i=1;i<MAXORDER;i++) (fileSizeLog[i]>max)?max=fileSizeLog[i]:max; (max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max); for(i=0;i<MAXORDER;i++){ printf("\nSize Order < 10^%2d bytes |",i); for(j=0;j<(int)(scale*fileSizeLog[i]);j++) printf("%c",219); printf("%Ld",fileSizeLog[i]); } } } return 0; } }
package main import ( "fmt" "log" "math" "os" "path/filepath" ) func commatize(n int64) 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 fileSizeDistribution(root string) { var sizes [12]int files := 0 directories := 0 totalSize := int64(0) walkFunc := func(path string, info os.FileInfo, err error) error { if err != nil { return err } files++ if info.IsDir() { directories++ } size := info.Size() if size == 0 { sizes[0]++ return nil } totalSize += size logSize := math.Log10(float64(size)) index := int(math.Floor(logSize)) sizes[index+1]++ return nil } err := filepath.Walk(root, walkFunc) if err != nil { log.Fatal(err) } fmt.Printf("File size distribution for '%s' :-\n\n", root) for i := 0; i < len(sizes); i++ { if i == 0 { fmt.Print(" ") } else { fmt.Print("+ ") } fmt.Printf("Files less than 10 ^ %-2d bytes : %5d\n", i, sizes[i]) } fmt.Println(" -----") fmt.Printf("= Total number of files  : %5d\n", files) fmt.Printf(" including directories  : %5d\n", directories) c := commatize(totalSize) fmt.Println("\n Total size of files  :", c, "bytes") } func main() { fileSizeDistribution("./") }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> int cmpstr(const void *a, const void *b) { return strcmp(*(const char**)a, *(const char**)b); } int main(void) { DIR *basedir; char path[PATH_MAX]; struct dirent *entry; char **dirnames; int diralloc = 128; int dirsize = 0; if (!(dirnames = malloc(diralloc * sizeof(char*)))) { perror("malloc error:"); return 1; } if (!getcwd(path, PATH_MAX)) { perror("getcwd error:"); return 1; } if (!(basedir = opendir(path))) { perror("opendir error:"); return 1; } while ((entry = readdir(basedir))) { if (dirsize >= diralloc) { diralloc *= 2; if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) { perror("realloc error:"); return 1; } } dirnames[dirsize++] = strdup(entry->d_name); } qsort(dirnames, dirsize, sizeof(char*), cmpstr); int i; for (i = 0; i < dirsize; ++i) { if (dirnames[i][0] != '.') { printf("%s\n", dirnames[i]); } } for (i = 0; i < dirsize; ++i) free(dirnames[i]); free(dirnames); closedir(basedir); return 0; }
package main import ( "fmt" "log" "os" "sort" ) func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdlib.h> #include <stdio.h> #include <pthread.h> typedef struct rendezvous { pthread_mutex_t lock; pthread_cond_t cv_entering; pthread_cond_t cv_accepting; pthread_cond_t cv_done; int (*accept_func)(void*); int entering; int accepting; int done; } rendezvous_t; #define RENDEZVOUS_INITILIZER(accept_function) { \ .lock = PTHREAD_MUTEX_INITIALIZER, \ .cv_entering = PTHREAD_COND_INITIALIZER, \ .cv_accepting = PTHREAD_COND_INITIALIZER, \ .cv_done = PTHREAD_COND_INITIALIZER, \ .accept_func = accept_function, \ .entering = 0, \ .accepting = 0, \ .done = 0, \ } int enter_rendezvous(rendezvous_t *rv, void* data) { pthread_mutex_lock(&rv->lock); rv->entering++; pthread_cond_signal(&rv->cv_entering); while (!rv->accepting) { pthread_cond_wait(&rv->cv_accepting, &rv->lock); } int ret = rv->accept_func(data); rv->done = 1; pthread_cond_signal(&rv->cv_done); rv->entering--; rv->accepting = 0; pthread_mutex_unlock(&rv->lock); return ret; } void accept_rendezvous(rendezvous_t *rv) { pthread_mutex_lock(&rv->lock); rv->accepting = 1; while (!rv->entering) { pthread_cond_wait(&rv->cv_entering, &rv->lock); } pthread_cond_signal(&rv->cv_accepting); while (!rv->done) { pthread_cond_wait(&rv->cv_done, &rv->lock); } rv->done = 0; rv->accepting = 0; pthread_mutex_unlock(&rv->lock); } typedef struct printer { rendezvous_t rv; struct printer *backup; int id; int remaining_lines; } printer_t; typedef struct print_args { struct printer *printer; const char* line; } print_args_t; int print_line(printer_t *printer, const char* line) { print_args_t args; args.printer = printer; args.line = line; return enter_rendezvous(&printer->rv, &args); } int accept_print(void* data) { print_args_t *args = (print_args_t*)data; printer_t *printer = args->printer; const char* line = args->line; if (printer->remaining_lines) { printf("%d: ", printer->id); while (*line != '\0') { putchar(*line++); } putchar('\n'); printer->remaining_lines--; return 1; } else if (printer->backup) { return print_line(printer->backup, line); } else { return -1; } } printer_t backup_printer = { .rv = RENDEZVOUS_INITILIZER(accept_print), .backup = NULL, .id = 2, .remaining_lines = 5, }; printer_t main_printer = { .rv = RENDEZVOUS_INITILIZER(accept_print), .backup = &backup_printer, .id = 1, .remaining_lines = 5, }; void* printer_thread(void* thread_data) { printer_t *printer = (printer_t*) thread_data; while (1) { accept_rendezvous(&printer->rv); } } typedef struct poem { char* name; char* lines[]; } poem_t; poem_t humpty_dumpty = { .name = "Humpty Dumpty", .lines = { "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men", "Couldn't put Humpty together again.", "" }, }; poem_t mother_goose = { .name = "Mother Goose", .lines = { "Old Mother Goose", "When she wanted to wander,", "Would ride through the air", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon.", "" }, }; void* poem_thread(void* thread_data) { poem_t *poem = (poem_t*)thread_data; for (unsigned i = 0; poem->lines[i] != ""; i++) { int ret = print_line(&main_printer, poem->lines[i]); if (ret < 0) { printf(" %s out of ink!\n", poem->name); exit(1); } } return NULL; } int main(void) { pthread_t threads[4]; pthread_create(&threads[0], NULL, poem_thread, &humpty_dumpty); pthread_create(&threads[1], NULL, poem_thread, &mother_goose); pthread_create(&threads[2], NULL, printer_thread, &main_printer); pthread_create(&threads[3], NULL, printer_thread, &backup_printer); pthread_join(threads[0], NULL); pthread_join(threads[1], NULL); pthread_cancel(threads[2]); pthread_cancel(threads[3]); return 0; }
package main import ( "errors" "fmt" "strings" "sync" ) var hdText = `Humpty Dumpty sat on a wall. Humpty Dumpty had a great fall. All the king's horses and all the king's men, Couldn't put Humpty together again.` var mgText = `Old Mother Goose, When she wanted to wander, Would ride through the air, On a very fine gander. Jack's mother came in, And caught the goose soon, And mounting its back, Flew up to the moon.` func main() { reservePrinter := startMonitor(newPrinter(5), nil) mainPrinter := startMonitor(newPrinter(5), reservePrinter) var busy sync.WaitGroup busy.Add(2) go writer(mainPrinter, "hd", hdText, &busy) go writer(mainPrinter, "mg", mgText, &busy) busy.Wait() } type printer func(string) error func newPrinter(ink int) printer { return func(line string) error { if ink == 0 { return eOutOfInk } for _, c := range line { fmt.Printf("%c", c) } fmt.Println() ink-- return nil } } var eOutOfInk = errors.New("out of ink") type rSync struct { call chan string response chan error } func (r *rSync) print(data string) error { r.call <- data return <-r.response } func monitor(hardPrint printer, entry, reserve *rSync) { for { data := <-entry.call switch err := hardPrint(data); { case err == nil: entry.response <- nil case err == eOutOfInk && reserve != nil: entry.response <- reserve.print(data) default: entry.response <- err } } } func startMonitor(p printer, reservePrinter *rSync) *rSync { entry := &rSync{make(chan string), make(chan error)} go monitor(p, entry, reservePrinter) return entry } func writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) { for _, line := range strings.Split(text, "\n") { if err := printMonitor.print(line); err != nil { fmt.Printf("**** writer task %q terminated: %v ****\n", id, err) break } } busy.Done() }
Translate the given C code snippet into Go without altering its behavior.
#include<stdio.h> #include<stdlib.h> #include<math.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int main(void) { int np = 1, d, i, n; printf( "3 " ); for(d=1; d<6; d++) { for(i=3; i<pow(10,d)-1; i+=10) { n = i + 3*pow(10,d); if(isprime(n)) { ++np; if(n<4009) { printf("%d ",n); if(!(np%10)) printf("\n"); } } } } printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np ); return 0; }
package main import ( "fmt" "rcu" ) func main() { var primes []int candidates := []int{3, 33} for i := 303; i <= 393; i += 10 { candidates = append(candidates, i) } for i := 3003; i <= 3993; i += 10 { candidates = append(candidates, i) } for _, cand := range candidates { if rcu.IsPrime(cand) { primes = append(primes, cand) } } fmt.Println("Primes under 4,000 which begin and end in 3:") for i, p := range primes { fmt.Printf("%5s ", rcu.Commatize(p)) if (i+1)%11 == 0 { fmt.Println() } } fmt.Println("\nFound", len(primes), "Such primes.") pc := len(primes) for i := 30003; i <= 39993; i += 10 { if rcu.IsPrime(i) { pc++ } } for i := 300003; i <= 399993; i += 10 { if rcu.IsPrime(i) { pc++ } } pcc := rcu.Commatize(pc) fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.") }
Write the same algorithm in Go as shown in this C implementation.
#include<stdio.h> #include<stdlib.h> #include<math.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int main(void) { int np = 1, d, i, n; printf( "3 " ); for(d=1; d<6; d++) { for(i=3; i<pow(10,d)-1; i+=10) { n = i + 3*pow(10,d); if(isprime(n)) { ++np; if(n<4009) { printf("%d ",n); if(!(np%10)) printf("\n"); } } } } printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np ); return 0; }
package main import ( "fmt" "rcu" ) func main() { var primes []int candidates := []int{3, 33} for i := 303; i <= 393; i += 10 { candidates = append(candidates, i) } for i := 3003; i <= 3993; i += 10 { candidates = append(candidates, i) } for _, cand := range candidates { if rcu.IsPrime(cand) { primes = append(primes, cand) } } fmt.Println("Primes under 4,000 which begin and end in 3:") for i, p := range primes { fmt.Printf("%5s ", rcu.Commatize(p)) if (i+1)%11 == 0 { fmt.Println() } } fmt.Println("\nFound", len(primes), "Such primes.") pc := len(primes) for i := 30003; i <= 39993; i += 10 { if rcu.IsPrime(i) { pc++ } } for i := 300003; i <= 399993; i += 10 { if rcu.IsPrime(i) { pc++ } } pcc := rcu.Commatize(pc) fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.") }
Produce a functionally identical Go code for the snippet given in C.
#include<stdio.h> #include<stdlib.h> #include<math.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int main(void) { int np = 1, d, i, n; printf( "3 " ); for(d=1; d<6; d++) { for(i=3; i<pow(10,d)-1; i+=10) { n = i + 3*pow(10,d); if(isprime(n)) { ++np; if(n<4009) { printf("%d ",n); if(!(np%10)) printf("\n"); } } } } printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np ); return 0; }
package main import ( "fmt" "rcu" ) func main() { var primes []int candidates := []int{3, 33} for i := 303; i <= 393; i += 10 { candidates = append(candidates, i) } for i := 3003; i <= 3993; i += 10 { candidates = append(candidates, i) } for _, cand := range candidates { if rcu.IsPrime(cand) { primes = append(primes, cand) } } fmt.Println("Primes under 4,000 which begin and end in 3:") for i, p := range primes { fmt.Printf("%5s ", rcu.Commatize(p)) if (i+1)%11 == 0 { fmt.Println() } } fmt.Println("\nFound", len(primes), "Such primes.") pc := len(primes) for i := 30003; i <= 39993; i += 10 { if rcu.IsPrime(i) { pc++ } } for i := 300003; i <= 399993; i += 10 { if rcu.IsPrime(i) { pc++ } } pcc := rcu.Commatize(pc) fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.") }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #define JOBS 12 #define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a)) typedef struct { int seq, cnt; } env_t; env_t env[JOBS] = {{0, 0}}; int *seq, *cnt; void hail() { printf("% 4d", *seq); if (*seq == 1) return; ++*cnt; *seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2; } void switch_to(int id) { seq = &env[id].seq; cnt = &env[id].cnt; } int main() { int i; jobs(i) { env[i].seq = i + 1; } again: jobs(i) { hail(); } jobs(i) { if (1 != *seq) goto again; } printf("COUNTS:\n"); jobs(i) { printf("% 4d", *cnt); } return 0; }
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 } } func switchTo(id int) { seq = &env[id].seq cnt = &env[id].cnt } func main() { for i := 0; i < jobs; i++ { switchTo(i) env[i].seq = i + 1 } again: for i := 0; i < jobs; i++ { switchTo(i) hail() } fmt.Println() for j := 0; j < jobs; j++ { switchTo(j) if *seq != 1 { goto again } } fmt.Println() fmt.Println("COUNTS:") for i := 0; i < jobs; i++ { switchTo(i) fmt.Printf("% 4d", *cnt) } fmt.Println() }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> typedef struct { char mask; char lead; uint32_t beg; uint32_t end; int bits_stored; }utf_t; utf_t * utf[] = { [0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 }, [1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 }, [2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 }, [3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 }, [4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 }, &(utf_t){0}, }; int codepoint_len(const uint32_t cp); int utf8_len(const char ch); char *to_utf8(const uint32_t cp); uint32_t to_cp(const char chr[4]); int codepoint_len(const uint32_t cp) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((cp >= (*u)->beg) && (cp <= (*u)->end)) { break; } ++len; } if(len > 4) exit(1); return len; } int utf8_len(const char ch) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((ch & ~(*u)->mask) == (*u)->lead) { break; } ++len; } if(len > 4) { exit(1); } return len; } char *to_utf8(const uint32_t cp) { static char ret[5]; const int bytes = codepoint_len(cp); int shift = utf[0]->bits_stored * (bytes - 1); ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead; shift -= utf[0]->bits_stored; for(int i = 1; i < bytes; ++i) { ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead; shift -= utf[0]->bits_stored; } ret[bytes] = '\0'; return ret; } uint32_t to_cp(const char chr[4]) { int bytes = utf8_len(*chr); int shift = utf[0]->bits_stored * (bytes - 1); uint32_t codep = (*chr++ & utf[bytes]->mask) << shift; for(int i = 1; i < bytes; ++i, ++chr) { shift -= utf[0]->bits_stored; codep |= ((char)*chr & utf[0]->mask) << shift; } return codep; } int main(void) { const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0}; printf("Character Unicode UTF-8 encoding (hex)\n"); printf("----------------------------------------\n"); char *utf8; uint32_t codepoint; for(in = input; *in; ++in) { utf8 = to_utf8(*in); codepoint = to_cp(utf8); printf("%s U+%-7.4x", utf8, codepoint); for(int i = 0; utf8[i] && i < 4; ++i) { printf("%hhx ", utf8[i]); } printf("\n"); } return 0; }
package main import ( "bytes" "encoding/hex" "fmt" "log" "strings" ) var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, } func main() { for _, tc := range testCases { u := fmt.Sprintf("U+%04X", tc.rune) b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1)) if err != nil { log.Fatal("bad test data") } e := encodeUTF8(tc.rune) d := decodeUTF8(b) fmt.Printf("%c  %-7s %X\n", d, u, e) if !bytes.Equal(e, b) { log.Fatal("encodeUTF8 wrong") } if d != tc.rune { log.Fatal("decodeUTF8 wrong") } } } const ( b2Lead = 0xC0 b2Mask = 0x1F b3Lead = 0xE0 b3Mask = 0x0F b4Lead = 0xF0 b4Mask = 0x07 mbLead = 0x80 mbMask = 0x3F ) func encodeUTF8(r rune) []byte { switch i := uint32(r); { case i <= 1<<7-1: return []byte{byte(r)} case i <= 1<<11-1: return []byte{ b2Lead | byte(r>>6), mbLead | byte(r)&mbMask} case i <= 1<<16-1: return []byte{ b3Lead | byte(r>>12), mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} default: return []byte{ b4Lead | byte(r>>18), mbLead | byte(r>>12)&mbMask, mbLead | byte(r>>6)&mbMask, mbLead | byte(r)&mbMask} } } func decodeUTF8(b []byte) rune { switch b0 := b[0]; { case b0 < 0x80: return rune(b0) case b0 < 0xE0: return rune(b0&b2Mask)<<6 | rune(b[1]&mbMask) case b0 < 0xF0: return rune(b0&b3Mask)<<12 | rune(b[1]&mbMask)<<6 | rune(b[2]&mbMask) default: return rune(b0&b4Mask)<<18 | rune(b[1]&mbMask)<<12 | rune(b[2]&mbMask)<<6 | rune(b[3]&mbMask) } }
Translate this program into Go but keep the logic exactly as in C.
void draw_line_antialias( image img, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, color_component r, color_component g, color_component b );
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) } func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { dx := x2 - x1 dy := y2 - y1 ax := dx if ax < 0 { ax = -ax } ay := dy if ay < 0 { ay = -ay } var plot func(int, int, float64) if ax < ay { x1, y1 = y1, x1 x2, y2 = y2, x2 dx, dy = dy, dx plot = func(x, y int, c float64) { g.SetPx(y, x, uint16(c*math.MaxUint16)) } } else { plot = func(x, y int, c float64) { g.SetPx(x, y, uint16(c*math.MaxUint16)) } } if x2 < x1 { x1, x2 = x2, x1 y1, y2 = y2, y1 } gradient := dy / dx xend := round(x1) yend := y1 + gradient*(xend-x1) xgap := rfpart(x1 + .5) xpxl1 := int(xend) ypxl1 := int(ipart(yend)) plot(xpxl1, ypxl1, rfpart(yend)*xgap) plot(xpxl1, ypxl1+1, fpart(yend)*xgap) intery := yend + gradient xend = round(x2) yend = y2 + gradient*(xend-x2) xgap = fpart(x2 + 0.5) xpxl2 := int(xend) ypxl2 := int(ipart(yend)) plot(xpxl2, ypxl2, rfpart(yend)*xgap) plot(xpxl2, ypxl2+1, fpart(yend)*xgap) for x := xpxl1 + 1; x <= xpxl2-1; x++ { plot(x, int(ipart(intery)), rfpart(intery)) plot(x, int(ipart(intery))+1, fpart(intery)) intery = intery + gradient } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/keysym.h> int main() { Display *d; XEvent event; d = XOpenDisplay(NULL); if ( d != NULL ) { XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync); XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync); for(;;) { XNextEvent(d, &event); if ( event.type == KeyPress ) { KeySym s = XLookupKeysym(&event.xkey, 0); if ( s == XK_F7 ) { printf("something's happened\n"); } else if ( s == XK_F6 ) { break; } } } XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d)); XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d)); } return EXIT_SUCCESS; }
package main import "C" import "fmt" import "unsafe" func main() { d := C.XOpenDisplay(nil) f7, f6 := C.CString("F7"), C.CString("F6") defer C.free(unsafe.Pointer(f7)) defer C.free(unsafe.Pointer(f6)) if d != nil { C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync) var event C.XEvent for { C.XNextEvent(d, &event) if C.getXEvent_type(event) == C.KeyPress { xkeyEvent := C.getXEvent_xkey(event) s := C.XLookupKeysym(&xkeyEvent, 0) if s == C.XK_F7 { fmt.Println("something's happened") } else if s == C.XK_F6 { break } } } C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d)) } else { fmt.Println("XOpenDisplay did not succeed") } }
Change the following C code into Go without altering its purpose.
#include <stdio.h> int main() { int max = 0, i = 0, sixes, nines, twenties; loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; } for (nines = 0; nines*9 < i; nines++) { if (sixes*6 + nines*9 == i) { i++; goto loopstart; } for (twenties = 0; twenties*20 < i; twenties++) { if (sixes*6 + nines*9 + twenties*20 == i) { i++; goto loopstart; } } } } max = i; i++; } printf("Maximum non-McNuggets number is %d\n", max); return 0; }
package main import "fmt" func mcnugget(limit int) { sv := make([]bool, limit+1) for s := 0; s <= limit; s += 6 { for n := s; n <= limit; n += 9 { for t := n; t <= limit; t += 20 { sv[t] = true } } } for i := limit; i >= 0; i-- { if !sv[i] { fmt.Println("Maximum non-McNuggets number is", i) return } } } func main() { mcnugget(100) }
Generate an equivalent Go version of this C code.
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** doublyEvenMagicSquare(int n) { if (n < 4 || n % 4 != 0) return NULL; int bits = 38505; int size = n * n; int mult = n / 4,i,r,c,bitPos; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (r = 0, i = 0; r < n; r++) { for (c = 0; c < n; c++, i++) { bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j,baseWidth = numDigits(rows*rows) + 3; printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2); for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf("Usage : %s <integer specifying rows in magic square>",argV[0]); else{ n = atoi(argV[1]); printMagicSquare(doublyEvenMagicSquare(n),n); } return 0; }
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
package main import ( "fmt" "math" ) func main() { var zero float64 var negZero, posInf, negInf, nan float64 negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero fmt.Println(negZero, posInf, negInf, nan) fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN()) fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") } func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } } func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } } func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } } func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } } func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
Translate the given C code snippet into Go without altering its behavior.
#include <math.h> #include <stdint.h> #include <stdio.h> static uint64_t state; static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D; void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x >> 27); state = x; answer = ((x * STATE_MAGIC) >> 32); return answer; } float next_float() { return (float)next_int() / (1LL << 32); } int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i; seed(1234567); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("\n"); seed(987654321); for (i = 0; i < 100000; i++) { int j = (int)floor(next_float() * 5.0); counts[j]++; } for (i = 0; i < 5; i++) { printf("%d: %d\n", i, counts[i]); } return 0; }
package main import ( "fmt" "math" ) const CONST = 0x2545F4914F6CDD1D type XorshiftStar struct{ state uint64 } func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} } func (xor *XorshiftStar) seed(state uint64) { xor.state = state } func (xor *XorshiftStar) nextInt() uint32 { x := xor.state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) xor.state = x return uint32((x * CONST) >> 32) } func (xor *XorshiftStar) nextFloat() float64 { return float64(xor.nextInt()) / (1 << 32) } func main() { randomGen := XorshiftStarNew(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
Convert the following code from C to Go, ensuring the logic remains intact.
#include <ctype.h> #include <locale.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <glib.h> typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "biliionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } typedef struct word_tag { size_t offset; size_t length; } word_t; typedef struct word_list_tag { GArray* words; GString* str; } word_list; void word_list_create(word_list* words) { words->words = g_array_new(FALSE, FALSE, sizeof(word_t)); words->str = g_string_new(NULL); } void word_list_destroy(word_list* words) { g_string_free(words->str, TRUE); g_array_free(words->words, TRUE); } void word_list_clear(word_list* words) { g_string_truncate(words->str, 0); g_array_set_size(words->words, 0); } void word_list_append(word_list* words, const char* str) { size_t offset = words->str->len; size_t len = strlen(str); g_string_append_len(words->str, str, len); word_t word; word.offset = offset; word.length = len; g_array_append_val(words->words, word); } word_t* word_list_get(word_list* words, size_t index) { return &g_array_index(words->words, word_t, index); } void word_list_extend(word_list* words, const char* str) { word_t* word = word_list_get(words, words->words->len - 1); size_t len = strlen(str); word->length += len; g_string_append_len(words->str, str, len); } size_t append_number_name(word_list* words, integer n, bool ordinal) { size_t count = 0; if (n < 20) { word_list_append(words, get_small_name(&small[n], ordinal)); count = 1; } else if (n < 100) { if (n % 10 == 0) { word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal)); } else { word_list_append(words, get_small_name(&tens[n/10 - 2], false)); word_list_extend(words, "-"); word_list_extend(words, get_small_name(&small[n % 10], ordinal)); } count = 1; } else { const named_number* num = get_named_number(n); integer p = num->number; count += append_number_name(words, n/p, false); if (n % p == 0) { word_list_append(words, get_big_name(num, ordinal)); ++count; } else { word_list_append(words, get_big_name(num, false)); ++count; count += append_number_name(words, n % p, ordinal); } } return count; } size_t count_letters(word_list* words, size_t index) { const word_t* word = word_list_get(words, index); size_t letters = 0; const char* s = words->str->str + word->offset; for (size_t i = 0, n = word->length; i < n; ++i) { if (isalpha((unsigned char)s[i])) ++letters; } return letters; } void sentence(word_list* result, size_t count) { static const char* words[] = { "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence," }; word_list_clear(result); size_t n = sizeof(words)/sizeof(words[0]); for (size_t i = 0; i < n; ++i) word_list_append(result, words[i]); for (size_t i = 1; count > n; ++i) { n += append_number_name(result, count_letters(result, i), false); word_list_append(result, "in"); word_list_append(result, "the"); n += 2; n += append_number_name(result, i + 1, true); word_list_extend(result, ","); } } size_t sentence_length(const word_list* words) { size_t n = words->words->len; if (n == 0) return 0; return words->str->len + n - 1; } int main() { setlocale(LC_ALL, ""); size_t n = 201; word_list result = { 0 }; word_list_create(&result); sentence(&result, n); printf("Number of letters in first %'lu words in the sequence:\n", n); for (size_t i = 0; i < n; ++i) { if (i != 0) printf("%c", i % 25 == 0 ? '\n' : ' '); printf("%'2lu", count_letters(&result, i)); } printf("\nSentence length: %'lu\n", sentence_length(&result)); for (n = 1000; n <= 10000000; n *= 10) { sentence(&result, n); const word_t* word = word_list_get(&result, n - 1); const char* s = result.str->str + word->offset; printf("The %'luth word is '%.*s' and has %lu letters. ", n, (int)word->length, s, count_letters(&result, n - 1)); printf("Sentence length: %'lu\n" , sentence_length(&result)); } word_list_destroy(&result); return 0; }
package main import ( "fmt" "strings" "unicode" ) func main() { f := NewFourIsSeq() fmt.Print("The lengths of the first 201 words are:") for i := 1; i <= 201; i++ { if i%25 == 1 { fmt.Printf("\n%3d: ", i) } _, n := f.WordLen(i) fmt.Printf(" %2d", n) } fmt.Println() fmt.Println("Length of sentence so far:", f.TotalLength()) for i := 1000; i <= 1e7; i *= 10 { w, n := f.WordLen(i) fmt.Printf("Word %8d is %q, with %d letters.", i, w, n) fmt.Println(" Length of sentence so far:", f.TotalLength()) } } type FourIsSeq struct { i int words []string } func NewFourIsSeq() *FourIsSeq { return &FourIsSeq{ words: []string{ "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence,", }, } } func (f *FourIsSeq) WordLen(w int) (string, int) { for len(f.words) < w { f.i++ n := countLetters(f.words[f.i]) ns := say(int64(n)) os := sayOrdinal(int64(f.i+1)) + "," f.words = append(f.words, strings.Fields(ns)...) f.words = append(f.words, "in", "the") f.words = append(f.words, strings.Fields(os)...) } word := f.words[w-1] return word, countLetters(word) } func (f FourIsSeq) TotalLength() int { cnt := 0 for _, w := range f.words { cnt += len(w) + 1 } return cnt - 1 } func countLetters(s string) int { cnt := 0 for _, r := range s { if unicode.IsLetter(r) { cnt++ } } return cnt }
Preserve the algorithm and functionality while converting the code from C to Go.
INT PUTCHAR(INT); INT WIDTH = 80, YEAR = 1969; INT COLS, LEAD, GAP; CONST CHAR *WDAYS[] = { "SU", "MO", "TU", "WE", "TH", "FR", "SA" }; STRUCT MONTHS { CONST CHAR *NAME; INT DAYS, START_WDAY, AT; } MONTHS[12] = { { "JANUARY", 31, 0, 0 }, { "FEBRUARY", 28, 0, 0 }, { "MARCH", 31, 0, 0 }, { "APRIL", 30, 0, 0 }, { "MAY", 31, 0, 0 }, { "JUNE", 30, 0, 0 }, { "JULY", 31, 0, 0 }, { "AUGUST", 31, 0, 0 }, { "SEPTEMBER", 30, 0, 0 }, { "OCTOBER", 31, 0, 0 }, { "NOVEMBER", 30, 0, 0 }, { "DECEMBER", 31, 0, 0 } }; VOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); } VOID PRINT(CONST CHAR * S){ WHILE (*S != '\0') { PUTCHAR(*S++); } } INT STRLEN(CONST CHAR * S) { INT L = 0; WHILE (*S++ != '\0') { L ++; }; RETURN L; } INT ATOI(CONST CHAR * S) { INT I = 0; INT SIGN = 1; CHAR C; WHILE ((C = *S++) != '\0') { IF (C == '-') SIGN *= -1; ELSE { I *= 10; I += (C - '0'); } } RETURN I * SIGN; } VOID INIT_MONTHS(VOID) { INT I; IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400)) MONTHS[1].DAYS = 29; YEAR--; MONTHS[0].START_WDAY = (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7; FOR (I = 1; I < 12; I++) MONTHS[I].START_WDAY = (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7; COLS = (WIDTH + 2) / 22; WHILE (12 % COLS) COLS--; GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0; IF (GAP > 4) GAP = 4; LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2; YEAR++; } VOID PRINT_ROW(INT ROW) { INT C, I, FROM = ROW * COLS, TO = FROM + COLS; SPACE(LEAD); FOR (C = FROM; C < TO; C++) { I = STRLEN(MONTHS[C].NAME); SPACE((20 - I)/2); PRINT(MONTHS[C].NAME); SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP)); } PUTCHAR('\012'); SPACE(LEAD); FOR (C = FROM; C < TO; C++) { FOR (I = 0; I < 7; I++) { PRINT(WDAYS[I]); PRINT(I == 6 ? "" : " "); } IF (C < TO - 1) SPACE(GAP); ELSE PUTCHAR('\012'); } WHILE (1) { FOR (C = FROM; C < TO; C++) IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK; IF (C == TO) BREAK; SPACE(LEAD); FOR (C = FROM; C < TO; C++) { FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3); WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) { INT MM = ++MONTHS[C].AT; PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10)); PUTCHAR('0' + (MM %10)); IF (I < 7 || C < TO - 1) PUTCHAR(' '); } WHILE (I++ <= 7 && C < TO - 1) SPACE(3); IF (C < TO - 1) SPACE(GAP - 1); MONTHS[C].START_WDAY = 0; } PUTCHAR('\012'); } PUTCHAR('\012'); } VOID PRINT_YEAR(VOID) { INT Y = YEAR; INT ROW; CHAR BUF[32]; CHAR * B = &(BUF[31]); *B-- = '\0'; DO { *B-- = '0' + (Y % 10); Y /= 10; } WHILE (Y > 0); B++; SPACE((WIDTH - STRLEN(B)) / 2); PRINT(B);PUTCHAR('\012');PUTCHAR('\012'); FOR (ROW = 0; ROW * COLS < 12; ROW++) PRINT_ROW(ROW); } INT MAIN(INT C, CHAR **V) { INT I, YEAR_SET = 0, RESULT = 0; FOR (I = 1; I < C && RESULT == 0; I++) { IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\0') { IF (++I == C || (WIDTH = ATOI(V[I])) < 20) RESULT = 1; } ELSE IF (!YEAR_SET) { YEAR = ATOI(V[I]); IF (YEAR <= 0) YEAR = 1969; YEAR_SET = 1; } ELSE RESULT = 1; } IF (RESULT == 0) { INIT_MONTHS(); PRINT_YEAR(); } ELSE { PRINT("BAD ARGS\012USAGE: "); PRINT(V[0]); PRINT(" YEAR [-W WIDTH (>= 20)]\012"); } RETURN RESULT; }
PACKAGE MAIN IMPORT ( "FMT" "TIME" ) CONST PAGEWIDTH = 80 FUNC MAIN() { PRINTCAL(1969) } FUNC PRINTCAL(YEAR INT) { THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC) VAR ( DAYARR [12][7][6]INT MONTH, LASTMONTH TIME.MONTH WEEKINMONTH, DAYINMONTH INT ) FOR THISDATE.YEAR() == YEAR { IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH { WEEKINMONTH = 0 DAYINMONTH = 1 } WEEKDAY := THISDATE.WEEKDAY() IF WEEKDAY == 0 && DAYINMONTH > 1 { WEEKINMONTH++ } DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY() LASTMONTH = MONTH DAYINMONTH++ THISDATE = THISDATE.ADD(TIME.HOUR * 24) } CENTRE := FMT.SPRINTF("%D", PAGEWIDTH/2) FMT.PRINTF("%"+CENTRE+"S\N\N", "[SNOOPY]") CENTRE = FMT.SPRINTF("%D", PAGEWIDTH/2-2) FMT.PRINTF("%"+CENTRE+"D\N\N", YEAR) MONTHS := [12]STRING{ " JANUARY ", " FEBRUARY", " MARCH ", " APRIL ", " MAY ", " JUNE ", " JULY ", " AUGUST ", "SEPTEMBER", " OCTOBER ", " NOVEMBER", " DECEMBER"} DAYS := [7]STRING{"SU", "MO", "TU", "WE", "TH", "FR", "SA"} FOR QTR := 0; QTR < 4; QTR++ { FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FMT.PRINTF(" %S ", MONTHS[QTR*3+MONTHINQTR]) } FMT.PRINTLN() FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FOR DAY := 0; DAY < 7; DAY++ { FMT.PRINTF(" %S", DAYS[DAY]) } FMT.PRINTF(" ") } FMT.PRINTLN() FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ { FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { FOR DAY := 0; DAY < 7; DAY++ { IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 { FMT.PRINTF(" ") } ELSE { FMT.PRINTF("%3D", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH]) } } FMT.PRINTF(" ") } FMT.PRINTLN() } FMT.PRINTLN() } }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdlib.h> #include <stdio.h> #include <string.h> enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ID |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | QDCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ANCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | NSCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ARCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf("Extract meta-data from bit-encoded text form\n"); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; } dump_names(); } int bit_hdr(char *pLine){ char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; int k=0; for(int j=0; j<sz;j++){ if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ NAME_T *pn; printf("-name-bits-mask-data-\n"); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data); } puts("bye.."); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; header[BITS] = 0xB50A; }
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { var lines []string for _, line := range strings.Split(diagram, "\n") { line = strings.Trim(line, " \t") if line != "" { lines = append(lines, line) } } if len(lines) == 0 { log.Fatal("diagram has no non-empty lines!") } width := len(lines[0]) cols := (width - 1) / 3 if cols != 8 && cols != 16 && cols != 32 && cols != 64 { log.Fatal("number of columns should be 8, 16, 32 or 64") } if len(lines)%2 == 0 { log.Fatal("number of non-empty lines should be odd") } if lines[0] != strings.Repeat("+--", cols)+"+" { log.Fatal("incorrect header line") } for i, line := range lines { if i == 0 { continue } else if i%2 == 0 { if line != lines[0] { log.Fatal("incorrect separator line") } } else if len(line) != width { log.Fatal("inconsistent line widths") } else if line[0] != '|' || line[width-1] != '|' { log.Fatal("non-separator lines must begin and end with '|'") } } return lines } func decode(lines []string) []result { fmt.Println("Name Bits Start End") fmt.Println("======= ==== ===== ===") start := 0 width := len(lines[0]) var results []result for i, line := range lines { if i%2 == 0 { continue } line := line[1 : width-1] for _, name := range strings.Split(line, "|") { size := (len(name) + 1) / 3 name = strings.TrimSpace(name) res := result{name, size, start, start + size - 1} results = append(results, res) fmt.Println(res) start += size } } return results } func unpack(results []result, hex string) { fmt.Println("\nTest string in hex:") fmt.Println(hex) fmt.Println("\nTest string in binary:") bin := hex2bin(hex) fmt.Println(bin) fmt.Println("\nUnpacked:\n") fmt.Println("Name Size Bit pattern") fmt.Println("======= ==== ================") for _, res := range results { fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1]) } } func hex2bin(hex string) string { z := new(big.Int) z.SetString(hex, 16) return fmt.Sprintf("%0*b", 4*len(hex), z) } func main() { const diagram = ` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ` lines := validate(diagram) fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n") for _, line := range lines { fmt.Println(line) } fmt.Println("\nDecoded:\n") results := decode(lines) hex := "78477bbf5496e12e1bf169a4" unpack(results, hex) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t)); for (i = 1; i <= la; i++) tbl[i] = tbl[i-1] + (1+lb); for (i = la; i >= 0; i--) { char *aa = a + i; for (j = lb; j >= 0; j--) { char *bb = b + j; if (!*aa && !*bb) continue; edit e = &tbl[i][j]; edit repl = &tbl[i+1][j+1]; edit dela = &tbl[i+1][j]; edit delb = &tbl[i][j+1]; e->c1 = *aa; e->c2 = *bb; if (!*aa) { e->next = delb; e->n = e->next->n + 1; continue; } if (!*bb) { e->next = dela; e->n = e->next->n + 1; continue; } e->next = repl; if (*aa == *bb) { e->n = e->next->n; continue; } if (e->next->n > delb->n) { e->next = delb; e->c1 = 0; } if (e->next->n > dela->n) { e->next = dela; e->c1 = *aa; e->c2 = 0; } e->n = e->next->n + 1; } } edit p = tbl[0]; printf("%s -> %s: %d edits\n", a, b, p->n); while (p->next) { if (p->c1 == p->c2) printf("%c", p->c1); else { putchar('('); if (p->c1) putchar(p->c1); putchar(','); if (p->c2) putchar(p->c2); putchar(')'); } p = p->next; } putchar('\n'); free(tbl[0]); free(tbl); } int main(void) { leven("raisethysword", "rosettacode"); return 0; }
package main import ( "fmt" "github.com/biogo/biogo/align" ab "github.com/biogo/biogo/alphabet" "github.com/biogo/biogo/feat" "github.com/biogo/biogo/seq/linear" ) func main() { lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz", feat.Undefined, '-', 0, true)) nw := make(align.NW, lc.Len()) for i := range nw { r := make([]int, lc.Len()) nw[i] = r for j := range r { if j != i { r[j] = -1 } } } a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))} a.Alpha = lc b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))} b.Alpha = lc aln, err := nw.Align(a, b) if err != nil { fmt.Println(err) return } fa := align.Format(a, b, aln, '-') fmt.Printf("%s\n%s\n", fa[0], fa[1]) aa := fmt.Sprint(fa[0]) ba := fmt.Sprint(fa[1]) ma := make([]byte, len(aa)) for i := range ma { if aa[i] == ba[i] { ma[i] = ' ' } else { ma[i] = '|' } } fmt.Println(string(ma)) }
Translate this program into Go but keep the logic exactly as in C.
#ifndef _CSEQUENCE_H #define _CSEQUENCE_H #include <stdlib.h> void setfillconst(double c); void fillwithconst(double *v, int n); void fillwithrrange(double *v, int n); void shuffledrange(double *v, int n); #endif
package main import ( "log" "math/rand" "testing" "time" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/plotutil" "github.com/gonum/plot/vg" ) func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } } func insertionsort(a []int) { for i := 1; i < len(a); i++ { value := a[i] j := i - 1 for j >= 0 && a[j] > value { a[j+1] = a[j] j = j - 1 } a[j+1] = value } } func quicksort(a []int) { var pex func(int, int) pex = func(lower, upper int) { for { switch upper - lower { case -1, 0: return case 1: if a[upper] < a[lower] { a[upper], a[lower] = a[lower], a[upper] } return } bx := (upper + lower) / 2 b := a[bx] lp := lower up := upper outer: for { for lp < upper && !(b < a[lp]) { lp++ } for { if lp > up { break outer } if a[up] < b { break } up-- } a[lp], a[up] = a[up], a[lp] lp++ up-- } if bx < lp { if bx < lp-1 { a[bx], a[lp-1] = a[lp-1], b } up = lp - 2 } else { if bx > lp { a[bx], a[lp] = a[lp], b } up = lp - 1 lp++ } if up-lower < upper-lp { pex(lower, up) lower = lp } else { pex(lp, upper) upper = up } } } pex(0, len(a)-1) } func ones(n int) []int { s := make([]int, n) for i := range s { s[i] = 1 } return s } func ascending(n int) []int { s := make([]int, n) v := 1 for i := 0; i < n; { if rand.Intn(3) == 0 { s[i] = v i++ } v++ } return s } func shuffled(n int) []int { return rand.Perm(n) } const ( nPts = 7 inc = 1000 ) var ( p *plot.Plot sortName = []string{"Bubble sort", "Insertion sort", "Quicksort"} sortFunc = []func([]int){bubblesort, insertionsort, quicksort} dataName = []string{"Ones", "Ascending", "Shuffled"} dataFunc = []func(int) []int{ones, ascending, shuffled} ) func main() { rand.Seed(time.Now().Unix()) var err error p, err = plot.New() if err != nil { log.Fatal(err) } p.X.Label.Text = "Data size" p.Y.Label.Text = "microseconds" p.Y.Scale = plot.LogScale{} p.Y.Tick.Marker = plot.LogTicks{} p.Y.Min = .5 for dx, name := range dataName { s, err := plotter.NewScatter(plotter.XYs{}) if err != nil { log.Fatal(err) } s.Shape = plotutil.DefaultGlyphShapes[dx] p.Legend.Add(name, s) } for sx, name := range sortName { l, err := plotter.NewLine(plotter.XYs{}) if err != nil { log.Fatal(err) } l.Color = plotutil.DarkColors[sx] p.Legend.Add(name, l) } for sx := range sortFunc { bench(sx, 0, 1) bench(sx, 1, 5) bench(sx, 2, 5) } if err := p.Save(5*vg.Inch, 5*vg.Inch, "comp.png"); err != nil { log.Fatal(err) } } func bench(sx, dx, rep int) { log.Println("bench", sortName[sx], dataName[dx], "x", rep) pts := make(plotter.XYs, nPts) sf := sortFunc[sx] for i := range pts { x := (i + 1) * inc s0 := dataFunc[dx](x) s := make([]int, x) var tSort int64 for j := 0; j < rep; j++ { tSort += testing.Benchmark(func(b *testing.B) { for i := 0; i < b.N; i++ { copy(s, s0) sf(s) } }).NsPerOp() } tSort /= int64(rep) log.Println(x, "items", tSort, "ns") pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001} } pl, ps, err := plotter.NewLinePoints(pts) if err != nil { log.Fatal(err) } pl.Color = plotutil.DarkColors[sx] ps.Color = plotutil.DarkColors[sx] ps.Shape = plotutil.DefaultGlyphShapes[dx] p.Add(pl, ps) }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <ucontext.h> typedef struct { ucontext_t caller, callee; char stack[8192]; void *in, *out; } co_t; co_t * co_new(void(*f)(), void *data) { co_t * c = malloc(sizeof(*c)); getcontext(&c->callee); c->in = data; c->callee.uc_stack.ss_sp = c->stack; c->callee.uc_stack.ss_size = sizeof(c->stack); c->callee.uc_link = &c->caller; makecontext(&c->callee, f, 1, (int)c); return c; } void co_del(co_t *c) { free(c); } inline void co_yield(co_t *c, void *data) { c->out = data; swapcontext(&c->callee, &c->caller); } inline void * co_collect(co_t *c) { c->out = 0; swapcontext(&c->caller, &c->callee); return c->out; } typedef struct node node; struct node { int v; node *left, *right; }; node *newnode(int v) { node *n = malloc(sizeof(node)); n->left = n->right = 0; n->v = v; return n; } void tree_insert(node **root, node *n) { while (*root) root = ((*root)->v > n->v) ? &(*root)->left : &(*root)->right; *root = n; } void tree_trav(int x) { co_t *c = (co_t *) x; void trav(node *root) { if (!root) return; trav(root->left); co_yield(c, root); trav(root->right); } trav(c->in); } int tree_eq(node *t1, node *t2) { co_t *c1 = co_new(tree_trav, t1); co_t *c2 = co_new(tree_trav, t2); node *p = 0, *q = 0; do { p = co_collect(c1); q = co_collect(c2); } while (p && q && (p->v == q->v)); co_del(c1); co_del(c2); return !p && !q; } int main() { int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 }; int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 }; int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 }; node *t1 = 0, *t2 = 0, *t3 = 0; void mktree(int *buf, node **root) { int i; for (i = 0; buf[i] >= 0; i++) tree_insert(root, newnode(buf[i])); } mktree(x, &t1); mktree(y, &t2); mktree(z, &t3); printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no"); printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no"); return 0; }
package main import "fmt" type node struct { int left, right *node } func leaves(t *node) chan int { ch := make(chan int) var f func(*node) f = func(n *node) { if n == nil { return } if n.left == nil && n.right == nil { ch <- n.int } else { f(n.left) f(n.right) } } go func() { f(t) close(ch) }() return ch } func sameFringe(t1, t2 *node) bool { f1 := leaves(t1) f2 := leaves(t2) for l1 := range f1 { if l2, ok := <-f2; !ok || l1 != l2 { return false } } _, ok := <-f2 return !ok } func main() { t1 := &node{3, &node{1, &node{int: 1}, &node{int: 2}}, &node{8, &node{int: 5}, &node{int: 13}}} t2 := &node{-8, &node{-3, &node{-1, &node{int: 1}, &node{int: 2}}, &node{int: 5}}, &node{int: 13}} fmt.Println(sameFringe(t1, t2)) }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdio.h> int main(int argc, char **argv){ int i; const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; enum {CREATE,PRINT,TITLE,DATE,AUTH}; if (argc<2) { usage: printf ("Usage: %s [commands]\n" "-c Create new entry.\n" "-p Print the latest entry.\n" "-t Sort by title.\n" "-d Sort by date.\n" "-a Sort by author.\n",argv[0]); return 0; } for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); switch (i) { case CREATE: ... break; case PRINT: ... break; ... ... default: printf ("Unknown command..." ...); goto usage; } return 0; }
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> int main(int argc, char **argv){ int i; const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; enum {CREATE,PRINT,TITLE,DATE,AUTH}; if (argc<2) { usage: printf ("Usage: %s [commands]\n" "-c Create new entry.\n" "-p Print the latest entry.\n" "-t Sort by title.\n" "-d Sort by date.\n" "-a Sort by author.\n",argv[0]); return 0; } for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); switch (i) { case CREATE: ... break; case PRINT: ... break; ... ... default: printf ("Unknown command..." ...); goto usage; } return 0; }
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdint.h> uint64_t ones_plus_three(uint64_t ones) { uint64_t r = 0; while (ones--) r = r*10 + 1; return r*10 + 3; } int main() { uint64_t n; for (n=0; n<8; n++) { uint64_t x = ones_plus_three(n); printf("%8lu^2 = %15lu\n", x, x*x); } return 0; }
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <stdint.h> uint64_t ones_plus_three(uint64_t ones) { uint64_t r = 0; while (ones--) r = r*10 + 1; return r*10 + 3; } int main() { uint64_t n; for (n=0; n<8; n++) { uint64_t x = ones_plus_three(n); printf("%8lu^2 = %15lu\n", x, x*x); } return 0; }
package main import ( "fmt" "strconv" "strings" ) func a(n int) { s, _ := strconv.Atoi(strings.Repeat("1", n) + "3") t := s * s fmt.Printf("%d %d\n", s, t) } func main() { for n := 0; n <= 7; n++ { a(n) } }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/Xutil.h> int main(int argc, char *argv[]) { Display *dpy; Window win; GC gc; int scr; Atom WM_DELETE_WINDOW; XEvent ev; XEvent ev2; KeySym keysym; int loop; dpy = XOpenDisplay(NULL); if (dpy == NULL) { fputs("Cannot open display", stderr); exit(1); } scr = XDefaultScreen(dpy); win = XCreateSimpleWindow(dpy, XRootWindow(dpy, scr), 10, 10, 300, 200, 1, XBlackPixel(dpy, scr), XWhitePixel(dpy, scr)); XStoreName(dpy, win, argv[0]); XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask); XMapWindow(dpy, win); XFlush(dpy); gc = XDefaultGC(dpy, scr); WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True); XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1); loop = 1; while (loop) { XNextEvent(dpy, &ev); switch (ev.type) { case Expose: { char msg1[] = "Clic in the window to generate"; char msg2[] = "a key press event"; XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1); XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1); } break; case ButtonPress: puts("ButtonPress event received"); ev2.type = KeyPress; ev2.xkey.state = ShiftMask; ev2.xkey.keycode = 24 + (rand() % 33); ev2.xkey.same_screen = True; XSendEvent(dpy, win, True, KeyPressMask, &ev2); break; case ClientMessage: if (ev.xclient.data.l[0] == WM_DELETE_WINDOW) loop = 0; break; case KeyPress: puts("KeyPress event received"); printf("> keycode: %d\n", ev.xkey.keycode); keysym = XLookupKeysym(&(ev.xkey), 0); if (keysym == XK_q || keysym == XK_Escape) { loop = 0; } else { char buffer[] = " "; int nchars = XLookupString( &(ev.xkey), buffer, 2, &keysym, NULL ); if (nchars == 1) printf("> Key '%c' pressed\n", buffer[0]); } break; } } XDestroyWindow(dpy, win); XCloseDisplay(dpy); return 1; }
package main import ( "github.com/micmonay/keybd_event" "log" "runtime" "time" ) func main() { kb, err := keybd_event.NewKeyBonding() if err != nil { log.Fatal(err) } if runtime.GOOS == "linux" { time.Sleep(2 * time.Second) } kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER) err = kb.Launching() if err != nil { log.Fatal(err) } }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> enum Piece { Empty, Black, White, }; typedef struct Position_t { int x, y; } Position; struct Node_t { Position pos; struct Node_t *next; }; void releaseNode(struct Node_t *head) { if (head == NULL) return; releaseNode(head->next); head->next = NULL; free(head); } typedef struct List_t { struct Node_t *head; struct Node_t *tail; size_t length; } List; List makeList() { return (List) { NULL, NULL, 0 }; } void releaseList(List *lst) { if (lst == NULL) return; releaseNode(lst->head); lst->head = NULL; lst->tail = NULL; } void addNode(List *lst, Position pos) { struct Node_t *newNode; if (lst == NULL) { exit(EXIT_FAILURE); } newNode = malloc(sizeof(struct Node_t)); if (newNode == NULL) { exit(EXIT_FAILURE); } newNode->next = NULL; newNode->pos = pos; if (lst->head == NULL) { lst->head = lst->tail = newNode; } else { lst->tail->next = newNode; lst->tail = newNode; } lst->length++; } void removeAt(List *lst, size_t pos) { if (lst == NULL) return; if (pos == 0) { struct Node_t *temp = lst->head; if (lst->tail == lst->head) { lst->tail = NULL; } lst->head = lst->head->next; temp->next = NULL; free(temp); lst->length--; } else { struct Node_t *temp = lst->head; struct Node_t *rem; size_t i = pos; while (i-- > 1) { temp = temp->next; } rem = temp->next; if (rem == lst->tail) { lst->tail = temp; } temp->next = rem->next; rem->next = NULL; free(rem); lst->length--; } } bool isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || abs(queen.x - pos.x) == abs(queen.y - pos.y); } bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) { struct Node_t *queenNode; bool placingBlack = true; int i, j; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } if (m == 0) return true; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Position pos = { i, j }; queenNode = pBlackQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } if (placingBlack) { addNode(pBlackQueens, pos); placingBlack = false; } else { addNode(pWhiteQueens, pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } removeAt(pBlackQueens, pBlackQueens->length - 1); removeAt(pWhiteQueens, pWhiteQueens->length - 1); placingBlack = true; } inner: {} } } if (!placingBlack) { removeAt(pBlackQueens, pBlackQueens->length - 1); } return false; } void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) { size_t length = n * n; struct Node_t *queenNode; char *board; size_t i, j, k; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } board = calloc(length, sizeof(char)); if (board == NULL) { exit(EXIT_FAILURE); } queenNode = pBlackQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = Black; queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = White; queenNode = queenNode->next; } for (i = 0; i < length; i++) { if (i != 0 && i % n == 0) { printf("\n"); } switch (board[i]) { case Black: printf("B "); break; case White: printf("W "); break; default: j = i / n; k = i - j * n; if (j % 2 == k % 2) { printf(" "); } else { printf("# "); } break; } } printf("\n\n"); } void test(int n, int q) { List blackQueens = makeList(); List whiteQueens = makeList(); printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n); if (place(q, n, &blackQueens, &whiteQueens)) { printBoard(n, &blackQueens, &whiteQueens); } else { printf("No solution exists.\n\n"); } releaseList(&blackQueens); releaseList(&whiteQueens); } int main() { test(2, 1); test(3, 1); test(3, 2); test(4, 1); test(4, 2); test(4, 3); test(5, 1); test(5, 2); test(5, 3); test(5, 4); test(5, 5); test(6, 1); test(6, 2); test(6, 3); test(6, 4); test(6, 5); test(6, 6); test(7, 1); test(7, 2); test(7, 3); test(7, 4); test(7, 5); test(7, 6); test(7, 7); return EXIT_SUCCESS; }
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false } func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false } func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white } for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") } func main() { nms := [][2]int{ {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, } for _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.Println("No solution exists.\n") } } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
while(1) puts("SPAM");
package main import "fmt" func main() { for { fmt.Printf("SPAM\n") } }
Change the following C code into Go without altering its purpose.
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1] #define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L) #define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L) #define COMPILE_TIME_ASSERT(X) COMPILE_TIME_ASSERT2(X,__LINE__) COMPILE_TIME_ASSERT(sizeof(long)==8); int main() { COMPILE_TIME_ASSERT(sizeof(int)==4); }
package main import "fmt" type person struct{ name string age int } func copy(p person) person { return person{p.name, p.age} } func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> #define LIMIT 100000 int digitset(int num, int base) { int set; for (set = 0; num; num /= base) set |= 1 << num % base; return set; } int main() { int i, c = 0; for (i = 0; i < LIMIT; i++) if (digitset(i,10) == digitset(i,16)) printf("%6d%c", i, ++c%10 ? ' ' : '\n'); printf("\n"); return 0; }
package main import ( "fmt" "rcu" "strconv" ) func equalSets(s1, s2 map[rune]bool) bool { if len(s1) != len(s2) { return false } for k, _ := range s1 { _, ok := s2[k] if !ok { return false } } return true } func main() { const limit = 100_000 count := 0 fmt.Println("Numbers under 100,000 which use the same digits in decimal or hex:") for n := 0; n < limit; n++ { h := strconv.FormatInt(int64(n), 16) hs := make(map[rune]bool) for _, c := range h { hs[c] = true } ns := make(map[rune]bool) for _, c := range strconv.Itoa(n) { ns[c] = true } if equalSets(hs, ns) { count++ fmt.Printf("%6s ", rcu.Commatize(n)) if count%10 == 0 { fmt.Println() } } } fmt.Printf("\n\n%d such numbers found.\n", count) }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> int isprime( long int n ) { int i=3; if(!(n%2)) return 0; while( i*i < n ) { if(!(n%i)) return 0; i+=2; } return 1; } int main(void) { long int n=600851475143, j=3; while(!isprime(n)) { if(!(n%j)) n/=j; j+=2; } printf( "%ld\n", n ); return 0; }
package main import "fmt" func largestPrimeFactor(n uint64) uint64 { if n < 2 { return 1 } inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6} max := uint64(1) for n%2 == 0 { max = 2 n /= 2 } for n%3 == 0 { max = 3 n /= 3 } for n%5 == 0 { max = 5 n /= 5 } k := uint64(7) i := 0 for k*k <= n { if n%k == 0 { max = k n /= k } else { k += inc[i] i = (i + 1) % 8 } } if n > 1 { return n } return max } func main() { n := uint64(600851475143) fmt.Println("The largest prime factor of", n, "is", largestPrimeFactor(n), "\b.") }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> unsigned int lpd(unsigned int n) { if (n<=1) return 1; int i; for (i=n-1; i>0; i--) if (n%i == 0) return i; } int main() { int i; for (i=1; i<=100; i++) { printf("%3d", lpd(i)); if (i % 10 == 0) printf("\n"); } return 0; }
package main import "fmt" func largestProperDivisor(n int) int { for i := 2; i*i <= n; i++ { if n%i == 0 { return n / i } } return 1 } func main() { fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:") fmt.Print(" 1 ") for n := 2; n <= 100; n++ { if n%2 == 0 { fmt.Printf("%2d ", n/2) } else { fmt.Printf("%2d ", largestProperDivisor(n)) } if n%10 == 0 { fmt.Println() } } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> typedef long long int64; void to_word(char *ws, int64 w) { sprintf(ws, "W%05lld", w); } int64 from_word(char *ws) { return atoi(++ws); } int main() { double lat, lon; int64 latlon, ilat, ilon, w1, w2, w3; char w1s[7], w2s[7], w3s[7]; printf("Starting figures:\n"); lat = 28.3852; lon = -81.5638; printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon); ilat = (int64)(lat*10000 + 900000); ilon = (int64)(lon*10000 + 1800000); latlon = (ilat << 22) + ilon; w1 = (latlon >> 28) & 0x7fff; w2 = (latlon >> 14) & 0x3fff; w3 = latlon & 0x3fff; to_word(w1s, w1); to_word(w2s, w2); to_word(w3s, w3); printf("\nThree word location is:\n"); printf(" %s %s %s\n", w1s, w2s, w3s); w1 = from_word(w1s); w2 = from_word(w2s); w3 = from_word(w3s); latlon = (w1 << 28) | (w2 << 14) | w3; ilat = latlon >> 22; ilon = latlon & 0x3fffff; lat = (double)(ilat-900000) / 10000; lon = (double)(ilon-1800000) / 10000; printf("\nAfter reversing the procedure:\n"); printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon); return 0; }
package main import ( "fmt" "strconv" ) func toWord(w int64) string { return fmt.Sprintf("W%05d", w) } func fromWord(ws string) int64 { var u, _ = strconv.ParseUint(ws[1:], 10, 64) return int64(u) } func main() { fmt.Println("Starting figures:") lat := 28.3852 lon := -81.5638 fmt.Printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon) ilat := int64(lat*10000 + 900000) ilon := int64(lon*10000 + 1800000) latlon := (ilat << 22) + ilon w1 := (latlon >> 28) & 0x7fff w2 := (latlon >> 14) & 0x3fff w3 := latlon & 0x3fff w1s := toWord(w1) w2s := toWord(w2) w3s := toWord(w3) fmt.Println("\nThree word location is:") fmt.Printf(" %s %s %s\n", w1s, w2s, w3s) w1 = fromWord(w1s) w2 = fromWord(w2s) w3 = fromWord(w3s) latlon = (w1 << 28) | (w2 << 14) | w3 ilat = latlon >> 22 ilon = latlon & 0x3fffff lat = float64(ilat-900000) / 10000 lon = float64(ilon-1800000) / 10000 fmt.Println("\nAfter reversing the procedure:") fmt.Printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon) }
Translate this program into Go but keep the logic exactly as in C.
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 100 int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); shift=q-p; strncpy(str+1,p,shift); str[0]=c; free(p); return shift; } void decode(int* pass,int size,char *sym) { int i,index; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=table[pass[i]]; index=move_to_front(table,c); if(pass[i]!=index) printf("there is an error"); sym[i]=c; } sym[size]='\0'; } void encode(char *sym,int size,int *pass) { int i=0; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=sym[i]; pass[i]=move_to_front(table,c); } } int check(char *sym,int size,int *pass) { int *pass2=malloc(sizeof(int)*size); char *sym2=malloc(sizeof(char)*size); int i,val=1; encode(sym,size,pass2); i=0; while(i<size && pass[i]==pass2[i])i++; if(i!=size)val=0; decode(pass,size,sym2); if(strcmp(sym,sym2)!=0)val=0; free(sym2); free(pass2); return val; } int main() { char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"}; int pass[MAX_SIZE]={0}; int i,len,j; for(i=0;i<3;i++) { len=strlen(sym[i]); encode(sym[i],len,pass); printf("%s : [",sym[i]); for(j=0;j<len;j++) printf("%d ",pass[j]); printf("]\n"); if(check(sym[i],len,pass)) printf("Correct :)\n"); else printf("Incorrect :(\n"); } return 0; }
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
Please provide an equivalent version of this C code in Go.
#include <ldap.h> char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); LDAPMessage **result; ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE, "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", NULL, 0, result); ldap_msgfree(*result); ldap_unbind(ld);
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } groups, err := client.GetGroupsOfUser("username") if err != nil { log.Fatalf("Error getting groups for user %s: %+v", "username", err) } log.Printf("Groups: %+v", groups) }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> #include <gsl/gsl_linalg.h> void gsl_matrix_print(const gsl_matrix *M) { int rows = M->size1; int cols = M->size2; for (int i = 0; i < rows; i++) { printf("|"); for (int j = 0; j < cols; j++) { printf("% 12.10f ", gsl_matrix_get(M, i, j)); } printf("\b|\n"); } printf("\n"); } int main(){ double a[] = {3, 0, 4, 5}; gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2); gsl_matrix *V = gsl_matrix_alloc(2, 2); gsl_vector *S = gsl_vector_alloc(2); gsl_vector *work = gsl_vector_alloc(2); gsl_linalg_SV_decomp(&A.matrix, V, S, work); gsl_matrix_transpose(V); double s[] = {S->data[0], 0, 0, S->data[1]}; gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2); printf("U:\n"); gsl_matrix_print(&A.matrix); printf("S:\n"); gsl_matrix_print(&SM.matrix); printf("VT:\n"); gsl_matrix_print(V); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); return 0; }
<package main import ( "fmt" "gonum.org/v1/gonum/mat" "log" ) func matPrint(m mat.Matrix) { fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze()) fmt.Printf("%13.10f\n", fa) } func main() { var svd mat.SVD a := mat.NewDense(2, 2, []float64{3, 0, 4, 5}) ok := svd.Factorize(a, mat.SVDFull) if !ok { log.Fatal("Something went wrong!") } u := mat.NewDense(2, 2, nil) svd.UTo(u) fmt.Println("U:") matPrint(u) values := svd.Values(nil) sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]}) fmt.Println("\nΣ:") matPrint(sigma) vt := mat.NewDense(2, 2, nil) svd.VTo(vt) fmt.Println("\nVT:") matPrint(vt) }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> int main() { for (int i = 0, sum = 0; i < 50; ++i) { sum += i * i * i; printf("%7d%c", sum, (i + 1) % 5 == 0 ? '\n' : ' '); } return 0; }
package main import ( "fmt" "rcu" ) func main() { fmt.Println("Cumulative sums of the first 50 cubes:") sum := 0 for n := 0; n < 50; n++ { sum += n * n * n fmt.Printf("%9s ", rcu.Commatize(sum)) if n%10 == 9 { fmt.Println() } } fmt.Println()
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <limits.h> #include <pthread.h> #define WILL_BLOCK_EVERYTHING 0 #if WILL_BLOCK_EVERYTHING #include <poll.h> #endif size_t tally = 0; void* write_loop(void *a) { int fd; char buf[32]; while (1) { #if WILL_BLOCK_EVERYTHING fd = open("out", O_WRONLY|O_NONBLOCK); if (fd < 0) { usleep(200000); continue; } #else fd = open("out", O_WRONLY); #endif write(fd, buf, snprintf(buf, 32, "%d\n", tally)); close(fd); usleep(10000); } } void read_loop() { int fd; size_t len; char buf[PIPE_BUF]; #if WILL_BLOCK_EVERYTHING struct pollfd pfd; pfd.events = POLLIN; #endif while (1) { #if WILL_BLOCK_EVERYTHING fd = pfd.fd = open("in", O_RDONLY|O_NONBLOCK); fcntl(fd, F_SETFL, 0); poll(&pfd, 1, INFTIM); #else fd = open("in", O_RDONLY); #endif while ((len = read(fd, buf, PIPE_BUF)) > 0) tally += len; close(fd); } } int main() { pthread_t pid; mkfifo("in", 0666); mkfifo("out", 0666); pthread_create(&pid, 0, write_loop, 0); read_loop(); return 0; }
package main import ( "fmt" "io" "log" "os" "sync/atomic" "syscall" ) const ( inputFifo = "/tmp/in.fifo" outputFifo = "/tmp/out.fifo" readsize = 64 << 10 ) func openFifo(path string, oflag int) (f *os.File, err error) { err = syscall.Mkfifo(path, 0660) if err != nil && !os.IsExist(err) { return } f, err = os.OpenFile(path, oflag, 0660) if err != nil { return } fi, err := f.Stat() if err != nil { f.Close() return nil, err } if fi.Mode()&os.ModeType != os.ModeNamedPipe { f.Close() return nil, os.ErrExist } return } func main() { var byteCount int64 go func() { var delta int var err error buf := make([]byte, readsize) for { input, err := openFifo(inputFifo, os.O_RDONLY) if err != nil { break } for err == nil { delta, err = input.Read(buf) atomic.AddInt64(&byteCount, int64(delta)) } input.Close() if err != io.EOF { break } } log.Fatal(err) }() for { output, err := openFifo(outputFifo, os.O_WRONLY) if err != nil { log.Fatal(err) } cnt := atomic.LoadInt64(&byteCount) fmt.Fprintln(output, cnt) output.Close() } }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> #include <complex.h> #include <math.h> #define FMTSPEC(arg) _Generic((arg), \ float: "%f", double: "%f", \ long double: "%Lf", unsigned int: "%u", \ unsigned long: "%lu", unsigned long long: "%llu", \ int: "%d", long: "%ld", long long: "%lld", \ default: "(invalid type (%p)") #define CMPPARTS(x, y) ((long double complex)((long double)(x) + \ I * (long double)(y))) #define TEST_CMPL(i, j)\ printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \ printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false")) #define TEST_REAL(i)\ printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false")) static inline int isint(long double complex n) { return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n); } int main(void) { TEST_REAL(0); TEST_REAL(-0); TEST_REAL(-2); TEST_REAL(-2.00000000000001); TEST_REAL(5); TEST_REAL(7.3333333333333); TEST_REAL(3.141592653589); TEST_REAL(-9.223372036854776e18); TEST_REAL(5e-324); TEST_REAL(NAN); TEST_CMPL(6, 0); TEST_CMPL(0, 1); TEST_CMPL(0, 0); TEST_CMPL(3.4, 0); double complex test1 = 5 + 0*I, test2 = 3.4f, test3 = 3, test4 = 0 + 1.2*I; printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false"); printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false"); printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false"); printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false"); }
package main import ( "fmt" "math" "math/big" "reflect" "strings" "unsafe" ) func Float64IsInt(f float64) bool { _, frac := math.Modf(f) return frac == 0 } func Float32IsInt(f float32) bool { return Float64IsInt(float64(f)) } func Complex128IsInt(c complex128) bool { return imag(c) == 0 && Float64IsInt(real(c)) } func Complex64IsInt(c complex64) bool { return imag(c) == 0 && Float64IsInt(float64(real(c))) } type hasIsInt interface { IsInt() bool } var bigIntT = reflect.TypeOf((*big.Int)(nil)) func IsInt(i interface{}) bool { if ci, ok := i.(hasIsInt); ok { return ci.IsInt() } switch v := reflect.ValueOf(i); v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return true case reflect.Float32, reflect.Float64: return Float64IsInt(v.Float()) case reflect.Complex64, reflect.Complex128: return Complex128IsInt(v.Complex()) case reflect.String: if r, ok := new(big.Rat).SetString(v.String()); ok { return r.IsInt() } case reflect.Ptr: if v.Type() == bigIntT { return true } } return false } type intbased int16 type complexbased complex64 type customIntegerType struct { } func (customIntegerType) IsInt() bool { return true } func (customIntegerType) String() string { return "<…>" } func main() { hdr := fmt.Sprintf("%27s  %-6s %s\n", "Input", "IsInt", "Type") show2 := func(t bool, i interface{}, args ...interface{}) { istr := fmt.Sprint(i) fmt.Printf("%27s  %-6t %T ", istr, t, i) fmt.Println(args...) } show := func(i interface{}, args ...interface{}) { show2(IsInt(i), i, args...) } fmt.Print("Using Float64IsInt with float64:\n", hdr) neg1 := -1. for _, f := range []float64{ 0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3, math.Pi, math.MinInt64, math.MaxUint64, math.SmallestNonzeroFloat64, math.MaxFloat64, math.NaN(), math.Inf(1), math.Inf(-1), } { show2(Float64IsInt(f), f) } fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr) for _, c := range []complex128{ 3, 1i, 0i, 3.4, } { show2(Complex128IsInt(c), c) } fmt.Println("\nUsing reflection:") fmt.Print(hdr) show("hello") show(math.MaxFloat64) show("9e100") f := new(big.Float) show(f) f.SetString("1e-3000") show(f) show("(4+0i)", "(complex strings not parsed)") show(4 + 0i) show(rune('§'), "or rune") show(byte('A'), "or byte") var t1 intbased = 5200 var t2a, t2b complexbased = 5 + 0i, 5 + 1i show(t1) show(t2a) show(t2b) x := uintptr(unsafe.Pointer(&t2b)) show(x) show(math.MinInt32) show(uint64(math.MaxUint64)) b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0) show(b) r := new(big.Rat) show(r) r.SetString("2/3") show(r) show(r.SetFrac(b, new(big.Int).SetInt64(9))) show("12345/5") show(new(customIntegerType)) }
Produce a functionally identical Go code for the snippet given in C.
#include <stdlib.h> int main() { system("ls"); return 0; }
package main import ( "log" "os" "os/exec" ) func main() { cmd := exec.Command("ls", "-l") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
Produce a language-to-language conversion: from C to Go, same semantics.
#include <stdio.h> #include <math.h> typedef struct { double x, y, z; } vector; typedef struct { vector i, j, k; } matrix; double norm(vector v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } vector normalize(vector v){ double length = norm(v); vector n = {v.x / length, v.y / length, v.z / length}; return n; } double dotProduct(vector v1, vector v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } vector crossProduct(vector v1, vector v2) { vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x}; return cp; } double getAngle(vector v1, vector v2) { return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2))); } vector matrixMultiply(matrix m ,vector v) { vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)}; return mm; } vector aRotate(vector p, vector v, double a) { double ca = cos(a), sa = sin(a); double t = 1.0 - ca; double x = v.x, y = v.y, z = v.z; matrix r = { {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa}, {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa}, {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t} }; return matrixMultiply(r, p); } int main() { vector v1 = {5, -6, 4}, v2 = {8, 5, -30}; double a = getAngle(v1, v2); vector cp = crossProduct(v1, v2); vector ncp = normalize(cp); vector np = aRotate(v1, ncp, a); printf("[%.13f, %.13f, %.13f]\n", np.x, np.y, np.z); return 0; }
package main import ( "fmt" "math" ) type vector [3]float64 type matrix [3]vector func norm(v vector) float64 { return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) } func normalize(v vector) vector { length := norm(v) return vector{v[0] / length, v[1] / length, v[2] / length} } func dotProduct(v1, v2 vector) float64 { return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] } func crossProduct(v1, v2 vector) vector { return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]} } func getAngle(v1, v2 vector) float64 { return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2))) } func matrixMultiply(m matrix, v vector) vector { return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)} } func aRotate(p, v vector, a float64) vector { ca, sa := math.Cos(a), math.Sin(a) t := 1 - ca x, y, z := v[0], v[1], v[2] r := matrix{ {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa}, {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa}, {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}, } return matrixMultiply(r, p) } func main() { v1 := vector{5, -6, 4} v2 := vector{8, 5, -30} a := getAngle(v1, v2) cp := crossProduct(v1, v2) ncp := normalize(cp) np := aRotate(v1, ncp, a) fmt.Println(np) }
Keep all operations the same but rewrite the snippet in Go.
#include <libxml/xmlschemastypes.h> int main(int argC, char** argV) { if (argC <= 2) { printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]); return 0; } xmlDocPtr doc; xmlSchemaPtr schema = NULL; xmlSchemaParserCtxtPtr ctxt; char *XMLFileName = argV[1]; char *XSDFileName = argV[2]; int ret; xmlLineNumbersDefault(1); ctxt = xmlSchemaNewParserCtxt(XSDFileName); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); doc = xmlReadFile(XMLFileName, NULL, 0); if (doc == NULL){ fprintf(stderr, "Could not parse %s\n", XMLFileName); } else{ xmlSchemaValidCtxtPtr ctxt; ctxt = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0){ printf("%s validates\n", XMLFileName); } else if (ret > 0){ printf("%s fails to validate\n", XMLFileName); } else{ printf("%s validation generated an internal error\n", XMLFileName); } xmlSchemaFreeValidCtxt(ctxt); xmlFreeDoc(doc); } if(schema != NULL) xmlSchemaFree(schema); xmlSchemaCleanupTypes(); xmlCleanupParser(); xmlMemoryDump(); return 0; }
package main import ( "fmt" "github.com/lestrrat-go/libxml2" "github.com/lestrrat-go/libxml2/xsd" "io/ioutil" "log" "os" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { xsdfile := "shiporder.xsd" f, err := os.Open(xsdfile) check(err) defer f.Close() buf, err := ioutil.ReadAll(f) check(err) s, err := xsd.Parse(buf) check(err) defer s.Free() xmlfile := "shiporder.xml" f2, err := os.Open(xmlfile) check(err) defer f2.Close() buf2, err := ioutil.ReadAll(f2) check(err) d, err := libxml2.Parse(buf2) check(err) if err := s.Validate(d); err != nil { for _, e := range err.(xsd.SchemaValidationError).Errors() { log.Printf("error: %s", e.Error()) } return } fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!") }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> struct node { int val, len; struct node *next; }; void lis(int *v, int len) { int i; struct node *p, *n = calloc(len, sizeof *n); for (i = 0; i < len; i++) n[i].val = v[i]; for (i = len; i--; ) { for (p = n + i; p++ < n + len; ) { if (p->val > n[i].val && p->len >= n[i].len) { n[i].next = p; n[i].len = p->len + 1; } } } for (i = 0, p = n; i < len; i++) if (n[i].len > p->len) p = n + i; do printf(" %d", p->val); while ((p = p->next)); putchar('\n'); free(n); } int main(void) { int x[] = { 3, 2, 6, 4, 5, 1 }; int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; lis(x, sizeof(x) / sizeof(int)); lis(y, sizeof(y) / sizeof(int)); return 0; }
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <math.h> #include <unistd.h> const char *shades = ".:!*oe&#%@"; double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } typedef struct { double cx, cy, cz, r; } sphere_t; sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 }; int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2) { double zsq; x -= sph->cx; y -= sph->cy; zsq = sph->r * sph->r - (x * x + y * y); if (zsq < 0) return 0; zsq = sqrt(zsq); *z1 = sph->cz - zsq; *z2 = sph->cz + zsq; return 1; } void draw_sphere(double k, double ambient) { int i, j, intensity, hit_result; double b; double vec[3], x, y, zb1, zb2, zs1, zs2; for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) { y = i + .5; for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) { x = (j - pos.cx) / 2. + .5 + pos.cx; if (!hit_sphere(&pos, x, y, &zb1, &zb2)) hit_result = 0; else if (!hit_sphere(&neg, x, y, &zs1, &zs2)) hit_result = 1; else if (zs1 > zb1) hit_result = 1; else if (zs2 > zb2) hit_result = 0; else if (zs2 > zb1) hit_result = 2; else hit_result = 1; switch(hit_result) { case 0: putchar('+'); continue; case 1: vec[0] = x - pos.cx; vec[1] = y - pos.cy; vec[2] = zb1 - pos.cz; break; default: vec[0] = neg.cx - x; vec[1] = neg.cy - y; vec[2] = neg.cz - zs2; } normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } putchar('\n'); } } int main() { double ang = 0; while (1) { printf("\033[H"); light[1] = cos(ang * 2); light[2] = cos(ang); light[0] = sin(ang); normalize(light); ang += .05; draw_sphere(2, .3); usleep(100000); } return 0; }
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } type sphere struct { cx, cy, cz int r int } func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false } func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img } func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100} img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> #include <math.h> #include <unistd.h> const char *shades = ".:!*oe&#%@"; double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } typedef struct { double cx, cy, cz, r; } sphere_t; sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 }; int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2) { double zsq; x -= sph->cx; y -= sph->cy; zsq = sph->r * sph->r - (x * x + y * y); if (zsq < 0) return 0; zsq = sqrt(zsq); *z1 = sph->cz - zsq; *z2 = sph->cz + zsq; return 1; } void draw_sphere(double k, double ambient) { int i, j, intensity, hit_result; double b; double vec[3], x, y, zb1, zb2, zs1, zs2; for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) { y = i + .5; for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) { x = (j - pos.cx) / 2. + .5 + pos.cx; if (!hit_sphere(&pos, x, y, &zb1, &zb2)) hit_result = 0; else if (!hit_sphere(&neg, x, y, &zs1, &zs2)) hit_result = 1; else if (zs1 > zb1) hit_result = 1; else if (zs2 > zb2) hit_result = 0; else if (zs2 > zb1) hit_result = 2; else hit_result = 1; switch(hit_result) { case 0: putchar('+'); continue; case 1: vec[0] = x - pos.cx; vec[1] = y - pos.cy; vec[2] = zb1 - pos.cz; break; default: vec[0] = neg.cx - x; vec[1] = neg.cy - y; vec[2] = neg.cz - zs2; } normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } putchar('\n'); } } int main() { double ang = 0; while (1) { printf("\033[H"); light[1] = cos(ang * 2); light[2] = cos(ang); light[0] = sin(ang); normalize(light); ang += .05; draw_sphere(2, .3); usleep(100000); } return 0; }
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func (v *vector) normalize() { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] } type sphere struct { cx, cy, cz int r int } func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) { x -= s.cx y -= s.cy if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 { zsqrt := math.Sqrt(float64(zsq)) return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true } return 0, 0, false } func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray { w, h := pos.r*4, pos.r*3 bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2) img := image.NewGray(bounds) vec := new(vector) for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ { for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ { zb1, zb2, hit := pos.hit(x, y) if !hit { continue } zs1, zs2, hit := neg.hit(x, y) if hit { if zs1 > zb1 { hit = false } else if zs2 > zb2 { continue } } if hit { vec[0] = float64(neg.cx - x) vec[1] = float64(neg.cy - y) vec[2] = float64(neg.cz) - zs2 } else { vec[0] = float64(x - pos.cx) vec[1] = float64(y - pos.cy) vec[2] = zb1 - float64(pos.cz) } vec.normalize() s := dot(dir, vec) if s < 0 { s = 0 } lum := 255 * (math.Pow(s, k) + amb) / (1 + amb) if lum < 0 { lum = 0 } else if lum > 255 { lum = 255 } img.SetGray(x, y, color.Gray{uint8(lum)}) } } return img } func main() { dir := &vector{20, -40, -10} dir.normalize() pos := &sphere{0, 0, 0, 120} neg := &sphere{-90, -90, -30, 100} img := deathStar(pos, neg, 1.5, .2, dir) f, err := os.Create("dstar.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, img); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Please provide an equivalent version of this C code in Go.
#include "SL_Generated.h" #include "CImg.h" using namespace cimg_library; int main( int argc, char** argv ) { string fileName = "Pentagon.bmp"; if(argc > 1) fileName = argv[1]; int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]); int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]); int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]); int threads = 0; if(argc > 5) threads = atoi(argv[5]); char titleBuffer[200]; SLTimer t; CImg<int> image(fileName.c_str()); int imageDimensions[] = {image.height(), image.width(), 0}; Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions); Sequence< Sequence<int> > result; sl_init(threads); t.start(); sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result); t.stop(); CImg<int> resultImage(result[1].size(), result.size()); for(int y = 0; y < result.size(); y++) for(int x = 0; x < result[y+1].size(); x++) resultImage(x,result.size() - 1 - y) = result[y+1][x+1]; sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0", image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime()); resultImage.display(titleBuffer); sl_done(); return 0; }
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) func hough(im image.Image, ntx, mry int) draw.Image { nimx := im.Bounds().Max.X mimy := im.Bounds().Max.Y him := image.NewGray(image.Rect(0, 0, ntx, mry)) draw.Draw(him, him.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) rmax := math.Hypot(float64(nimx), float64(mimy)) dr := rmax / float64(mry/2) dth := math.Pi / float64(ntx) for jx := 0; jx < nimx; jx++ { for iy := 0; iy < mimy; iy++ { col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray) if col.Y == 255 { continue } for jtx := 0; jtx < ntx; jtx++ { th := dth * float64(jtx) r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th) iry := mry/2 - int(math.Floor(r/dr+.5)) col = him.At(jtx, iry).(color.Gray) if col.Y > 0 { col.Y-- him.SetGray(jtx, iry, col) } } } } return him } func main() { f, err := os.Open("Pentagon.png") if err != nil { fmt.Println(err) return } pent, err := png.Decode(f) if err != nil { fmt.Println(err) return } if err = f.Close(); err != nil { fmt.Println(err) } h := hough(pent, 460, 360) if f, err = os.Create("hough.png"); err != nil { fmt.Println(err) return } if err = png.Encode(f, h); err != nil { fmt.Println(err) } if cErr := f.Close(); cErr != nil && err == nil { fmt.Println(err) } }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif typedef double (* Ifctn)( double t); double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b); for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
package main import ( "fmt" "math" ) type ifctn func(float64) float64 func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } else { sum += 3 * f(a+h1*float64(j)) } } return h * sum / 8 } func gammaIncQ(a, x float64) float64 { aa1 := a - 1 var f ifctn = func(t float64) float64 { return math.Pow(t, aa1) * math.Exp(-t) } y := aa1 h := 1.5e-2 for f(y)*(x-y) > 2e-8 && y < x { y += .4 } if y > x { y = x } return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a))) } func chi2ud(ds []int) float64 { var sum, expected float64 for _, d := range ds { expected += float64(d) } expected /= float64(len(ds)) for _, d := range ds { x := float64(d) - expected sum += x * x } return sum / expected } func chi2p(dof int, distance float64) float64 { return gammaIncQ(.5*float64(dof), .5*distance) } const sigLevel = .05 func main() { for _, dset := range [][]int{ {199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}, } { utest(dset) } } func utest(dset []int) { fmt.Println("Uniform distribution test") var sum int for _, c := range dset { sum += c } fmt.Println(" dataset:", dset) fmt.Println(" samples: ", sum) fmt.Println(" categories: ", len(dset)) dof := len(dset) - 1 fmt.Println(" degrees of freedom: ", dof) dist := chi2ud(dset) fmt.Println(" chi square test statistic: ", dist) p := chi2p(dof, dist) fmt.Println(" p-value of test statistic: ", p) sig := p < sigLevel fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig) fmt.Println(" uniform? ", !sig, "\n") }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif typedef double (* Ifctn)( double t); double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b); for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
package main import ( "fmt" "math" ) type ifctn func(float64) float64 func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } else { sum += 3 * f(a+h1*float64(j)) } } return h * sum / 8 } func gammaIncQ(a, x float64) float64 { aa1 := a - 1 var f ifctn = func(t float64) float64 { return math.Pow(t, aa1) * math.Exp(-t) } y := aa1 h := 1.5e-2 for f(y)*(x-y) > 2e-8 && y < x { y += .4 } if y > x { y = x } return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a))) } func chi2ud(ds []int) float64 { var sum, expected float64 for _, d := range ds { expected += float64(d) } expected /= float64(len(ds)) for _, d := range ds { x := float64(d) - expected sum += x * x } return sum / expected } func chi2p(dof int, distance float64) float64 { return gammaIncQ(.5*float64(dof), .5*distance) } const sigLevel = .05 func main() { for _, dset := range [][]int{ {199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}, } { utest(dset) } } func utest(dset []int) { fmt.Println("Uniform distribution test") var sum int for _, c := range dset { sum += c } fmt.Println(" dataset:", dset) fmt.Println(" samples: ", sum) fmt.Println(" categories: ", len(dset)) dof := len(dset) - 1 fmt.Println(" degrees of freedom: ", dof) dist := chi2ud(dset) fmt.Println(" chi square test statistic: ", dist) p := chi2p(dof, dist) fmt.Println(" p-value of test statistic: ", p) sig := p < sigLevel fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig) fmt.Println(" uniform? ", !sig, "\n") }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
Rewrite the snippet below in Go so it works the same as the original C code.
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err := parseLibDep(data) if err != nil { fmt.Println(err) return } var tops []string for n := range g { if !dep[n] { tops = append(tops, n) } } fmt.Println("Top levels:", tops) showOrder(g, "top1") showOrder(g, "top2") showOrder(g, "top1", "top2") fmt.Println("Cycle examples:") g, _, err = parseLibDep(data + ` des1a1 des1`) if err != nil { fmt.Println(err) return } showOrder(g, "top1") showOrder(g, "ip1", "ip2") } func showOrder(g graph, target ...string) { order, cyclic := g.orderFrom(target...) if cyclic == nil { reverse(order) fmt.Println("Target", target, "order:", order) } else { fmt.Println("Target", target, "cyclic dependencies:", cyclic) } } func reverse(s []string) { last := len(s) - 1 for i, e := range s[:len(s)/2] { s[i], s[last-i] = s[last-i], e } } type graph map[string][]string type depList map[string]bool func parseLibDep(data string) (g graph, d depList, err error) { lines := strings.Split(data, "\n") if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") { return nil, nil, fmt.Errorf("data format") } lines = lines[3:] g = graph{} d = depList{} for _, line := range lines { libs := strings.Fields(line) if len(libs) == 0 { continue } lib := libs[0] var deps []string for _, dep := range libs[1:] { g[dep] = g[dep] if dep == lib { continue } for i := 0; ; i++ { if i == len(deps) { deps = append(deps, dep) d[dep] = true break } if dep == deps[i] { break } } } g[lib] = deps } return g, d, nil } func (g graph) orderFrom(start ...string) (order, cyclic []string) { L := make([]string, len(g)) i := len(L) temp := map[string]bool{} perm := map[string]bool{} var cycleFound bool var cycleStart string var visit func(string) visit = func(n string) { switch { case temp[n]: cycleFound = true cycleStart = n return case perm[n]: return } temp[n] = true for _, m := range g[n] { visit(m) if cycleFound { if cycleStart > "" { cyclic = append(cyclic, n) if n == cycleStart { cycleStart = "" } } return } } delete(temp, n) perm[n] = true i-- L[i] = n } for _, n := range start { if perm[n] { continue } visit(n) if cycleFound { return nil, cyclic } } return L[i:], nil }
Translate the given C code snippet into Go without altering its behavior.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 typedef unsigned char character; typedef character *string; typedef struct node_t node; struct node_t { enum tag_t { NODE_LEAF, NODE_TREE, NODE_SEQ, } tag; union { string str; node *root; } data; node *next; }; node *allocate_node(enum tag_t tag) { node *n = malloc(sizeof(node)); if (n == NULL) { fprintf(stderr, "Failed to allocate node for tag: %d\n", tag); exit(1); } n->tag = tag; n->next = NULL; return n; } node *make_leaf(string str) { node *n = allocate_node(NODE_LEAF); n->data.str = str; return n; } node *make_tree() { node *n = allocate_node(NODE_TREE); n->data.root = NULL; return n; } node *make_seq() { node *n = allocate_node(NODE_SEQ); n->data.root = NULL; return n; } void deallocate_node(node *n) { if (n == NULL) { return; } deallocate_node(n->next); n->next = NULL; if (n->tag == NODE_LEAF) { free(n->data.str); n->data.str = NULL; } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) { deallocate_node(n->data.root); n->data.root = NULL; } else { fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag); exit(1); } free(n); } void append(node *root, node *elem) { if (root == NULL) { fprintf(stderr, "Cannot append to uninitialized node."); exit(1); } if (elem == NULL) { return; } if (root->tag == NODE_SEQ || root->tag == NODE_TREE) { if (root->data.root == NULL) { root->data.root = elem; } else { node *it = root->data.root; while (it->next != NULL) { it = it->next; } it->next = elem; } } else { fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag); exit(1); } } size_t count(node *n) { if (n == NULL) { return 0; } if (n->tag == NODE_LEAF) { return 1; } if (n->tag == NODE_TREE) { size_t sum = 0; node *it = n->data.root; while (it != NULL) { sum += count(it); it = it->next; } return sum; } if (n->tag == NODE_SEQ) { size_t prod = 1; node *it = n->data.root; while (it != NULL) { prod *= count(it); it = it->next; } return prod; } fprintf(stderr, "Cannot count node with tag: %d\n", n->tag); exit(1); } void expand(node *n, size_t pos) { if (n == NULL) { return; } if (n->tag == NODE_LEAF) { printf(n->data.str); } else if (n->tag == NODE_TREE) { node *it = n->data.root; while (true) { size_t cnt = count(it); if (pos < cnt) { expand(it, pos); break; } pos -= cnt; it = it->next; } } else if (n->tag == NODE_SEQ) { size_t prod = pos; node *it = n->data.root; while (it != NULL) { size_t cnt = count(it); size_t rem = prod % cnt; expand(it, rem); it = it->next; } } else { fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag); exit(1); } } string allocate_string(string src) { size_t len = strlen(src); string out = calloc(len + 1, sizeof(character)); if (out == NULL) { fprintf(stderr, "Failed to allocate a copy of the string."); exit(1); } strcpy(out, src); return out; } node *parse_seq(string input, size_t *pos); node *parse_tree(string input, size_t *pos) { node *root = make_tree(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; size_t depth = 0; bool asSeq = false; bool allow = false; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = '\\'; buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { buffer[bufpos++] = c; buffer[bufpos] = 0; asSeq = true; depth++; } else if (c == '}') { if (depth-- > 0) { buffer[bufpos++] = c; buffer[bufpos] = 0; } else { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); } else { append(root, make_leaf(allocate_string(buffer))); } break; } } else if (c == ',') { if (depth == 0) { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); bufpos = 0; buffer[bufpos] = 0; asSeq = false; } else { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } return root; } node *parse_seq(string input, size_t *pos) { node *root = make_seq(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { node *tree = parse_tree(input, pos); if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } append(root, tree); } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } return root; } void test(string input) { size_t pos = 0; node *n = parse_seq(input, &pos); size_t cnt = count(n); size_t i; printf("Pattern: %s\n", input); for (i = 0; i < cnt; i++) { expand(n, i); printf("\n"); } printf("\n"); deallocate_node(n); } int main() { test("~/{Downloads,Pictures}/*.{jpg,gif,png}"); test("It{{em,alic}iz,erat}e{d,}, please."); test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!"); return 0; }
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } type Sequence []Expander func (seq Sequence) Expand() []string { if len(seq) == 0 { return nil } out := seq[0].Expand() for _, e := range seq[1:] { out = combine(out, e.Expand()) } return out } func combine(al, bl []string) []string { out := make([]string, 0, len(al)*len(bl)) for _, a := range al { for _, b := range bl { out = append(out, a+b) } } return out } const ( escape = '\\' altStart = '{' altEnd = '}' altSep = ',' ) type piT struct{ pos, cnt, depth int } type Brace string func Expand(s string) []string { return Brace(s).Expand() } func (b Brace) Expand() []string { return b.Expander().Expand() } func (b Brace) Expander() Expander { s := string(b) var posInfo []piT var stack []int removePosInfo := func(i int) { end := len(posInfo) - 1 copy(posInfo[i:end], posInfo[i+1:]) posInfo = posInfo[:end] } inEscape := false for i, r := range s { if inEscape { inEscape = false continue } switch r { case escape: inEscape = true case altStart: stack = append(stack, len(posInfo)) posInfo = append(posInfo, piT{i, 0, len(stack)}) case altEnd: if len(stack) == 0 { continue } si := len(stack) - 1 pi := stack[si] if posInfo[pi].cnt == 0 { removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == len(stack) { removePosInfo(pi) } else { pi++ } } } else { posInfo = append(posInfo, piT{i, -2, len(stack)}) } stack = stack[:si] case altSep: if len(stack) == 0 { continue } posInfo = append(posInfo, piT{i, -1, len(stack)}) posInfo[stack[len(stack)-1]].cnt++ } } for len(stack) > 0 { si := len(stack) - 1 pi := stack[si] depth := posInfo[pi].depth removePosInfo(pi) for pi < len(posInfo) { if posInfo[pi].depth == depth { removePosInfo(pi) } else { pi++ } } stack = stack[:si] } return buildExp(s, 0, posInfo) } func buildExp(s string, off int, info []piT) Expander { if len(info) == 0 { return Text(s) } var seq Sequence i := 0 var dj, j, depth int for dk, piK := range info { k := piK.pos - off switch s[k] { case altStart: if depth == 0 { dj = dk j = k depth = piK.depth } case altEnd: if piK.depth != depth { continue } if j > i { seq = append(seq, Text(s[i:j])) } alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk]) seq = append(seq, alt) i = k + 1 depth = 0 } } if j := len(s); j > i { seq = append(seq, Text(s[i:j])) } if len(seq) == 1 { return seq[0] } return seq } func buildAlt(s string, depth, off int, info []piT) Alternation { var alt Alternation i := 0 var di int for dk, piK := range info { if piK.depth != depth { continue } if k := piK.pos - off; s[k] == altSep { sub := buildExp(s[i:k], i+off, info[di:dk]) alt = append(alt, sub) i = k + 1 di = dk + 1 } } sub := buildExp(s[i:], i+off, info[di:]) alt = append(alt, sub) return alt }
Change the following C code into Go without altering its purpose.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
Maintain the same structure and functionality when rewriting this code in Go.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
import ( "image" "image/gif" "io/ioutil" "strings" "unicode" ) func f() (int, float64) { return 0, 0 } func g(int, float64) int { return 0 } func h(string, ...int) {}
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> #define MAX 12 char *super = 0; int pos, cnt[MAX]; int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; } int r(int n) { if (!n) return 0; char c = super[pos - n]; if (!--cnt[n]) { cnt[n] = n; if (!r(n-1)) return 0; } super[pos++] = c; return 1; } void superperm(int n) { int i, len; pos = n; len = fact_sum(n); super = realloc(super, len + 1); super[len] = '\0'; for (i = 0; i <= n; i++) cnt[i] = i; for (i = 1; i <= n; i++) super[i - 1] = i + '0'; while (r(n)); } int main(void) { int n; for (n = 0; n < MAX; n++) { printf("superperm(%2d) ", n); superperm(n); printf("len = %d", (int)strlen(super)); putchar('\n'); } return 0; }
package main import "fmt" const max = 12 var ( super []byte pos int cnt [max]int ) func factSum(n int) int { s := 0 for x, f := 0, 1; x < n; { x++ f *= x s += f } return s } func r(n int) bool { if n == 0 { return false } c := super[pos-n] cnt[n]-- if cnt[n] == 0 { cnt[n] = n if !r(n - 1) { return false } } super[pos] = c pos++ return true } func superperm(n int) { pos = n le := factSum(n) super = make([]byte, le) for i := 0; i <= n; i++ { cnt[i] = i } for i := 1; i <= n; i++ { super[i-1] = byte(i) + '0' } for r(n) { } } func main() { for n := 0; n < max; n++ { fmt.Printf("superperm(%2d) ", n) superperm(n) fmt.Printf("len = %d\n", len(super)) } }
Maintain the same structure and functionality when rewriting this code in Go.
#include <windows.h> #include "resource.h" BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) { switch( msg ) { case WM_INITDIALOG: srand( GetTickCount() ); SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE ); break; case WM_COMMAND: switch( LOWORD(wPar) ) { case IDC_INCREMENT: { UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE ); SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE ); } break; case IDC_RANDOM: { int reply = MessageBox( hwnd, "Do you really want to\nget a random number?", "Random input confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE ); } break; case IDC_QUIT: SendMessage( hwnd, WM_CLOSE, 0, 0 ); break; default: ; } break; case WM_CLOSE: { int reply = MessageBox( hwnd, "Do you really want to quit?", "Quit confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) EndDialog( hwnd, 0 ); } break; default: ; } return 0; } int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) { return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc ); }
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str string) (int64, bool) { i, err := strconv.ParseInt(str, 10, 64) if err != nil { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid value", ) dialog.Run() dialog.Destroy() return 0, false } return i, true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create box:") box.SetBorderWidth(1) label, err := gtk.LabelNew("Value:") check(err, "Unable to create label:") entry, err := gtk.EntryNew() check(err, "Unable to create entry:") entry.SetText("0") entry.Connect("activate", func() { str, _ := entry.GetText() validateInput(window, str) }) ib, err := gtk.ButtonNewWithLabel("Increment") check(err, "Unable to create increment button:") ib.Connect("clicked", func() { str, _ := entry.GetText() if i, ok := validateInput(window, str); ok { entry.SetText(strconv.FormatInt(i+1, 10)) } }) rb, err := gtk.ButtonNewWithLabel("Random") check(err, "Unable to create random button:") rb.Connect("clicked", func() { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Set random value", ) answer := dialog.Run() dialog.Destroy() if answer == gtk.RESPONSE_YES { entry.SetText(strconv.Itoa(rand.Intn(10000))) } }) box.PackStart(label, false, false, 2) box.PackStart(entry, false, false, 2) box.PackStart(ib, false, false, 2) box.PackStart(rb, false, false, 2) window.Add(box) window.ShowAll() gtk.Main() }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <windows.h> #include "resource.h" BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) { switch( msg ) { case WM_INITDIALOG: srand( GetTickCount() ); SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE ); break; case WM_COMMAND: switch( LOWORD(wPar) ) { case IDC_INCREMENT: { UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE ); SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE ); } break; case IDC_RANDOM: { int reply = MessageBox( hwnd, "Do you really want to\nget a random number?", "Random input confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE ); } break; case IDC_QUIT: SendMessage( hwnd, WM_CLOSE, 0, 0 ); break; default: ; } break; case WM_CLOSE: { int reply = MessageBox( hwnd, "Do you really want to quit?", "Quit confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) EndDialog( hwnd, 0 ); } break; default: ; } return 0; } int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) { return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc ); }
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str string) (int64, bool) { i, err := strconv.ParseInt(str, 10, 64) if err != nil { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid value", ) dialog.Run() dialog.Destroy() return 0, false } return i, true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create box:") box.SetBorderWidth(1) label, err := gtk.LabelNew("Value:") check(err, "Unable to create label:") entry, err := gtk.EntryNew() check(err, "Unable to create entry:") entry.SetText("0") entry.Connect("activate", func() { str, _ := entry.GetText() validateInput(window, str) }) ib, err := gtk.ButtonNewWithLabel("Increment") check(err, "Unable to create increment button:") ib.Connect("clicked", func() { str, _ := entry.GetText() if i, ok := validateInput(window, str); ok { entry.SetText(strconv.FormatInt(i+1, 10)) } }) rb, err := gtk.ButtonNewWithLabel("Random") check(err, "Unable to create random button:") rb.Connect("clicked", func() { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Set random value", ) answer := dialog.Run() dialog.Destroy() if answer == gtk.RESPONSE_YES { entry.SetText(strconv.Itoa(rand.Intn(10000))) } }) box.PackStart(label, false, false, 2) box.PackStart(entry, false, false, 2) box.PackStart(ib, false, false, 2) box.PackStart(rb, false, false, 2) window.Add(box) window.ShowAll() gtk.Main() }
Generate an equivalent Go version of this C code.
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
package main import ( "bufio" "fmt" "io" "math/rand" "time" ) func choseLineRandomly(r io.Reader) (s string, ln int, err error) { br := bufio.NewReader(r) s, err = br.ReadString('\n') if err != nil { return } ln = 1 lnLast := 1. var sLast string for { sLast, err = br.ReadString('\n') if err == io.EOF { return s, ln, nil } if err != nil { break } lnLast++ if rand.Float64() < 1/lnLast { s = sLast ln = int(lnLast) } } return } func oneOfN(n int, file io.Reader) int { _, ln, err := choseLineRandomly(file) if err != nil { panic(err) } return ln } type simReader int func (r *simReader) Read(b []byte) (int, error) { if *r <= 0 { return 0, io.EOF } b[0] = '\n' *r-- return 1, nil } func main() { n := 10 freq := make([]int, n) rand.Seed(time.Now().UnixNano()) for times := 0; times < 1e6; times++ { sr := simReader(n) freq[oneOfN(n, &sr)-1]++ } fmt.Println(freq) }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
package main import ( "bufio" "fmt" "io" "math/rand" "time" ) func choseLineRandomly(r io.Reader) (s string, ln int, err error) { br := bufio.NewReader(r) s, err = br.ReadString('\n') if err != nil { return } ln = 1 lnLast := 1. var sLast string for { sLast, err = br.ReadString('\n') if err == io.EOF { return s, ln, nil } if err != nil { break } lnLast++ if rand.Float64() < 1/lnLast { s = sLast ln = int(lnLast) } } return } func oneOfN(n int, file io.Reader) int { _, ln, err := choseLineRandomly(file) if err != nil { panic(err) } return ln } type simReader int func (r *simReader) Read(b []byte) (int, error) { if *r <= 0 { return 0, io.EOF } b[0] = '\n' *r-- return 1, nil } func main() { n := 10 freq := make([]int, n) rand.Seed(time.Now().UnixNano()) for times := 0; times < 1e6; times++ { sr := simReader(n) freq[oneOfN(n, &sr)-1]++ } fmt.Println(freq) }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { if (head == tail) { head = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } #else #define new_rec() calloc(sizeof(rec_t), 1) #endif rec_t *find_rec(char *s) { int i; rec_t *r = &root; while (*s) { i = *s++ - '0'; if (!r->p[i]) r->p[i] = new_rec(); r = r->p[i]; } return r; } char number[100][4]; void init() { int i; for (i = 0; i < 100; i++) sprintf(number[i], "%d", i); } void count(char *buf) { int i, c[10] = {0}; char *s; for (s = buf; *s; c[*s++ - '0']++); for (i = 9; i >= 0; i--) { if (!c[i]) continue; s = number[c[i]]; *buf++ = s[0]; if ((*buf = s[1])) buf++; *buf++ = i + '0'; } *buf = '\0'; } int depth(char *in, int d) { rec_t *r = find_rec(in); if (r->depth > 0) return r->depth; d++; if (!r->depth) r->depth = -d; else r->depth += d; count(in); d = depth(in, d); if (r->depth <= 0) r->depth = d + 1; return r->depth; } int main(void) { char a[100]; int i, d, best_len = 0, n_best = 0; int best_ints[32]; rec_t *r; init(); for (i = 0; i < 1000000; i++) { sprintf(a, "%d", i); d = depth(a, 0); if (d < best_len) continue; if (d > best_len) { n_best = 0; best_len = d; } if (d == best_len) best_ints[n_best++] = i; } printf("longest length: %d\n", best_len); for (i = 0; i < n_best; i++) { printf("%d\n", best_ints[i]); sprintf(a, "%d", best_ints[i]); for (d = 0; d <= best_len; d++) { r = find_rec(a); printf("%3d: %s\n", r->depth, a); count(a); } putchar('\n'); } return 0; }
package main import ( "fmt" "strconv" ) func main() { var maxLen int var seqMaxLen [][]string for n := 1; n < 1e6; n++ { switch s := seq(n); { case len(s) == maxLen: seqMaxLen = append(seqMaxLen, s) case len(s) > maxLen: maxLen = len(s) seqMaxLen = [][]string{s} } } fmt.Println("Max sequence length:", maxLen) fmt.Println("Sequences:", len(seqMaxLen)) for _, seq := range seqMaxLen { fmt.Println("Sequence:") for _, t := range seq { fmt.Println(t) } } } func seq(n int) []string { s := strconv.Itoa(n) ss := []string{s} for { dSeq := sortD(s) d := dSeq[0] nd := 1 s = "" for i := 1; ; i++ { if i == len(dSeq) { s = fmt.Sprintf("%s%d%c", s, nd, d) break } if dSeq[i] == d { nd++ } else { s = fmt.Sprintf("%s%d%c", s, nd, d) d = dSeq[i] nd = 1 } } for _, s0 := range ss { if s == s0 { return ss } } ss = append(ss, s) } panic("unreachable") } func sortD(s string) []rune { r := make([]rune, len(s)) for i, d := range s { j := 0 for ; j < i; j++ { if d > r[j] { copy(r[j+1:], r[j:i]) break } } r[j] = d } return r }
Produce a language-to-language conversion: from C to Go, same semantics.
#include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <glib.h> typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf("%llu: %s\n", n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
import ( "fmt" "strings" ) func main() { for _, n := range []int64{ 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, } { fmt.Println(sayOrdinal(n)) } } var irregularOrdinals = map[string]string{ "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } func sayOrdinal(n int64) string { s := say(n) i := strings.LastIndexAny(s, " -") i++ if x, ok := irregularOrdinals[s[i:]]; ok { s = s[:i] + x } else if s[len(s)-1] == 'y' { s = s[:i] + s[i:len(s)-1] + "ieth" } else { s = s[:i] + s[i:] + "th" } return s } 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 }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } func main() { for n := int64(0); n < 1e10; n++ { if sdn(n) { fmt.Println(n) } } }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
package main import ( "fmt" "strconv" "strings" ) func sdn(n int64) bool { if n >= 1e10 { return false } s := strconv.FormatInt(n, 10) for d, p := range s { if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) { return false } } return true } func main() { for n := int64(0); n < 1e10; n++ { if sdn(n) { fmt.Println(n) } } }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 typedef int bool; typedef struct { int x, y; } pair; int* example = NULL; int exampleLen = 0; void reverse(int s[], int len) { int i, j, t; for (i = 0, j = len - 1; i < j; ++i, --j) { t = s[i]; s[i] = s[j]; s[j] = t; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen); pair checkSeq(int pos, int seq[], int n, int len, int minLen) { pair p; if (pos > minLen || seq[0] > n) { p.x = minLen; p.y = 0; return p; } else if (seq[0] == n) { example = malloc(len * sizeof(int)); memcpy(example, seq, len * sizeof(int)); exampleLen = len; p.x = pos; p.y = 1; return p; } else if (pos < minLen) { return tryPerm(0, pos, seq, n, len, minLen); } else { p.x = minLen; p.y = 0; return p; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) { int *seq2; pair p, res1, res2; size_t size = sizeof(int); if (i > pos) { p.x = minLen; p.y = 0; return p; } seq2 = malloc((len + 1) * size); memcpy(seq2 + 1, seq, len * size); seq2[0] = seq[0] + seq[i]; res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen); res2 = tryPerm(i + 1, pos, seq, n, len, res1.x); free(seq2); if (res2.x < res1.x) return res2; else if (res2.x == res1.x) { p.x = res2.x; p.y = res1.y + res2.y; return p; } else { printf("Error in tryPerm\n"); p.x = 0; p.y = 0; return p; } } pair initTryPerm(int x, int minLen) { int seq[1] = {1}; return tryPerm(0, 0, seq, x, 1, minLen); } void printArray(int a[], int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]\n"); } bool isBrauer(int a[], int len) { int i, j; bool ok; for (i = 2; i < len; ++i) { ok = FALSE; for (j = i - 1; j >= 0; j--) { if (a[i-1] + a[j] == a[i]) { ok = TRUE; break; } } if (!ok) return FALSE; } return TRUE; } bool isAdditionChain(int a[], int len) { int i, j, k; bool ok, exit; for (i = 2; i < len; ++i) { if (a[i] > a[i - 1] * 2) return FALSE; ok = FALSE; exit = FALSE; for (j = i - 1; j >= 0; --j) { for (k = j; k >= 0; --k) { if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; } } if (exit) break; } if (!ok) return FALSE; } if (example == NULL && !isBrauer(a, len)) { example = malloc(len * sizeof(int)); memcpy(example, a, len * sizeof(int)); exampleLen = len; } return TRUE; } void nextChains(int index, int len, int seq[], int *pcount) { for (;;) { int i; if (index < len - 1) { nextChains(index + 1, len, seq, pcount); } if (seq[index] + len - 1 - index >= seq[len - 1]) return; seq[index]++; for (i = index + 1; i < len - 1; ++i) { seq[i] = seq[i-1] + 1; } if (isAdditionChain(seq, len)) (*pcount)++; } } int findNonBrauer(int num, int len, int brauer) { int i, count = 0; int *seq = malloc(len * sizeof(int)); seq[0] = 1; seq[len - 1] = num; for (i = 1; i < len - 1; ++i) { seq[i] = seq[i - 1] + 1; } if (isAdditionChain(seq, len)) count = 1; nextChains(2, len, seq, &count); free(seq); return count - brauer; } void findBrauer(int num, int minLen, int nbLimit) { pair p = initTryPerm(num, minLen); int actualMin = p.x, brauer = p.y, nonBrauer; printf("\nN = %d\n", num); printf("Minimum length of chains : L(%d) = %d\n", num, actualMin); printf("Number of minimum length Brauer chains : %d\n", brauer); if (brauer > 0) { printf("Brauer example : "); reverse(example, exampleLen); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } if (num <= nbLimit) { nonBrauer = findNonBrauer(num, actualMin + 1, brauer); printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer); if (nonBrauer > 0) { printf("Non-Brauer example : "); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } } else { printf("Non-Brauer analysis suppressed\n"); } } int main() { int i; int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; printf("Searching for Brauer chains up to a minimum length of 12:\n"); for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79); return 0; }
package main import "fmt" var example []int func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func checkSeq(pos, n, minLen int, seq []int) (int, int) { switch { case pos > minLen || seq[0] > n: return minLen, 0 case seq[0] == n: example = seq return pos, 1 case pos < minLen: return tryPerm(0, pos, n, minLen, seq) default: return minLen, 0 } } func tryPerm(i, pos, n, minLen int, seq []int) (int, int) { if i > pos { return minLen, 0 } seq2 := make([]int, len(seq)+1) copy(seq2[1:], seq) seq2[0] = seq[0] + seq[i] res11, res12 := checkSeq(pos+1, n, minLen, seq2) res21, res22 := tryPerm(i+1, pos, n, res11, seq) switch { case res21 < res11: return res21, res22 case res21 == res11: return res21, res12 + res22 default: fmt.Println("Error in tryPerm") return 0, 0 } } func initTryPerm(x, minLen int) (int, int) { return tryPerm(0, 0, x, minLen, []int{1}) } func findBrauer(num, minLen, nbLimit int) { actualMin, brauer := initTryPerm(num, minLen) fmt.Println("\nN =", num) fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin) fmt.Println("Number of minimum length Brauer chains :", brauer) if brauer > 0 { reverse(example) fmt.Println("Brauer example :", example) } example = nil if num <= nbLimit { nonBrauer := findNonBrauer(num, actualMin+1, brauer) fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer) if nonBrauer > 0 { fmt.Println("Non-Brauer example :", example) } example = nil } else { println("Non-Brauer analysis suppressed") } } func isAdditionChain(a []int) bool { for i := 2; i < len(a); i++ { if a[i] > a[i-1]*2 { return false } ok := false jloop: for j := i - 1; j >= 0; j-- { for k := j; k >= 0; k-- { if a[j]+a[k] == a[i] { ok = true break jloop } } } if !ok { return false } } if example == nil && !isBrauer(a) { example = make([]int, len(a)) copy(example, a) } return true } func isBrauer(a []int) bool { for i := 2; i < len(a); i++ { ok := false for j := i - 1; j >= 0; j-- { if a[i-1]+a[j] == a[i] { ok = true break } } if !ok { return false } } return true } func nextChains(index, le int, seq []int, pcount *int) { for { if index < le-1 { nextChains(index+1, le, seq, pcount) } if seq[index]+le-1-index >= seq[le-1] { return } seq[index]++ for i := index + 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } if isAdditionChain(seq) { (*pcount)++ } } } func findNonBrauer(num, le, brauer int) int { seq := make([]int, le) seq[0] = 1 seq[le-1] = num for i := 1; i < le-1; i++ { seq[i] = seq[i-1] + 1 } count := 0 if isAdditionChain(seq) { count = 1 } nextChains(2, le, seq, &count) return count - brauer } func main() { nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} fmt.Println("Searching for Brauer chains up to a minimum length of 12:") for _, num := range nums { findBrauer(num, 12, 79) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <locale.h> #include <stdio.h> int main() { unsigned long long int trillion = 1000000000000; setlocale(LC_NUMERIC,""); printf("Locale : %s, One Trillion : %'llu\n", setlocale(LC_CTYPE,NULL),trillion); return 0; }
package main import "fmt" func main() { integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef} for _, integer := range integers { fmt.Printf("%d ", integer) } floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2} for _, float := range floats { fmt.Printf("%g ", float) } fmt.Println() }
Convert this C block to Go, preserving its control flow and logic.
#include <locale.h> #include <stdio.h> int main() { unsigned long long int trillion = 1000000000000; setlocale(LC_NUMERIC,""); printf("Locale : %s, One Trillion : %'llu\n", setlocale(LC_CTYPE,NULL),trillion); return 0; }
package main import "fmt" func main() { integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef} for _, integer := range integers { fmt.Printf("%d ", integer) } floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2} for _, float := range floats { fmt.Printf("%g ", float) } fmt.Println() }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
Generate an equivalent Go version of this C code.
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
package main import ( "bufio" "errors" "fmt" "math" "os" "regexp" "strconv" "strings" ) func main() { fmt.Println("Numbers please separated by space/commas:") sc := bufio.NewScanner(os.Stdin) sc.Scan() s, n, min, max, err := spark(sc.Text()) if err != nil { fmt.Println(err) return } if n == 1 { fmt.Println("1 value =", min) } else { fmt.Println(n, "values. Min:", min, "Max:", max) } fmt.Println(s) } var sep = regexp.MustCompile(`[\s,]+`) func spark(s0 string) (sp string, n int, min, max float64, err error) { ss := sep.Split(s0, -1) n = len(ss) vs := make([]float64, n) var v float64 min = math.Inf(1) max = math.Inf(-1) for i, s := range ss { switch v, err = strconv.ParseFloat(s, 64); { case err != nil: case math.IsNaN(v): err = errors.New("NaN not supported.") case math.IsInf(v, 0): err = errors.New("Inf not supported.") default: if v < min { min = v } if v > max { max = v } vs[i] = v continue } return } if min == max { sp = strings.Repeat("▄", n) } else { rs := make([]rune, n) f := 8 / (max - min) for j, v := range vs { i := rune(f * (v - min)) if i > 7 { i = 7 } rs[j] = '▁' + i } sp = string(rs) } return }
Change the following C code into Go without altering its purpose.
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
package main import ( "bufio" "errors" "fmt" "math" "os" "regexp" "strconv" "strings" ) func main() { fmt.Println("Numbers please separated by space/commas:") sc := bufio.NewScanner(os.Stdin) sc.Scan() s, n, min, max, err := spark(sc.Text()) if err != nil { fmt.Println(err) return } if n == 1 { fmt.Println("1 value =", min) } else { fmt.Println(n, "values. Min:", min, "Max:", max) } fmt.Println(s) } var sep = regexp.MustCompile(`[\s,]+`) func spark(s0 string) (sp string, n int, min, max float64, err error) { ss := sep.Split(s0, -1) n = len(ss) vs := make([]float64, n) var v float64 min = math.Inf(1) max = math.Inf(-1) for i, s := range ss { switch v, err = strconv.ParseFloat(s, 64); { case err != nil: case math.IsNaN(v): err = errors.New("NaN not supported.") case math.IsInf(v, 0): err = errors.New("Inf not supported.") default: if v < min { min = v } if v > max { max = v } vs[i] = v continue } return } if min == max { sp = strings.Repeat("▄", n) } else { rs := make([]rune, n) f := 8 / (max - min) for j, v := range vs { i := rune(f * (v - min)) if i > 7 { i = 7 } rs[j] = '▁' + i } sp = string(rs) } return }
Port the following code from C to Go with equivalent syntax and logic.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
Write the same code in Go as shown below in C.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
Convert the following code from C to Go, ensuring the logic remains intact.
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
Produce a functionally identical Go code for the snippet given in C.
#define WINVER 0x500 #include<windows.h> int main() { int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); int x = maxX/2, y = maxY/2; double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY; INPUT ip; ZeroMemory(&ip,sizeof(ip)); ip.type = INPUT_MOUSE; while(x > 5 || y < maxY-5){ ip.mi.mouseData = 0; ip.mi.dx = x * factorX; ip.mi.dy = y * factorY; ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; SendInput(1,&ip,sizeof(ip)); Sleep(1); if(x>3) x-=1; if(y<maxY-3) y+=1; } ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP; SendInput(1,&ip,sizeof(ip)); return 0; }
package main import "github.com/go-vgo/robotgo" func main() { robotgo.MouseClick("left", false) robotgo.MouseClick("right", true) }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#define WINVER 0x500 #include<windows.h> int main() { int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); int x = maxX/2, y = maxY/2; double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY; INPUT ip; ZeroMemory(&ip,sizeof(ip)); ip.type = INPUT_MOUSE; while(x > 5 || y < maxY-5){ ip.mi.mouseData = 0; ip.mi.dx = x * factorX; ip.mi.dy = y * factorY; ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; SendInput(1,&ip,sizeof(ip)); Sleep(1); if(x>3) x-=1; if(y<maxY-3) y+=1; } ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP; SendInput(1,&ip,sizeof(ip)); return 0; }
package main import "github.com/go-vgo/robotgo" func main() { robotgo.MouseClick("left", false) robotgo.MouseClick("right", true) }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Goodbye, World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintln(w, "Goodbye, World!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
Produce a functionally identical Go code for the snippet given in C.
#include<graphics.h> #include<math.h> #define pi M_PI void sunflower(int winWidth, int winHeight, double diskRatio, int iter){ double factor = .5 + sqrt(1.25),r,theta; double x = winWidth/2.0, y = winHeight/2.0; double maxRad = pow(iter,factor)/iter; int i; setbkcolor(LIGHTBLUE); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW); theta = 2*pi*factor*i; circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter)); } } int main() { initwindow(1000,1000,"Sunflower..."); sunflower(1000,1000,0.5,3000); getch(); closegraph(); return 0; }
package main import ( "github.com/fogleman/gg" "math" ) func main() { dc := gg.NewContext(400, 400) dc.SetRGB(1, 1, 1) dc.Clear() dc.SetRGB(0, 0, 1) c := (math.Sqrt(5) + 1) / 2 numberOfSeeds := 3000 for i := 0; i <= numberOfSeeds; i++ { fi := float64(i) fn := float64(numberOfSeeds) r := math.Pow(fi, c) / fn angle := 2 * math.Pi * c * fi x := r*math.Sin(angle) + 200 y := r*math.Cos(angle) + 200 fi /= fn / 5 dc.DrawCircle(x, y, fi) } dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("sunflower_fractal.png") }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 4 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 5 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 461, 277, 356, 488, 393 }; int demand[N_COLS] = { 278, 60, 461, 116, 1060 }; int costs[N_ROWS][N_COLS] = { { 46, 74, 9, 28, 99 }, { 12, 75, 6, 36, 48 }, { 35, 199, 4, 5, 71 }, { 61, 81, 44, 88, 9 }, { 85, 60, 14, 25, 79 } }; int main() { printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'V' + i); for (j = 0; j < N_COLS; ++j) printf(" %3d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <math.h> #include <stdio.h> #define DEG 0.017453292519943295769236907684886127134 #define RE 6371000.0 #define DD 0.001 #define FIN 10000000.0 static double rho(double a) { return exp(-a / 8500.0); } static double height(double a, double z, double d) { double aa = RE + a; double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG)); return hh - RE; } static double column_density(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = DD * d; if (delta < DD) delta = DD; sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } static double airmass(double a, double z) { return column_density(a, z) / column_density(a, 0.0); } int main() { puts("Angle 0 m 13700 m"); puts("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } }
package main import ( "fmt" "math" ) const ( RE = 6371000 DD = 0.001 FIN = 1e7 ) func rho(a float64) float64 { return math.Exp(-a / 8500) } func radians(degrees float64) float64 { return degrees * math.Pi / 180 } func height(a, z, d float64) float64 { aa := RE + a hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z))) return hh - RE } func columnDensity(a, z float64) float64 { sum := 0.0 d := 0.0 for d < FIN { delta := math.Max(DD, DD*d) sum += rho(height(a, z, d+0.5*delta)) * delta d += delta } return sum } func airmass(a, z float64) float64 { return columnDensity(a, z) / columnDensity(a, 0) } func main() { fmt.Println("Angle 0 m 13700 m") fmt.Println("------------------------------------") for z := 0; z <= 90; z += 5 { fz := float64(z) fmt.Printf("%2d %11.8f %11.8f\n", z, airmass(0, fz), airmass(13700, fz)) } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdlib.h> #include <math.h> enum fps_type { FPS_CONST = 0, FPS_ADD, FPS_SUB, FPS_MUL, FPS_DIV, FPS_DERIV, FPS_INT, }; typedef struct fps_t *fps; typedef struct fps_t { int type; fps s1, s2; double a0; } fps_t; fps fps_new() { fps x = malloc(sizeof(fps_t)); x->a0 = 0; x->s1 = x->s2 = 0; x->type = 0; return x; } void fps_redefine(fps x, int op, fps y, fps z) { x->type = op; x->s1 = y; x->s2 = z; } fps _binary(fps x, fps y, int op) { fps s = fps_new(); s->s1 = x; s->s2 = y; s->type = op; return s; } fps _unary(fps x, int op) { fps s = fps_new(); s->s1 = x; s->type = op; return s; } double term(fps x, int n) { double ret = 0; int i; switch (x->type) { case FPS_CONST: return n > 0 ? 0 : x->a0; case FPS_ADD: ret = term(x->s1, n) + term(x->s2, n); break; case FPS_SUB: ret = term(x->s1, n) - term(x->s2, n); break; case FPS_MUL: for (i = 0; i <= n; i++) ret += term(x->s1, i) * term(x->s2, n - i); break; case FPS_DIV: if (! term(x->s2, 0)) return NAN; ret = term(x->s1, n); for (i = 1; i <= n; i++) ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0); break; case FPS_DERIV: ret = n * term(x->s1, n + 1); break; case FPS_INT: if (!n) return x->a0; ret = term(x->s1, n - 1) / n; break; default: fprintf(stderr, "Unknown operator %d\n", x->type); exit(1); } return ret; } #define _add(x, y) _binary(x, y, FPS_ADD) #define _sub(x, y) _binary(x, y, FPS_SUB) #define _mul(x, y) _binary(x, y, FPS_MUL) #define _div(x, y) _binary(x, y, FPS_DIV) #define _integ(x) _unary(x, FPS_INT) #define _deriv(x) _unary(x, FPS_DERIV) fps fps_const(double a0) { fps x = fps_new(); x->type = FPS_CONST; x->a0 = a0; return x; } int main() { int i; fps one = fps_const(1); fps fcos = fps_new(); fps fsin = _integ(fcos); fps ftan = _div(fsin, fcos); fps_redefine(fcos, FPS_SUB, one, _integ(fsin)); fps fexp = fps_const(1); fps_redefine(fexp, FPS_INT, fexp, 0); printf("Sin:"); for (i = 0; i < 10; i++) printf(" %g", term(fsin, i)); printf("\nCos:"); for (i = 0; i < 10; i++) printf(" %g", term(fcos, i)); printf("\nTan:"); for (i = 0; i < 10; i++) printf(" %g", term(ftan, i)); printf("\nExp:"); for (i = 0; i < 10; i++) printf(" %g", term(fexp, i)); return 0; }
package main import ( "fmt" "math" ) type fps interface { extract(int) float64 } func one() fps { return &oneFps{} } func add(s1, s2 fps) fps { return &sum{s1: s1, s2: s2} } func sub(s1, s2 fps) fps { return &diff{s1: s1, s2: s2} } func mul(s1, s2 fps) fps { return &prod{s1: s1, s2: s2} } func div(s1, s2 fps) fps { return &quo{s1: s1, s2: s2} } func differentiate(s1 fps) fps { return &deriv{s1: s1} } func integrate(s1 fps) fps { return &integ{s1: s1} } func sinCos() (fps, fps) { sin := &integ{} cos := sub(one(), integrate(sin)) sin.s1 = cos return sin, cos } type oneFps struct{} func (*oneFps) extract(n int) float64 { if n == 0 { return 1 } return 0 } type sum struct { s []float64 s1, s2 fps } func (s *sum) extract(n int) float64 { for i := len(s.s); i <= n; i++ { s.s = append(s.s, s.s1.extract(i)+s.s2.extract(i)) } return s.s[n] } type diff struct { s []float64 s1, s2 fps } func (s *diff) extract(n int) float64 { for i := len(s.s); i <= n; i++ { s.s = append(s.s, s.s1.extract(i)-s.s2.extract(i)) } return s.s[n] } type prod struct { s []float64 s1, s2 fps } func (s *prod) extract(n int) float64 { for i := len(s.s); i <= n; i++ { c := 0. for k := 0; k <= i; k++ { c += s.s1.extract(k) * s.s1.extract(n-k) } s.s = append(s.s, c) } return s.s[n] } type quo struct { s1, s2 fps inv float64 c []float64 s []float64 } func (s *quo) extract(n int) float64 { switch { case len(s.s) > 0: case !math.IsInf(s.inv, 1): a0 := s.s2.extract(0) s.inv = 1 / a0 if a0 != 0 { break } fallthrough default: return math.NaN() } for i := len(s.s); i <= n; i++ { c := 0. for k := 1; k <= i; k++ { c += s.s2.extract(k) * s.c[n-k] } c = s.s1.extract(i) - c*s.inv s.c = append(s.c, c) s.s = append(s.s, c*s.inv) } return s.s[n] } type deriv struct { s []float64 s1 fps } func (s *deriv) extract(n int) float64 { for i := len(s.s); i <= n; { i++ s.s = append(s.s, float64(i)*s.s1.extract(i)) } return s.s[n] } type integ struct { s []float64 s1 fps } func (s *integ) extract(n int) float64 { if n == 0 { return 0 } for i := len(s.s) + 1; i <= n; i++ { s.s = append(s.s, s.s1.extract(i-1)/float64(i)) } return s.s[n-1] } func main() { partialSeries := func(f fps) (s string) { for i := 0; i < 6; i++ { s = fmt.Sprintf("%s %8.5f ", s, f.extract(i)) } return } sin, cos := sinCos() fmt.Println("sin:", partialSeries(sin)) fmt.Println("cos:", partialSeries(cos)) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <math.h> #define MAX_DIGITS 9 int digits[MAX_DIGITS]; void getDigits(int i) { int ix = 0; while (i > 0) { digits[ix++] = i % 10; i /= 10; } } int main() { int n, d, i, max, lastDigit, sum, dp; int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}; printf("Own digits power sums for N = 3 to 9 inclusive:\n"); for (n = 3; n < 10; ++n) { for (d = 2; d < 10; ++d) powers[d] *= d; i = (int)pow(10, n-1); max = i * 10; lastDigit = 0; while (i < max) { if (!lastDigit) { getDigits(i); sum = 0; for (d = 0; d < n; ++d) { dp = digits[d]; sum += powers[dp]; } } else if (lastDigit == 1) { sum++; } else { sum += powers[lastDigit] - powers[lastDigit-1]; } if (sum == i) { printf("%d\n", i); if (lastDigit == 0) printf("%d\n", i + 1); i += 10 - lastDigit; lastDigit = 0; } else if (sum > i) { i += 10 - lastDigit; lastDigit = 0; } else if (lastDigit < 9) { i++; lastDigit++; } else { i++; lastDigit = 0; } } } return 0; }
package main import ( "fmt" "math" "rcu" ) func main() { powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81} fmt.Println("Own digits power sums for N = 3 to 9 inclusive:") for n := 3; n < 10; n++ { for d := 2; d < 10; d++ { powers[d] *= d } i := int(math.Pow(10, float64(n-1))) max := i * 10 lastDigit := 0 sum := 0 var digits []int for i < max { if lastDigit == 0 { digits = rcu.Digits(i, 10) sum = 0 for _, d := range digits { sum += powers[d] } } else if lastDigit == 1 { sum++ } else { sum += powers[lastDigit] - powers[lastDigit-1] } if sum == i { fmt.Println(i) if lastDigit == 0 { fmt.Println(i + 1) } i += 10 - lastDigit lastDigit = 0 } else if sum > i { i += 10 - lastDigit lastDigit = 0 } else if lastDigit < 9 { i++ lastDigit++ } else { i++ lastDigit = 0 } } } }
Change the following C code into Go without altering its purpose.
void cubic_bezier( image img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int x3, unsigned int y3, unsigned int x4, unsigned int y4, color_component r, color_component g, color_component b );
package raster const b3Seg = 30 func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) { var px, py [b3Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) fx4, fy4 := float64(x4), float64(y4) for i := range px { d := float64(i) / b3Seg a := 1 - d b, c := a * a, d * d a, b, c, d = a*b, 3*b*d, 3*a*c, c*d px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4) py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4) } x0, y0 := px[0], py[0] for i := 1; i <= b3Seg; i++ { x1, y1 := px[i], py[i] b.Line(x0, y0, x1, y1, p) x0, y0 = x1, y1 } } func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) { b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel()) }
Generate a Go translation of this C snippet without changing its computational steps.
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
package main import "fmt" func main() { list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) list.sort() fmt.Println("sorted! ", list) } type pancake []int func (a pancake) sort() { for uns := len(a) - 1; uns > 0; uns-- { lx, lg := 0, a[0] for i := 1; i <= uns; i++ { if a[i] > lg { lx, lg = i, a[i] } } a.flip(lx) a.flip(uns) } } func (a pancake) flip(r int) { for l := 0; l < r; l, r = l+1, r-1 { a[l], a[r] = a[r], a[l] } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #define DIGITS 1000 #define NUMSIZE 5 uint8_t randomDigit() { uint8_t d; do {d = rand() & 0xF;} while (d >= 10); return d; } int numberAt(uint8_t *d, int size) { int acc = 0; while (size--) acc = 10*acc + *d++; return acc; } int main() { uint8_t digits[DIGITS]; int i, largest = 0; srand(time(NULL)); for (i=0; i<DIGITS; i++) digits[i] = randomDigit(); for (i=0; i<DIGITS-NUMSIZE; i++) { int here = numberAt(&digits[i], NUMSIZE); if (here > largest) largest = here; } printf("%d\n", largest); return 0; }
package main import ( "fmt" "math/rand" "rcu" "strings" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var sb strings.Builder for i := 0; i < 1000; i++ { sb.WriteByte(byte(rand.Intn(10) + 48)) } number := sb.String() for i := 99999; i >= 0; i-- { quintet := fmt.Sprintf("%05d", i) if strings.Contains(number, quintet) { ci := rcu.Commatize(i) fmt.Printf("The largest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci) break } } for i := 0; i <= 99999; i++ { quintet := fmt.Sprintf("%05d", i) if strings.Contains(number, quintet) { ci := rcu.Commatize(i) fmt.Printf("The smallest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci) return } } }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #define DIGITS 1000 #define NUMSIZE 5 uint8_t randomDigit() { uint8_t d; do {d = rand() & 0xF;} while (d >= 10); return d; } int numberAt(uint8_t *d, int size) { int acc = 0; while (size--) acc = 10*acc + *d++; return acc; } int main() { uint8_t digits[DIGITS]; int i, largest = 0; srand(time(NULL)); for (i=0; i<DIGITS; i++) digits[i] = randomDigit(); for (i=0; i<DIGITS-NUMSIZE; i++) { int here = numberAt(&digits[i], NUMSIZE); if (here > largest) largest = here; } printf("%d\n", largest); return 0; }
package main import ( "fmt" "math/rand" "rcu" "strings" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var sb strings.Builder for i := 0; i < 1000; i++ { sb.WriteByte(byte(rand.Intn(10) + 48)) } number := sb.String() for i := 99999; i >= 0; i-- { quintet := fmt.Sprintf("%05d", i) if strings.Contains(number, quintet) { ci := rcu.Commatize(i) fmt.Printf("The largest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci) break } } for i := 0; i <= 99999; i++ { quintet := fmt.Sprintf("%05d", i) if strings.Contains(number, quintet) { ci := rcu.Commatize(i) fmt.Printf("The smallest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci) return } } }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #include <stdbool.h> int digit_sum(int n) { int sum; for (sum = 0; n; n /= 10) sum += n % 10; return sum; } bool prime(int n) { if (n<4) return n>=2; for (int d=2; d*d <= n; d++) if (n%d == 0) return false; return true; } int main() { for (int i=1; i<100; i++) if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i))) printf("%d ", i); printf("\n"); return 0; }
package main import ( "fmt" "rcu" ) func main() { for i := 1; i < 100; i++ { if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) { continue } if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) { fmt.Printf("%d ", i) } } fmt.Println() }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(void) { int nprimes = 1000000; int nmax = ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385)); int i, j, m, k; int *a; k = (nmax-2)/2; a = (int *)calloc(k + 1, sizeof(int)); for(i = 0; i <= k; i++)a[i] = 2*i+1; for (i = 1; (i+1)*i*2 <= k; i++) for (j = i; j <= (k-i)/(2*i+1); j++) { m = i + j + 2*i*j; if(a[m]) a[m] = 0; } for (i = 1, j = 0; i <= k; i++) if (a[i]) { if(j%10 == 0 && j <= 100)printf("\n"); j++; if(j <= 100)printf("%3d ", a[i]); else if(j == nprimes){ printf("\n%d th prime is %d\n",j,a[i]); break; } } }
package main import ( "fmt" "math" "rcu" "time" ) func sos(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k) limit := (int(math.Sqrt(float64(n)))-3)/2 + 1 for i := 0; i < limit; i++ { p := 2*i + 3 s := (p*p - 3) / 2 for j := s; j < k; j += p { marked[j] = true } } for i := 0; i < k; i++ { if !marked[i] { primes = append(primes, 2*i+3) } } return primes } func soe(n int) []int { if n < 3 { return []int{} } var primes []int k := (n-3)/2 + 1 marked := make([]bool, k) limit := (int(math.Sqrt(float64(n)))-3)/2 + 1 for i := 0; i < limit; i++ { if !marked[i] { p := 2*i + 3 s := (p*p - 3) / 2 for j := s; j < k; j += p { marked[j] = true } } } for i := 0; i < k; i++ { if !marked[i] { primes = append(primes, 2*i+3) } } return primes } func main() { const limit = int(16e6) start := time.Now() primes := sos(limit) elapsed := int(time.Since(start).Milliseconds()) climit := rcu.Commatize(limit) celapsed := rcu.Commatize(elapsed) million := rcu.Commatize(1e6) millionth := rcu.Commatize(primes[1e6-1]) fmt.Printf("Using the Sieve of Sundaram generated primes up to %s in %s ms.\n\n", climit, celapsed) fmt.Println("First 100 odd primes generated by the Sieve of Sundaram:") for i, p := range primes[0:100] { fmt.Printf("%3d ", p) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\nThe %s Sundaram prime is %s\n", million, millionth) start = time.Now() primes = soe(limit) elapsed = int(time.Since(start).Milliseconds()) celapsed = rcu.Commatize(elapsed) millionth = rcu.Commatize(primes[1e6-1]) fmt.Printf("\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\n", celapsed) fmt.Printf("\nAs a check, the %s Sundaram prime would again have been %s\n", million, millionth) }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <ldap.h> ... char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); ... after done with it... ldap_unbind(ld);
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=example,dc=com", BindPassword: "readonlypassword", UserFilter: "(uid=%s)", GroupFilter: "(memberUid=%s)", Attributes: []string{"givenName", "sn", "mail", "uid"}, } defer client.Close() err := client.Connect() if err != nil { log.Fatalf("Failed to connect : %+v", err) } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <stdbool.h> bool three_3s(const int *items, size_t len) { int threes = 0; while (len--) if (*items++ == 3) if (threes<3) threes++; else return false; else if (threes != 0 && threes != 3) return false; return true; } void print_list(const int *items, size_t len) { while (len--) printf("%d ", *items++); } int main() { int lists[][9] = { {9,3,3,3,2,1,7,8,5}, {5,2,9,3,3,6,8,4,1}, {1,4,3,6,7,3,8,3,2}, {1,2,3,4,5,6,7,8,9}, {4,6,8,7,2,3,3,3,1} }; size_t list_length = sizeof(lists[0]) / sizeof(int); size_t n_lists = sizeof(lists) / sizeof(lists[0]); for (size_t i=0; i<n_lists; i++) { print_list(lists[i], list_length); printf("-> %s\n", three_3s(lists[i], list_length) ? "true" : "false"); } return 0; }
package main import "fmt" func main() { lists := [][]int{ {9, 3, 3, 3, 2, 1, 7, 8, 5}, {5, 2, 9, 3, 3, 7, 8, 4, 1}, {1, 4, 3, 6, 7, 3, 8, 3, 2}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {4, 6, 8, 7, 2, 3, 3, 3, 1}, {3, 3, 3, 1, 2, 4, 5, 1, 3}, {0, 3, 3, 3, 3, 7, 2, 2, 6}, {3, 3, 3, 3, 3, 4, 4, 4, 4}, } for d := 1; d <= 4; d++ { fmt.Printf("Exactly %d adjacent %d's:\n", d, d) for _, list := range lists { var indices []int for i, e := range list { if e == d { indices = append(indices, i) } } adjacent := false if len(indices) == d { adjacent = true for i := 1; i < len(indices); i++ { if indices[i]-indices[i-1] != 1 { adjacent = false break } } } fmt.Printf("%v -> %t\n", list, adjacent) } fmt.Println() } }
Generate a Go translation of this C snippet without changing its computational steps.
#include<stdlib.h> #include<string.h> #include<stdio.h> int flag = 1; void heapPermute(int n, int arr[],int arrLen){ int temp; int i; if(n==1){ printf("\n["); for(i=0;i<arrLen;i++) printf("%d,",arr[i]); printf("\b] Sign : %d",flag); flag*=-1; } else{ for(i=0;i<n-1;i++){ heapPermute(n-1,arr,arrLen); if(n%2==0){ temp = arr[i]; arr[i] = arr[n-1]; arr[n-1] = temp; } else{ temp = arr[0]; arr[0] = arr[n-1]; arr[n-1] = temp; } } heapPermute(n-1,arr,arrLen); } } int main(int argC,char* argV[0]) { int *arr, i=0, count = 1; char* token; if(argC==1) printf("Usage : %s <comma separated list of integers>",argV[0]); else{ while(argV[1][i]!=00){ if(argV[1][i++]==',') count++; } arr = (int*)malloc(count*sizeof(int)); i = 0; token = strtok(argV[1],","); while(token!=NULL){ arr[i++] = atoi(token); token = strtok(NULL,","); } heapPermute(i,arr,count); } return 0; }
package permute func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } } func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } default: p0 := pf(n - 1) i := n var d int return func(p []int) int { switch { case sign == 0: case i == n: i-- sign = p0(p[:i]) d = -1 case i == 0: i++ sign *= p0(p[1:]) d = 1 if sign == 0 { p[0], p[1] = p[1], p[0] } default: p[i], p[i-1] = p[i-1], p[i] sign = -sign i += d } return sign } } }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> unsigned digit_sum(unsigned n) { unsigned sum = 0; do { sum += n % 10; } while(n /= 10); return sum; } unsigned a131382(unsigned n) { unsigned m; for (m = 1; n != digit_sum(m*n); m++); return m; } int main() { unsigned n; for (n = 1; n <= 70; n++) { printf("%9u", a131382(n)); if (n % 10 == 0) printf("\n"); } return 0; }
package main import "rcu" func main() { var res []int for n := 1; n <= 70; n++ { m := 1 for rcu.DigitSum(m*n, 10) != n { m++ } res = append(res, m) } rcu.PrintTable(res, 7, 10, true) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <math.h> #include <string.h> #define N 2200 int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
package main import "fmt" const ( N = 2200 N2 = N * N * 2 ) func main() { s := 3 var s1, s2 int var r [N + 1]bool var ab [N2 + 1]bool for a := 1; a <= N; a++ { a2 := a * a for b := a; b <= N; b++ { ab[a2 + b * b] = true } } for c := 1; c <= N; c++ { s1 = s s += 2 s2 = s for d := c + 1; d <= N; d++ { if ab[s1] { r[d] = true } s1 += s2 s2 += 2 } } for d := 1; d <= N; d++ { if !r[d] { fmt.Printf("%d ", d) } } fmt.Println() }
Change the following C code into Go without altering its purpose.
#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <string.h> static const int d[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; static const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; static const int p[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; int verhoeff(const char* s, bool validate, bool verbose) { if (verbose) { const char* t = validate ? "Validation" : "Check digit"; printf("%s calculations for '%s':\n\n", t, s); puts(u8" i n\xE1\xB5\xA2 p[i,n\xE1\xB5\xA2] c"); puts("------------------"); } int len = strlen(s); if (validate) --len; int c = 0; for (int i = len; i >= 0; --i) { int ni = (i == len && !validate) ? 0 : s[i] - '0'; assert(ni >= 0 && ni < 10); int pi = p[(len - i) % 8][ni]; c = d[c][pi]; if (verbose) printf("%2d %d %d %d\n", len - i, ni, pi, c); } if (verbose && !validate) printf("\ninv[%d] = %d\n", c, inv[c]); return validate ? c == 0 : inv[c]; } int main() { const char* ss[3] = {"236", "12345", "123456789012"}; for (int i = 0; i < 3; ++i) { const char* s = ss[i]; bool verbose = i < 2; int c = verhoeff(s, false, verbose); printf("\nThe check digit for '%s' is '%d'.\n", s, c); int len = strlen(s); char sc[len + 2]; strncpy(sc, s, len + 2); for (int j = 0; j < 2; ++j) { sc[len] = (j == 0) ? c + '0' : '9'; int v = verhoeff(sc, true, verbose); printf("\nThe validation for '%s' is %s.\n", sc, v ? "correct" : "incorrect"); } } return 0; }
package main import "fmt" var d = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, } var inv = []int{0, 4, 3, 2, 1, 5, 6, 7, 8, 9} var p = [][]int{ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, } func verhoeff(s string, validate, table bool) interface{} { if table { t := "Check digit" if validate { t = "Validation" } fmt.Printf("%s calculations for '%s':\n\n", t, s) fmt.Println(" i nᵢ p[i,nᵢ] c") fmt.Println("------------------") } if !validate { s = s + "0" } c := 0 le := len(s) - 1 for i := le; i >= 0; i-- { ni := int(s[i] - 48) pi := p[(le-i)%8][ni] c = d[c][pi] if table { fmt.Printf("%2d %d %d %d\n", le-i, ni, pi, c) } } if table && !validate { fmt.Printf("\ninv[%d] = %d\n", c, inv[c]) } if !validate { return inv[c] } return c == 0 } func main() { ss := []string{"236", "12345", "123456789012"} ts := []bool{true, true, false, true} for i, s := range ss { c := verhoeff(s, false, ts[i]).(int) fmt.Printf("\nThe check digit for '%s' is '%d'\n\n", s, c) for _, sc := range []string{s + string(c+48), s + "9"} { v := verhoeff(sc, true, ts[i]).(bool) ans := "correct" if !v { ans = "incorrect" } fmt.Printf("\nThe validation for '%s' is %s\n\n", sc, ans) } } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <stdbool.h> bool steady(int n) { int mask = 1; for (int d = n; d != 0; d /= 10) mask *= 10; return (n * n) % mask == n; } int main() { for (int i = 1; i < 10000; i++) if (steady(i)) printf("%4d^2 = %8d\n", i, i * i); return 0; }
package main import ( "fmt" "rcu" "strconv" "strings" ) func contains(list []int, s int) bool { for _, e := range list { if e == s { return true } } return false } func main() { fmt.Println("Steady squares under 10,000:") finalDigits := []int{1, 5, 6} for i := 1; i < 10000; i++ { if !contains(finalDigits, i%10) { continue } sq := i * i sqs := strconv.Itoa(sq) is := strconv.Itoa(i) if strings.HasSuffix(sqs, is) { fmt.Printf("%5s -> %10s\n", rcu.Commatize(i), rcu.Commatize(sq)) } } }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> #define MAXIMUM 25000 int reverse(int n, int base) { int r; for (r = 0; n; n /= base) r = r*base + n%base; return r; } int palindrome(int n, int base) { return n == reverse(n, base); } int main() { int i, c = 0; for (i = 0; i < MAXIMUM; i++) { if (palindrome(i, 2) && palindrome(i, 4) && palindrome(i, 16)) { printf("%5d%c", i, ++c % 12 ? ' ' : '\n'); } } printf("\n"); return 0; }
package main import ( "fmt" "rcu" "strconv" ) func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { fmt.Println("Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:") var numbers []int for i := int64(0); i < 25000; i++ { b2 := strconv.FormatInt(i, 2) if b2 == reverse(b2) { b4 := strconv.FormatInt(i, 4) if b4 == reverse(b4) { b16 := strconv.FormatInt(i, 16) if b16 == reverse(b16) { numbers = append(numbers, int(i)) } } } } for i, n := range numbers { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(numbers), "such numbers.") }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int trial, secs_tot=0, steps_tot=0; int sbeh, slen, wiz, secs; time_t t; srand((unsigned) time(&t)); printf( "Seconds steps behind steps ahead\n" ); for( trial=1;trial<=10000;trial++ ) { sbeh = 0; slen = 100; secs = 0; while(sbeh<slen) { sbeh+=1; for(wiz=1;wiz<=5;wiz++) { if(rand()%slen < sbeh) sbeh+=1; slen+=1; } secs+=1; if(trial==1&&599<secs&&secs<610) printf("%d %d %d\n", secs, sbeh, slen-sbeh ); } secs_tot+=secs; steps_tot+=slen; } printf( "Average secs taken: %f\n", secs_tot/10000.0 ); printf( "Average final length of staircase: %f\n", steps_tot/10000.0 ); return 0; }
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) totalSecs := 0 totalSteps := 0 fmt.Println("Seconds steps behind steps ahead") fmt.Println("------- ------------ -----------") for trial := 1; trial < 10000; trial++ { sbeh := 0 slen := 100 secs := 0 for sbeh < slen { sbeh++ for wiz := 1; wiz < 6; wiz++ { if rand.Intn(slen) < sbeh { sbeh++ } slen++ } secs++ if trial == 1 && secs > 599 && secs < 610 { fmt.Printf("%d %d %d\n", secs, sbeh, slen-sbeh) } } totalSecs += secs totalSteps += slen } fmt.Println("\nAverage secs taken:", float64(totalSecs)/10000) fmt.Println("Average final length of staircase:", float64(totalSteps)/10000) }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <windows.h> #include <wchar.h> int main() { CONSOLE_SCREEN_BUFFER_INFO info; COORD pos; HANDLE conout; long len; wchar_t c; conout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (conout == INVALID_HANDLE_VALUE) return 1; if (GetConsoleScreenBufferInfo(conout, &info) == 0) return 1; pos.X = info.srWindow.Left + 3; pos.Y = info.srWindow.Top + 6; if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 || len <= 0) return 1; wprintf(L"Character at (3, 6) had been '%lc'\n", c); return 0; }
package main import "C" import "fmt" func main() { for i := 0; i < 80*25; i++ { fmt.Print("A") } fmt.Println() conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE) info := C.CONSOLE_SCREEN_BUFFER_INFO{} pos := C.COORD{} C.GetConsoleScreenBufferInfo(conOut, &info) pos.X = info.srWindow.Left + 3 pos.Y = info.srWindow.Top + 6 var c C.wchar_t var le C.ulong ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le) if ret == 0 || le <= 0 { fmt.Println("Something went wrong!") return } fmt.Printf("The character at column 3, row 6 is '%c'\n", c) }