Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this C code in Go.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <signal.h> #include <time.h> #include <sys/time.h> struct timeval start, last; inline int64_t tv_to_u(struct timeval s) { return s.tv_sec * 1000000 + s.tv_usec; } inline struct timeval u_to_tv(int64_t x) { struct timeval s; s.tv_sec = x / 1000000; s.tv_usec = x % 1000000; return s; } void draw(int dir, int64_t period, int64_t cur, int64_t next) { int len = 40 * (next - cur) / period; int s, i; if (len > 20) len = 40 - len; s = 20 + (dir ? len : -len); printf("\033[H"); for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-'); } void beat(int delay) { struct timeval tv = start; int dir = 0; int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay; int64_t draw_interval = 20000; printf("\033[H\033[J"); while (1) { gettimeofday(&tv, 0); slp = next - tv_to_u(tv) - corr; usleep(slp); gettimeofday(&tv, 0); putchar(7); fflush(stdout); printf("\033[5;1Hdrift: %d compensate: %d (usec) ", (int)d, (int)corr); dir = !dir; cur = tv_to_u(tv); d = cur - next; corr = (corr + d) / 2; next += delay; while (cur + d + draw_interval < next) { usleep(draw_interval); gettimeofday(&tv, 0); cur = tv_to_u(tv); draw(dir, delay, cur, next); fflush(stdout); } } } int main(int c, char**v) { int bpm; if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60; if (bpm > 600) { fprintf(stderr, "frequency %d too high\n", bpm); exit(1); } gettimeofday(&start, 0); last = start; beat(60 * 1000000 / bpm); return 0; }
package main import ( "fmt" "time" ) func main() { var bpm = 72.0 var bpb = 4 d := time.Duration(float64(time.Minute) / bpm) fmt.Println("Delay:", d) t := time.NewTicker(d) i := 1 for _ = range t.C { i-- if i == 0 { i = bpb fmt.Printf("\nTICK ") } else { fmt.Printf("tick ") } } }
Translate this program into Go but keep the logic exactly as in C.
#!/usr/local/bin/script_gcc.sh #include <errno.h> #include <libgen.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> typedef char *STRING; typedef enum{FALSE=0, TRUE=1} BOOL; const STRING ENDCAT = NULL; #define DIALECT "c" const STRING CC="gcc", COPTS="-lm -x "DIALECT, IEXT="."DIALECT, OEXT=".out"; const BOOL OPT_CACHE = TRUE; char strcat_out[BUFSIZ]; STRING STRCAT(STRING argv, ... ){ va_list ap; va_start(ap, argv); STRING arg; strcat_out[0]='\0'; for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){ strncat(strcat_out, arg, sizeof strcat_out); } va_end(ap); return strndup(strcat_out, sizeof strcat_out); } char itoa_out[BUFSIZ]; STRING itoa_(int i){ sprintf(itoa_out, "%d", i); return itoa_out; } time_t modtime(STRING filename){ struct stat buf; if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename); return buf.st_mtime; } BOOL compile(STRING srcpath, STRING binpath){ int out; STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT); FILE *src=fopen(srcpath, "r"), *compiler=popen(compiler_command, "w"); char buf[BUFSIZ]; BOOL shebang; for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE) if(!shebang)fwrite(buf, strlen(buf), 1, compiler); out=pclose(compiler); return out; } void main(int argc, STRING *argv, STRING *envp){ STRING binpath, srcpath=argv[1], argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT), *dirnamew, *dirnamex; argv++; STRING paths[] = { dirname(strdup(srcpath)), STRCAT(getenv("HOME"), "/bin", ENDCAT), "/usr/local/bin", ".", STRCAT(getenv("HOME"), "/tmp", ENDCAT), getenv("HOME"), STRCAT(getenv("HOME"), "/Desktop", ENDCAT), ENDCAT }; for(dirnamew = paths; *dirnamew; dirnamew++){ if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break; } if(OPT_CACHE == FALSE){ binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT); if(compile(srcpath, binpath) == EXIT_SUCCESS){ if(fork()){ sleep(0.1); unlink(binpath); } else { execvp(binpath, argv); } } } else { time_t modtime_srcpath = modtime(srcpath); for(dirnamex = paths; *dirnamex; dirnamex++){ binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT); if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath)) execvp(binpath, argv); } } binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT); if(compile(srcpath, binpath) == EXIT_SUCCESS) execvp(binpath, argv); perror(STRCAT(binpath, ": executable not available", ENDCAT)); exit(errno); }
package main import ( "fmt" "os" ) func main() { if len(os.Args) > 1 { fmt.Println(os.Args[1]) } }
Ensure the translated Go code behaves exactly like the original C snippet.
#!/usr/local/bin/script_gcc.sh #include <errno.h> #include <libgen.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> typedef char *STRING; typedef enum{FALSE=0, TRUE=1} BOOL; const STRING ENDCAT = NULL; #define DIALECT "c" const STRING CC="gcc", COPTS="-lm -x "DIALECT, IEXT="."DIALECT, OEXT=".out"; const BOOL OPT_CACHE = TRUE; char strcat_out[BUFSIZ]; STRING STRCAT(STRING argv, ... ){ va_list ap; va_start(ap, argv); STRING arg; strcat_out[0]='\0'; for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){ strncat(strcat_out, arg, sizeof strcat_out); } va_end(ap); return strndup(strcat_out, sizeof strcat_out); } char itoa_out[BUFSIZ]; STRING itoa_(int i){ sprintf(itoa_out, "%d", i); return itoa_out; } time_t modtime(STRING filename){ struct stat buf; if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename); return buf.st_mtime; } BOOL compile(STRING srcpath, STRING binpath){ int out; STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT); FILE *src=fopen(srcpath, "r"), *compiler=popen(compiler_command, "w"); char buf[BUFSIZ]; BOOL shebang; for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE) if(!shebang)fwrite(buf, strlen(buf), 1, compiler); out=pclose(compiler); return out; } void main(int argc, STRING *argv, STRING *envp){ STRING binpath, srcpath=argv[1], argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT), *dirnamew, *dirnamex; argv++; STRING paths[] = { dirname(strdup(srcpath)), STRCAT(getenv("HOME"), "/bin", ENDCAT), "/usr/local/bin", ".", STRCAT(getenv("HOME"), "/tmp", ENDCAT), getenv("HOME"), STRCAT(getenv("HOME"), "/Desktop", ENDCAT), ENDCAT }; for(dirnamew = paths; *dirnamew; dirnamew++){ if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break; } if(OPT_CACHE == FALSE){ binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT); if(compile(srcpath, binpath) == EXIT_SUCCESS){ if(fork()){ sleep(0.1); unlink(binpath); } else { execvp(binpath, argv); } } } else { time_t modtime_srcpath = modtime(srcpath); for(dirnamex = paths; *dirnamex; dirnamex++){ binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT); if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath)) execvp(binpath, argv); } } binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT); if(compile(srcpath, binpath) == EXIT_SUCCESS) execvp(binpath, argv); perror(STRCAT(binpath, ": executable not available", ENDCAT)); exit(errno); }
package main import ( "fmt" "os" ) func main() { if len(os.Args) > 1 { fmt.Println(os.Args[1]) } }
Produce a language-to-language conversion: from C to Go, same semantics.
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define LIMIT 100 typedef int bool; int compareInts(const void *a, const void *b) { int aa = *(int *)a; int bb = *(int *)b; return aa - bb; } bool contains(int a[], int b, size_t len) { int i; for (i = 0; i < len; ++i) { if (a[i] == b) return TRUE; } return FALSE; } int gcd(int a, int b) { while (a != b) { if (a > b) a -= b; else b -= a; } return a; } bool areSame(int s[], int t[], size_t len) { int i; qsort(s, len, sizeof(int), compareInts); qsort(t, len, sizeof(int), compareInts); for (i = 0; i < len; ++i) { if (s[i] != t[i]) return FALSE; } return TRUE; } int main() { int s, n, i; int starts[5] = {2, 5, 7, 9, 10}; int ekg[5][LIMIT]; for (s = 0; s < 5; ++s) { ekg[s][0] = 1; ekg[s][1] = starts[s]; for (n = 2; n < LIMIT; ++n) { for (i = 2; ; ++i) { if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) { ekg[s][n] = i; break; } } } printf("EKG(%2d): [", starts[s]); for (i = 0; i < 30; ++i) printf("%d ", ekg[s][i]); printf("\b]\n"); } for (i = 2; i < LIMIT; ++i) { if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) { printf("\nEKG(5) and EKG(7) converge at term %d\n", i + 1); return 0; } } printf("\nEKG5(5) and EKG(7) do not converge within %d terms\n", LIMIT); return 0; }
package main import ( "fmt" "sort" ) func contains(a []int, b int) bool { for _, j := range a { if j == b { return true } } return false } func gcd(a, b int) int { for a != b { if a > b { a -= b } else { b -= a } } return a } func areSame(s, t []int) bool { le := len(s) if le != len(t) { return false } sort.Ints(s) sort.Ints(t) for i := 0; i < le; i++ { if s[i] != t[i] { return false } } return true } func main() { const limit = 100 starts := [5]int{2, 5, 7, 9, 10} var ekg [5][limit]int for s, start := range starts { ekg[s][0] = 1 ekg[s][1] = start for n := 2; n < limit; n++ { for i := 2; ; i++ { if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 { ekg[s][n] = i break } } } fmt.Printf("EKG(%2d): %v\n", start, ekg[s][:30]) } for i := 2; i < limit; i++ { if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) { fmt.Println("\nEKG(5) and EKG(7) converge at term", i+1) return } } fmt.Println("\nEKG5(5) and EKG(7) do not converge within", limit, "terms") }
Generate an equivalent Go version of this C code.
#include <stdio.h> #include <string.h> int repstr(char *str) { if (!str) return 0; size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; } return 0; } int main(void) { char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" }; size_t strslen = sizeof(strs) / sizeof(strs[0]); size_t i; for (i = 0; i < strslen; ++i) { int n = repstr(strs[i]); if (n) printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]); else printf("\"%s\" = not a rep-string\n", strs[i]); } return 0; }
package main import ( "fmt" "strings" ) func rep(s string) int { for x := len(s) / 2; x > 0; x-- { if strings.HasPrefix(s, s[x:]) { return x } } return 0 } const m = ` 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1` func main() { for _, s := range strings.Fields(m) { if n := rep(s); n > 0 { fmt.Printf("%q %d rep-string %q\n", s, n, s[:n]) } else { fmt.Printf("%q not a rep-string\n", s) } } }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> #include <unistd.h> int main() { int i; printf("\033[?1049h\033[H"); printf("Alternate screen buffer\n"); for (i = 5; i; i--) { printf("\rgoing back in %d...", i); fflush(stdout); sleep(1); } printf("\033[?1049l"); return 0; }
package main import ( "fmt" "time" ) func main() { fmt.Print("\033[?1049h\033[H") fmt.Println("Alternate screen buffer\n") s := "s" for i := 5; i > 0; i-- { if i == 1 { s = "" } fmt.Printf("\rgoing back in %d second%s...", i, s) time.Sleep(time.Second) } fmt.Print("\033[?1049l") }
Convert the following code from C to Go, ensuring the logic remains intact.
char ch = 'z';
ch := 'z' ch = 122 ch = '\x7a' ch = '\u007a' ch = '\U0000007a' ch = '\172'
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 32 typedef struct string_tag { size_t length; char str[MAX_WORD_SIZE]; } string_t; void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int hamming_distance(const string_t* str1, const string_t* str2) { size_t len1 = str1->length; size_t len2 = str2->length; if (len1 != len2) return 0; int count = 0; const char* s1 = str1->str; const char* s2 = str2->str; for (size_t i = 0; i < len1; ++i) { if (s1[i] != s2[i]) ++count; if (count == 2) break; } return count; } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; FILE* in = fopen(filename, "r"); if (!in) { perror(filename); return EXIT_FAILURE; } char line[MAX_WORD_SIZE]; size_t size = 0, capacity = 1024; string_t* dictionary = xmalloc(sizeof(string_t) * capacity); while (fgets(line, sizeof(line), in)) { if (size == capacity) { capacity *= 2; dictionary = xrealloc(dictionary, sizeof(string_t) * capacity); } size_t len = strlen(line) - 1; if (len > 11) { string_t* str = &dictionary[size]; str->length = len; memcpy(str->str, line, len); str->str[len] = '\0'; ++size; } } fclose(in); printf("Changeable words in %s:\n", filename); int n = 1; for (size_t i = 0; i < size; ++i) { const string_t* str1 = &dictionary[i]; for (size_t j = 0; j < size; ++j) { const string_t* str2 = &dictionary[j]; if (i != j && hamming_distance(str1, str2) == 1) printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str); } } free(dictionary); return EXIT_SUCCESS; }
package main import ( "bytes" "fmt" "io/ioutil" "log" "unicode/utf8" ) func hammingDist(s1, s2 string) int { r1 := []rune(s1) r2 := []rune(s2) if len(r1) != len(r2) { return 0 } count := 0 for i := 0; i < len(r1); i++ { if r1[i] != r2[i] { count++ if count == 2 { break } } } return count } func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) > 11 { words = append(words, s) } } count := 0 fmt.Println("Changeable words in", wordList, "\b:") for _, word1 := range words { for _, word2 := range words { if word1 != word2 && hammingDist(word1, word2) == 1 { count++ fmt.Printf("%2d: %-14s -> %s\n", count, word1, word2) } } } }
Translate the given C code snippet into Go without altering its behavior.
#include<windows.h> #include<unistd.h> #include<stdio.h> const char g_szClassName[] = "weirdWindow"; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd[3]; MSG Msg; int i,x=0,y=0; char str[3][100]; int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.", "If you can see two blank windows just behind this message box, you are in luck.", "Let's get started....", "Yes, you will be seeing a lot of me :)", "Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)", "Let's compare the windows for equality.", "Now let's hide Window 1.", "Now let's see Window 1 again.", "Let's close Window 2, bye, bye, Number 2 !", "Let's minimize Window 1.", "Now let's maximize Window 1.", "And finally we come to the fun part, watch Window 1 move !", "Let's double Window 1 in size for all the good work.", "That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"}; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } for(i=0;i<2;i++){ sprintf(str[i],"Window Number %d",i+1); hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL); if(hwnd[i] == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd[i], nCmdShow); UpdateWindow(hwnd[i]); } for(i=0;i<6;i++){ MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); } if(hwnd[0]==hwnd[1]) MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); else MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_HIDE); MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_SHOW); MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[1], SW_HIDE); MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MINIMIZE); MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MAXIMIZE); MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_RESTORE); while(x!=maxX/2||y!=maxY/2){ if(x<maxX/2) x++; if(y<maxY/2) y++; MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0); sleep(10); } MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MoveWindow(hwnd[0],0,0,maxX, maxY,0); MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
package main import ( "github.com/gotk3/gotk3/gtk" "log" "time" ) func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetResizable(true) window.SetTitle("Window management") window.SetBorderWidth(5) window.Connect("destroy", func() { gtk.MainQuit() }) stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10) check(err, "Unable to create stack box:") bmax, err := gtk.ButtonNewWithLabel("Maximize") check(err, "Unable to create maximize button:") bmax.Connect("clicked", func() { window.Maximize() }) bunmax, err := gtk.ButtonNewWithLabel("Unmaximize") check(err, "Unable to create unmaximize button:") bunmax.Connect("clicked", func() { window.Unmaximize() }) bicon, err := gtk.ButtonNewWithLabel("Iconize") check(err, "Unable to create iconize button:") bicon.Connect("clicked", func() { window.Iconify() }) bdeicon, err := gtk.ButtonNewWithLabel("Deiconize") check(err, "Unable to create deiconize button:") bdeicon.Connect("clicked", func() { window.Deiconify() }) bhide, err := gtk.ButtonNewWithLabel("Hide") check(err, "Unable to create hide button:") bhide.Connect("clicked", func() { window.Hide() time.Sleep(10 * time.Second) window.Show() }) bshow, err := gtk.ButtonNewWithLabel("Show") check(err, "Unable to create show button:") bshow.Connect("clicked", func() { window.Show() }) bmove, err := gtk.ButtonNewWithLabel("Move") check(err, "Unable to create move button:") isShifted := false bmove.Connect("clicked", func() { w, h := window.GetSize() if isShifted { window.Move(w-10, h-10) } else { window.Move(w+10, h+10) } isShifted = !isShifted }) bquit, err := gtk.ButtonNewWithLabel("Quit") check(err, "Unable to create quit button:") bquit.Connect("clicked", func() { window.Destroy() }) stackbox.PackStart(bmax, true, true, 0) stackbox.PackStart(bunmax, true, true, 0) stackbox.PackStart(bicon, true, true, 0) stackbox.PackStart(bdeicon, true, true, 0) stackbox.PackStart(bhide, true, true, 0) stackbox.PackStart(bshow, true, true, 0) stackbox.PackStart(bmove, true, true, 0) stackbox.PackStart(bquit, true, true, 0) window.Add(stackbox) window.ShowAll() gtk.Main() }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdlib.h> #define MONAD void* #define INTBIND(f, g, x) (f((int*)g(x))) #define RETURN(type,x) &((type)*)(x) MONAD boundInt(int *x) { return (MONAD)(x); } MONAD boundInt2str(int *x) { char buf[100]; char*str= malloc(1+sprintf(buf, "%d", *x)); sprintf(str, "%d", *x); return (MONAD)(str); } void task(int y) { char *z= INTBIND(boundInt2str, boundInt, &y); printf("%s\n", z); free(z); } int main() { task(13); }
package main import "fmt" type mlist struct{ value []int } func (m mlist) bind(f func(lst []int) mlist) mlist { return f(m.value) } func unit(lst []int) mlist { return mlist{lst} } func increment(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = v + 1 } return unit(lst2) } func double(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = 2 * v } return unit(lst2) } func main() { ml1 := unit([]int{3, 4, 5}) ml2 := ml1.bind(increment).bind(double) fmt.Printf("%v -> %v\n", ml1.value, ml2.value) }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <stdbool.h> #include <math.h> #define MAX 1000 void sieve(int n, bool *prime) { prime[0] = prime[1] = false; for (int i=2; i<=n; i++) prime[i] = true; for (int p=2; p*p<=n; p++) if (prime[p]) for (int c=p*p; c<=n; c+=p) prime[c] = false; } bool square(int n) { int sq = sqrt(n); return (sq * sq == n); } int main() { bool prime[MAX + 1]; sieve(MAX, prime); for (int i=2; i<=MAX; i++) if (prime[i]) { int sq = i-1; if (square(sq)) printf("%d ", sq); } printf("\n"); return 0; }
package main import ( "fmt" "math" "rcu" ) func main() { var squares []int limit := int(math.Sqrt(1000)) i := 1 for i <= limit { n := i * i if rcu.IsPrime(n + 1) { squares = append(squares, n) } if i == 1 { i = 2 } else { i += 2 } } fmt.Println("There are", len(squares), "square numbers 'n' where 'n+1' is prime, viz:") fmt.Println(squares) }
Convert the following code from C to Go, ensuring the logic remains intact.
#include <stdio.h> #include <stdbool.h> #include <math.h> #define MAX 1000 void sieve(int n, bool *prime) { prime[0] = prime[1] = false; for (int i=2; i<=n; i++) prime[i] = true; for (int p=2; p*p<=n; p++) if (prime[p]) for (int c=p*p; c<=n; c+=p) prime[c] = false; } bool square(int n) { int sq = sqrt(n); return (sq * sq == n); } int main() { bool prime[MAX + 1]; sieve(MAX, prime); for (int i=2; i<=MAX; i++) if (prime[i]) { int sq = i-1; if (square(sq)) printf("%d ", sq); } printf("\n"); return 0; }
package main import ( "fmt" "math" "rcu" ) func main() { var squares []int limit := int(math.Sqrt(1000)) i := 1 for i <= limit { n := i * i if rcu.IsPrime(n + 1) { squares = append(squares, n) } if i == 1 { i = 2 } else { i += 2 } } fmt.Println("There are", len(squares), "square numbers 'n' where 'n+1' is prime, viz:") fmt.Println(squares) }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #include <stdbool.h> bool isPrime(int n) { int d; if (n < 2) return false; if (!(n%2)) return n == 2; if (!(n%3)) return n == 3; d = 5; while (d*d <= n) { if (!(n%d)) return false; d += 2; if (!(n%d)) return false; d += 4; } return true; } int main() { int i, lastSpecial = 3, lastGap = 1; printf("Special primes under 1,050:\n"); printf("Prime1 Prime2 Gap\n"); printf("%6d %6d %3d\n", 2, 3, lastGap); for (i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func main() { c := sieve(1049) fmt.Println("Special primes under 1,050:") fmt.Println("Prime1 Prime2 Gap") lastSpecial := 3 lastGap := 1 fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap) for i := 5; i < 1050; i += 2 { if !c[i] && (i-lastSpecial) > lastGap { lastGap = i - lastSpecial fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap) lastSpecial = i } } }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> #include <stdbool.h> bool isPrime(int n) { int d; if (n < 2) return false; if (!(n%2)) return n == 2; if (!(n%3)) return n == 3; d = 5; while (d*d <= n) { if (!(n%d)) return false; d += 2; if (!(n%d)) return false; d += 4; } return true; } int main() { int i, lastSpecial = 3, lastGap = 1; printf("Special primes under 1,050:\n"); printf("Prime1 Prime2 Gap\n"); printf("%6d %6d %3d\n", 2, 3, lastGap); for (i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func main() { c := sieve(1049) fmt.Println("Special primes under 1,050:") fmt.Println("Prime1 Prime2 Gap") lastSpecial := 3 lastGap := 1 fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap) for i := 5; i < 1050; i += 2 { if !c[i] && (i-lastSpecial) > lastGap { lastGap = i - lastSpecial fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap) lastSpecial = i } } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #define MAX(x,y) ((x) > (y) ? (x) : (y)) #define MIN(x,y) ((x) < (y) ? (x) : (y)) size_t base20(unsigned int n, uint8_t *out) { uint8_t *start = out; do {*out++ = n % 20;} while (n /= 20); size_t length = out - start; while (out > start) { uint8_t x = *--out; *out = *start; *start++ = x; } return length; } void make_digit(int n, char *place, size_t line_length) { static const char *parts[] = {" "," . "," .. ","... ","....","----"}; int i; for (i=4; i>0; i--, n -= 5) memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4); if (n == -20) place[4 * line_length + 1] = '@'; } char *mayan(unsigned int n) { if (n == 0) return NULL; uint8_t digits[15]; size_t n_digits = base20(n, digits); size_t line_length = n_digits*5 + 2; char *str = malloc(line_length * 6 + 1); if (str == NULL) return NULL; str[line_length * 6] = 0; char *ptr; unsigned int i; for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "+----", 5); memcpy(ptr-5, "+\n", 2); memcpy(str+5*line_length, str, line_length); for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "| ", 5); memcpy(ptr-5, "|\n", 2); memcpy(str+2*line_length, str+line_length, line_length); memcpy(str+3*line_length, str+line_length, 2*line_length); for (i=0; i<n_digits; i++) make_digit(digits[i], str+1+5*i, line_length); return str; } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: mayan <number>\n"); return 1; } int i = atoi(argv[1]); if (i <= 0) { fprintf(stderr, "number must be positive\n"); return 1; } char *m = mayan(i); printf("%s",m); free(m); return 0; }
package main import ( "fmt" "strconv" ) const ( ul = "╔" uc = "╦" ur = "╗" ll = "╚" lc = "╩" lr = "╝" hb = "═" vb = "║" ) var mayan = [5]string{ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", } const ( m0 = " Θ " m5 = "────" ) func dec2vig(n uint64) []uint64 { vig := strconv.FormatUint(n, 20) res := make([]uint64, len(vig)) for i, d := range vig { res[i], _ = strconv.ParseUint(string(d), 20, 64) } return res } func vig2quin(n uint64) [4]string { if n >= 20 { panic("Cant't convert a number >= 20") } res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]} if n == 0 { res[3] = m0 return res } fives := n / 5 rem := n % 5 res[3-fives] = mayan[rem] for i := 3; i > 3-int(fives); i-- { res[i] = m5 } return res } func draw(mayans [][4]string) { lm := len(mayans) fmt.Print(ul) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(uc) } else { fmt.Println(ur) } } for i := 1; i < 5; i++ { fmt.Print(vb) for j := 0; j < lm; j++ { fmt.Print(mayans[j][i-1]) fmt.Print(vb) } fmt.Println() } fmt.Print(ll) for i := 0; i < lm; i++ { for j := 0; j < 4; j++ { fmt.Print(hb) } if i < lm-1 { fmt.Print(lc) } else { fmt.Println(lr) } } } func main() { numbers := []uint64{4005, 8017, 326205, 886205, 1081439556} for _, n := range numbers { fmt.Printf("Converting %d to Mayan:\n", n) vigs := dec2vig(n) lv := len(vigs) mayans := make([][4]string, lv) for i, vig := range vigs { mayans[i] = vig2quin(vig) } draw(mayans) fmt.Println() } }
Write a version of this C function in Go with identical behavior.
#include <math.h> #include <stdint.h> #include <stdio.h> uint64_t factorial(int n) { uint64_t result = 1; int i; for (i = 1; i <= n; i++) { result *= i; } return result; } int inverse_factorial(uint64_t f) { int p = 1; int i = 1; if (f == 1) { return 0; } while (p < f) { p *= i; i++; } if (p == f) { return i - 1; } return -1; } uint64_t super_factorial(int n) { uint64_t result = 1; int i; for (i = 1; i <= n; i++) { result *= factorial(i); } return result; } uint64_t hyper_factorial(int n) { uint64_t result = 1; int i; for (i = 1; i <= n; i++) { result *= (uint64_t)powl(i, i); } return result; } uint64_t alternating_factorial(int n) { uint64_t result = 0; int i; for (i = 1; i <= n; i++) { if ((n - i) % 2 == 0) { result += factorial(i); } else { result -= factorial(i); } } return result; } uint64_t exponential_factorial(int n) { uint64_t result = 0; int i; for (i = 1; i <= n; i++) { result = (uint64_t)powl(i, (long double)result); } return result; } void test_factorial(int count, uint64_t(*func)(int), char *name) { int i; printf("First %d %s:\n", count, name); for (i = 0; i < count ; i++) { printf("%llu ", func(i)); } printf("\n"); } void test_inverse(uint64_t f) { int n = inverse_factorial(f); if (n < 0) { printf("rf(%llu) = No Solution\n", f); } else { printf("rf(%llu) = %d\n", f, n); } } int main() { int i; test_factorial(9, super_factorial, "super factorials"); printf("\n"); test_factorial(8, super_factorial, "hyper factorials"); printf("\n"); test_factorial(10, alternating_factorial, "alternating factorials"); printf("\n"); test_factorial(5, exponential_factorial, "exponential factorials"); printf("\n"); test_inverse(1); test_inverse(2); test_inverse(6); test_inverse(24); test_inverse(120); test_inverse(720); test_inverse(5040); test_inverse(40320); test_inverse(362880); test_inverse(3628800); test_inverse(119); return 0; }
package main import ( "fmt" "math/big" ) func sf(n int) *big.Int { if n < 2 { return big.NewInt(1) } sfact := big.NewInt(1) fact := big.NewInt(1) for i := 2; i <= n; i++ { fact.Mul(fact, big.NewInt(int64(i))) sfact.Mul(sfact, fact) } return sfact } func H(n int) *big.Int { if n < 2 { return big.NewInt(1) } hfact := big.NewInt(1) for i := 2; i <= n; i++ { bi := big.NewInt(int64(i)) hfact.Mul(hfact, bi.Exp(bi, bi, nil)) } return hfact } func af(n int) *big.Int { if n < 1 { return new(big.Int) } afact := new(big.Int) fact := big.NewInt(1) sign := new(big.Int) if n%2 == 0 { sign.SetInt64(-1) } else { sign.SetInt64(1) } t := new(big.Int) for i := 1; i <= n; i++ { fact.Mul(fact, big.NewInt(int64(i))) afact.Add(afact, t.Mul(fact, sign)) sign.Neg(sign) } return afact } func ef(n int) *big.Int { if n < 1 { return big.NewInt(1) } t := big.NewInt(int64(n)) return t.Exp(t, ef(n-1), nil) } func rf(n *big.Int) int { i := 0 fact := big.NewInt(1) for { if fact.Cmp(n) == 0 { return i } if fact.Cmp(n) > 0 { return -1 } i++ fact.Mul(fact, big.NewInt(int64(i))) } } func main() { fmt.Println("First 10 superfactorials:") for i := 0; i < 10; i++ { fmt.Println(sf(i)) } fmt.Println("\nFirst 10 hyperfactorials:") for i := 0; i < 10; i++ { fmt.Println(H(i)) } fmt.Println("\nFirst 10 alternating factorials:") for i := 0; i < 10; i++ { fmt.Print(af(i), " ") } fmt.Println("\n\nFirst 5 exponential factorials:") for i := 0; i <= 4; i++ { fmt.Print(ef(i), " ") } fmt.Println("\n\nThe number of digits in 5$ is", len(ef(5).String())) fmt.Println("\nReverse factorials:") facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119} for _, fact := range facts { bfact := big.NewInt(fact) rfact := rf(bfact) srfact := fmt.Sprintf("%d", rfact) if rfact == -1 { srfact = "none" } fmt.Printf("%4s <- rf(%d)\n", srfact, fact) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include<stdio.h> #include<stdlib.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int nextprime( int p ) { int i=0; if(p==0) return 2; if(p<3) return p+1; while(!isprime(++i + p)); return i+p; } int main(void) { int p1, p2; for(p1=3;p1<=99;p1+=2) { p2=nextprime(p1); if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) { printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 ); } } return 0; }
package main import ( "fmt" "rcu" ) const MAX = 1e7 - 1 var primes = rcu.Primes(MAX) func specialNP(limit int, showAll bool) { if showAll { fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:") } count := 0 for i := 1; i < len(primes); i++ { p2 := primes[i] if p2 >= limit { break } p1 := primes[i-1] p3 := p1 + p2 - 1 if rcu.IsPrime(p3) { if showAll { fmt.Printf("(%2d, %2d) => %3d\n", p1, p2, p3) } count++ } } ccount := rcu.Commatize(count) climit := rcu.Commatize(limit) fmt.Printf("\nFound %s special neighbor primes under %s.\n", ccount, climit) } func main() { specialNP(100, true) var pow = 1000 for i := 3; i < 8; i++ { specialNP(pow, false) pow *= 10 } }
Convert this C block to Go, preserving its control flow and logic.
#include<stdio.h> #include<stdlib.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int nextprime( int p ) { int i=0; if(p==0) return 2; if(p<3) return p+1; while(!isprime(++i + p)); return i+p; } int main(void) { int p1, p2; for(p1=3;p1<=99;p1+=2) { p2=nextprime(p1); if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) { printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 ); } } return 0; }
package main import ( "fmt" "rcu" ) const MAX = 1e7 - 1 var primes = rcu.Primes(MAX) func specialNP(limit int, showAll bool) { if showAll { fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:") } count := 0 for i := 1; i < len(primes); i++ { p2 := primes[i] if p2 >= limit { break } p1 := primes[i-1] p3 := p1 + p2 - 1 if rcu.IsPrime(p3) { if showAll { fmt.Printf("(%2d, %2d) => %3d\n", p1, p2, p3) } count++ } } ccount := rcu.Commatize(count) climit := rcu.Commatize(limit) fmt.Printf("\nFound %s special neighbor primes under %s.\n", ccount, climit) } func main() { specialNP(100, true) var pow = 1000 for i := 3; i < 8; i++ { specialNP(pow, false) pow *= 10 } }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> int a[17][17], idx[4]; int find_group(int type, int min_n, int max_n, int depth) { int i, n; if (depth == 4) { printf("totally %sconnected group:", type ? "" : "un"); for (i = 0; i < 4; i++) printf(" %d", idx[i]); putchar('\n'); return 1; } for (i = min_n; i < max_n; i++) { for (n = 0; n < depth; n++) if (a[idx[n]][i] != type) break; if (n == depth) { idx[n] = i; if (find_group(type, 1, max_n, depth + 1)) return 1; } } return 0; } int main() { int i, j, k; const char *mark = "01-"; for (i = 0; i < 17; i++) a[i][i] = 2; for (k = 1; k <= 8; k <<= 1) { for (i = 0; i < 17; i++) { j = (i + k) % 17; a[i][j] = a[j][i] = 1; } } for (i = 0; i < 17; i++) { for (j = 0; j < 17; j++) printf("%c ", mark[a[i][j]]); putchar('\n'); } for (i = 0; i < 17; i++) { idx[0] = i; if (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) { puts("no good"); return 0; } } puts("all good"); return 0; }
package main import "fmt" var ( a [17][17]int idx [4]int ) func findGroup(ctype, min, max, depth int) bool { if depth == 4 { cs := "" if ctype == 0 { cs = "un" } fmt.Printf("Totally %sconnected group:", cs) for i := 0; i < 4; i++ { fmt.Printf(" %d", idx[i]) } fmt.Println() return true } for i := min; i < max; i++ { n := 0 for ; n < depth; n++ { if a[idx[n]][i] != ctype { break } } if n == depth { idx[n] = i if findGroup(ctype, 1, max, depth+1) { return true } } } return false } func main() { const mark = "01-" for i := 0; i < 17; i++ { a[i][i] = 2 } for k := 1; k <= 8; k <<= 1 { for i := 0; i < 17; i++ { j := (i + k) % 17 a[i][j], a[j][i] = 1, 1 } } for i := 0; i < 17; i++ { for j := 0; j < 17; j++ { fmt.Printf("%c ", mark[a[i][j]]) } fmt.Println() } for i := 0; i < 17; i++ { idx[0] = i if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) { fmt.Println("No good.") return } } fmt.Println("All good.") }
Produce a language-to-language conversion: from C to Go, same semantics.
#include<windows.h> #include<stdio.h> int main() { printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN)); return 0; }
package main import ( "fmt" "github.com/go-vgo/robotgo" ) func main() { w, h := robotgo.GetScreenSize() fmt.Printf("Screen size: %d x %d\n", w, h) fpid, err := robotgo.FindIds("firefox") if err == nil && len(fpid) > 0 { pid := fpid[0] robotgo.ActivePID(pid) robotgo.MaxWindow(pid) _, _, w, h = robotgo.GetBounds(pid) fmt.Printf("Max usable : %d x %d\n", w, h) } }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> int main() { printf("\033[7mReversed\033[m Normal\n"); return 0; }
package main import ( "fmt" "os" "os/exec" ) func main() { tput("rev") fmt.Print("Rosetta") tput("sgr0") fmt.Println(" Code") } func tput(arg string) error { cmd := exec.Command("tput", arg) cmd.Stdout = os.Stdout return cmd.Run() }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdint.h> #include <stdio.h> #include <glib.h> typedef struct named_number_tag { const char* name; uint64_t number; } named_number; const named_number named_numbers[] = { { "hundred", 100 }, { "thousand", 1000 }, { "million", 1000000 }, { "billion", 1000000000 }, { "trillion", 1000000000000 }, { "quadrillion", 1000000000000000ULL }, { "quintillion", 1000000000000000000ULL } }; const named_number* get_named_number(uint64_t n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_number); 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]; } size_t append_number_name(GString* str, uint64_t n) { static const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; static const char* tens[] = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; size_t len = str->len; if (n < 20) { g_string_append(str, small[n]); } else if (n < 100) { g_string_append(str, tens[n/10 - 2]); if (n % 10 != 0) { g_string_append_c(str, '-'); g_string_append(str, small[n % 10]); } } else { const named_number* num = get_named_number(n); uint64_t p = num->number; append_number_name(str, n/p); g_string_append_c(str, ' '); g_string_append(str, num->name); if (n % p != 0) { g_string_append_c(str, ' '); append_number_name(str, n % p); } } return str->len - len; } GString* magic(uint64_t n) { GString* str = g_string_new(NULL); for (unsigned int i = 0; ; ++i) { size_t count = append_number_name(str, n); if (i == 0) str->str[0] = g_ascii_toupper(str->str[0]); if (n == 4) { g_string_append(str, " is magic."); break; } g_string_append(str, " is "); append_number_name(str, count); g_string_append(str, ", "); n = count; } return str; } void test_magic(uint64_t n) { GString* str = magic(n); printf("%s\n", str->str); g_string_free(str, TRUE); } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
package main import ( "fmt" "math" "strings" ) func main() { for _, n := range [...]int64{ 0, 4, 6, 11, 13, 75, 100, 337, -164, math.MaxInt64, } { fmt.Println(fourIsMagic(n)) } } func fourIsMagic(n int64) string { s := say(n) s = strings.ToUpper(s[:1]) + s[1:] t := s for n != 4 { n = int64(len(s)) s = say(n) t += " is " + s + ", " + s } t += " is magic." return t } 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 }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "wren.h" void C_usleep(WrenVM* vm) { useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1); usleep(usec); } void C_espeak(WrenVM* vm) { const char *arg = wrenGetSlotString(vm, 1); char command[strlen(arg) + 10]; strcpy(command, "espeak \""); strcat(command, arg); strcat(command, "\""); system(command); } void C_flushStdout(WrenVM* vm) { fflush(stdout); } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "C") == 0) { if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep; if (isStatic && strcmp(signature, "espeak(_)") == 0) return C_espeak; if (isStatic && strcmp(signature, "flushStdout()") == 0) return C_flushStdout; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { if( result.source) free((void*)result.source); } WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { WrenLoadModuleResult result = {0}; if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { result.onComplete = loadModuleComplete; char fullName[strlen(name) + 6]; strcpy(fullName, name); strcat(fullName, ".wren"); result.source = readFile(fullName); } return result; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "speech_engine_highlight_words.wren"; char *script = readFile(fileName); wrenInterpret(vm, module, script); wrenFreeVM(vm); free(script); return 0; }
package main import ( "fmt" "log" "os/exec" "strings" "time" ) func main() { s := "Actions speak louder than words." prev := "" prevLen := 0 bs := "" for _, word := range strings.Fields(s) { cmd := exec.Command("espeak", word) if err := cmd.Run(); err != nil { log.Fatal(err) } if prevLen > 0 { bs = strings.Repeat("\b", prevLen) } fmt.Printf("%s%s%s ", bs, prev, strings.ToUpper(word)) prev = word + " " prevLen = len(word) + 1 } bs = strings.Repeat("\b", prevLen) time.Sleep(time.Second) fmt.Printf("%s%s\n", bs, prev) }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "wren.h" void C_usleep(WrenVM* vm) { useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1); usleep(usec); } void C_espeak(WrenVM* vm) { const char *arg = wrenGetSlotString(vm, 1); char command[strlen(arg) + 10]; strcpy(command, "espeak \""); strcat(command, arg); strcat(command, "\""); system(command); } void C_flushStdout(WrenVM* vm) { fflush(stdout); } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "C") == 0) { if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep; if (isStatic && strcmp(signature, "espeak(_)") == 0) return C_espeak; if (isStatic && strcmp(signature, "flushStdout()") == 0) return C_flushStdout; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { if( result.source) free((void*)result.source); } WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { WrenLoadModuleResult result = {0}; if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { result.onComplete = loadModuleComplete; char fullName[strlen(name) + 6]; strcpy(fullName, name); strcat(fullName, ".wren"); result.source = readFile(fullName); } return result; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "speech_engine_highlight_words.wren"; char *script = readFile(fileName); wrenInterpret(vm, module, script); wrenFreeVM(vm); free(script); return 0; }
package main import ( "fmt" "log" "os/exec" "strings" "time" ) func main() { s := "Actions speak louder than words." prev := "" prevLen := 0 bs := "" for _, word := range strings.Fields(s) { cmd := exec.Command("espeak", word) if err := cmd.Run(); err != nil { log.Fatal(err) } if prevLen > 0 { bs = strings.Repeat("\b", prevLen) } fmt.Printf("%s%s%s ", bs, prev, strings.ToUpper(word)) prev = word + " " prevLen = len(word) + 1 } bs = strings.Repeat("\b", prevLen) time.Sleep(time.Second) fmt.Printf("%s%s\n", bs, prev) }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> int findNumOfDec(double x) { char buffer[128]; int pos, num; sprintf(buffer, "%.14f", x); pos = 0; num = 0; while (buffer[pos] != 0 && buffer[pos] != '.') { pos++; } if (buffer[pos] != 0) { pos++; while (buffer[pos] != 0) { pos++; } pos--; while (buffer[pos] == '0') { pos--; } while (buffer[pos] != '.') { num++; pos--; } } return num; } void test(double x) { int num = findNumOfDec(x); printf("%f has %d decimals\n", x, num); } int main() { test(12.0); test(12.345); test(12.345555555555); test(12.3450); test(12.34555555555555555555); test(1.2345e+54); return 0; }
package main import ( "fmt" "log" "math" "strings" ) var error = "Argument must be a numeric literal or a decimal numeric string." func getNumDecimals(n interface{}) int { switch v := n.(type) { case int: return 0 case float64: if v == math.Trunc(v) { return 0 } s := fmt.Sprintf("%g", v) return len(strings.Split(s, ".")[1]) case string: if v == "" { log.Fatal(error) } if v[0] == '+' || v[0] == '-' { v = v[1:] } for _, c := range v { if strings.IndexRune("0123456789.", c) == -1 { log.Fatal(error) } } s := strings.Split(v, ".") ls := len(s) if ls == 1 { return 0 } else if ls == 2 { return len(s[1]) } else { log.Fatal("Too many decimal points") } default: log.Fatal(error) } return 0 } func main() { var a = []interface{}{12, 12.345, 12.345555555555, "12.3450", "12.34555555555555555555", 12.345e53} for _, n := range a { d := getNumDecimals(n) switch v := n.(type) { case string: fmt.Printf("%q has %d decimals\n", v, d) case float32, float64: fmt.Printf("%g has %d decimals\n", v, d) default: fmt.Printf("%d has %d decimals\n", v, d) } } }
Convert this C snippet to Go and keep its semantics consistent.
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
const ( apple = iota banana cherry )
Please provide an equivalent version of this C code in Go.
#include <stdio.h> #define MAX_N 33 #define BRANCH 4 typedef unsigned long long xint; #define FMT "llu" xint rooted[MAX_N] = {1, 1, 0}; xint unrooted[MAX_N] = {1, 1, 0}; xint choose(xint m, xint k) { xint i, r; if (k == 1) return m; for (r = m, i = 1; i < k; i++) r = r * (m + i) / (i + 1); return r; } void tree(xint br, xint n, xint cnt, xint sum, xint l) { xint b, c, m, s; for (b = br + 1; b <= BRANCH; b++) { s = sum + (b - br) * n; if (s >= MAX_N) return; c = choose(rooted[n], b - br) * cnt; if (l * 2 < s) unrooted[s] += c; if (b == BRANCH) return; rooted[s] += c; for (m = n; --m; ) tree(b, m, c, s, l); } } void bicenter(int s) { if (s & 1) return; unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; } int main() { xint n; for (n = 1; n < MAX_N; n++) { tree(0, n, 1, 1, n); bicenter(n); printf("%"FMT": %"FMT"\n", n, unrooted[n]); } return 0; }
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } } func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } } func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d: %d\n", n, &unrooted[n]) } }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #define MAX_N 33 #define BRANCH 4 typedef unsigned long long xint; #define FMT "llu" xint rooted[MAX_N] = {1, 1, 0}; xint unrooted[MAX_N] = {1, 1, 0}; xint choose(xint m, xint k) { xint i, r; if (k == 1) return m; for (r = m, i = 1; i < k; i++) r = r * (m + i) / (i + 1); return r; } void tree(xint br, xint n, xint cnt, xint sum, xint l) { xint b, c, m, s; for (b = br + 1; b <= BRANCH; b++) { s = sum + (b - br) * n; if (s >= MAX_N) return; c = choose(rooted[n], b - br) * cnt; if (l * 2 < s) unrooted[s] += c; if (b == BRANCH) return; rooted[s] += c; for (m = n; --m; ) tree(b, m, c, s, l); } } void bicenter(int s) { if (s & 1) return; unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; } int main() { xint n; for (n = 1; n < MAX_N; n++) { tree(0, n, 1, 1, n); bicenter(n); printf("%"FMT": %"FMT"\n", n, unrooted[n]); } return 0; }
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } } func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } } func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d: %d\n", n, &unrooted[n]) } }
Write a version of this C function in Go with identical behavior.
#include<stdio.h> #include<stdlib.h> #define min(a, b) (a<=b?a:b) void minab( unsigned int n ) { int i, j; for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf( "%2d ", min( min(i, n-1-i), min(j, n-1-j) )); } printf( "\n" ); } return; } int main(void) { minab(10); return 0; }
package main import "fmt" func printMinCells(n int) { fmt.Printf("Minimum number of cells after, before, above and below %d x %d square:\n", n, n) p := 1 if n > 20 { p = 2 } for r := 0; r < n; r++ { cells := make([]int, n) for c := 0; c < n; c++ { nums := []int{n - r - 1, r, c, n - c - 1} min := n for _, num := range nums { if num < min { min = num } } cells[c] = min } fmt.Printf("%*d \n", p, cells) } } func main() { for _, n := range []int{23, 10, 9, 2, 1} { printMinCells(n) fmt.Println() } }
Translate this program into Go but keep the logic exactly as in C.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
package main import ( "github.com/fogleman/gg" "math" ) func Pentagram(x, y, r float64) []gg.Point { points := make([]gg.Point, 5) for i := 0; i < 5; i++ { fi := float64(i) angle := 2*math.Pi*fi/5 - math.Pi/2 points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)} } return points } func main() { points := Pentagram(320, 320, 250) dc := gg.NewContext(640, 640) dc.SetRGB(1, 1, 1) dc.Clear() for i := 0; i <= 5; i++ { index := (i * 2) % 5 p := points[index] dc.LineTo(p.X, p.Y) } dc.SetHexColor("#6495ED") dc.SetFillRule(gg.FillRuleWinding) dc.FillPreserve() dc.SetRGB(0, 0, 0) dc.SetLineWidth(5) dc.Stroke() dc.SavePNG("pentagram.png") }
Produce a language-to-language conversion: from C to Go, same semantics.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
package main import ( "github.com/fogleman/gg" "math" ) func Pentagram(x, y, r float64) []gg.Point { points := make([]gg.Point, 5) for i := 0; i < 5; i++ { fi := float64(i) angle := 2*math.Pi*fi/5 - math.Pi/2 points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)} } return points } func main() { points := Pentagram(320, 320, 250) dc := gg.NewContext(640, 640) dc.SetRGB(1, 1, 1) dc.Clear() for i := 0; i <= 5; i++ { index := (i * 2) % 5 p := points[index] dc.LineTo(p.X, p.Y) } dc.SetHexColor("#6495ED") dc.SetFillRule(gg.FillRuleWinding) dc.FillPreserve() dc.SetRGB(0, 0, 0) dc.SetLineWidth(5) dc.Stroke() dc.SavePNG("pentagram.png") }
Please provide an equivalent version of this C code in Go.
#include <string.h> #include <memory.h> static unsigned int _parseDecimal ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' ) { nVal *= 10; nVal += chNow - '0'; ++*pchCursor; } return nVal; } static unsigned int _parseHex ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor & 0x5f, (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || (chNow >= 'A' && chNow <= 'F') ) { unsigned char nybbleValue; chNow -= 0x10; nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow ); nVal <<= 4; nVal += nybbleValue; ++*pchCursor; } return nVal; } int ParseIPv4OrIPv6 ( const char** ppszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { unsigned char* abyAddrLocal; unsigned char abyDummyAddr[16]; const char* pchColon = strchr ( *ppszText, ':' ); const char* pchDot = strchr ( *ppszText, '.' ); const char* pchOpenBracket = strchr ( *ppszText, '[' ); const char* pchCloseBracket = NULL; int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot || ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) ); if ( bIsIPv6local ) { pchCloseBracket = strchr ( *ppszText, ']' ); if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket || pchCloseBracket < pchOpenBracket ) ) return 0; } else { if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) ) return 0; } if ( NULL != pbIsIPv6 ) *pbIsIPv6 = bIsIPv6local; abyAddrLocal = abyAddr; if ( NULL == abyAddrLocal ) abyAddrLocal = abyDummyAddr; if ( ! bIsIPv6local ) { unsigned char* pbyAddrCursor = abyAddrLocal; unsigned int nVal; const char* pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; if ( ':' == **ppszText && NULL != pnPort ) { unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } else { unsigned char* pbyAddrCursor; unsigned char* pbyZerosLoc; int bIPv4Detected; int nIdx; if ( NULL != pchOpenBracket ) *ppszText = pchOpenBracket + 1; pbyAddrCursor = abyAddrLocal; pbyZerosLoc = NULL; bIPv4Detected = 0; for ( nIdx = 0; nIdx < 8; ++nIdx ) { const char* pszTextBefore = *ppszText; unsigned nVal =_parseHex ( ppszText ); if ( pszTextBefore == *ppszText ) { if ( NULL != pbyZerosLoc ) { if ( pbyZerosLoc == pbyAddrCursor ) { --nIdx; break; } return 0; } if ( ':' != **ppszText ) return 0; if ( 0 == nIdx ) { ++(*ppszText); if ( ':' != **ppszText ) return 0; } pbyZerosLoc = pbyAddrCursor; ++(*ppszText); } else { if ( '.' == **ppszText ) { const char* pszTextlocal = pszTextBefore; unsigned char abyAddrlocal[16]; int bIsIPv6local; int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local ); *ppszText = pszTextlocal; if ( ! bParseResultlocal || bIsIPv6local ) return 0; *(pbyAddrCursor++) = abyAddrlocal[0]; *(pbyAddrCursor++) = abyAddrlocal[1]; *(pbyAddrCursor++) = abyAddrlocal[2]; *(pbyAddrCursor++) = abyAddrlocal[3]; ++nIdx; bIPv4Detected = 1; break; } if ( nVal > 65535 ) return 0; *(pbyAddrCursor++) = nVal >> 8; *(pbyAddrCursor++) = nVal & 0xff; if ( ':' == **ppszText ) { ++(*ppszText); } else { break; } } } if ( NULL != pbyZerosLoc ) { int nHead = (int)( pbyZerosLoc - abyAddrLocal ); int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); int nZeros = 16 - nTail - nHead; memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); memset ( pbyZerosLoc, 0, nZeros ); } if ( bIPv4Detected ) { static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff }; if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) ) return 0; } if ( NULL != pchOpenBracket ) { if ( ']' != **ppszText ) return 0; ++(*ppszText); } if ( ':' == **ppszText && NULL != pnPort ) { const char* pszTextBefore; unsigned int nVal; unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } } int ParseIPv4OrIPv6_2 ( const char* pszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { const char* pszTextLocal = pszText; return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6); }
package main import ( "encoding/hex" "fmt" "io" "net" "os" "strconv" "strings" "text/tabwriter" ) func parseIPPort(address string) (net.IP, *uint64, error) { ip := net.ParseIP(address) if ip != nil { return ip, nil, nil } host, portStr, err := net.SplitHostPort(address) if err != nil { return nil, nil, fmt.Errorf("splithostport failed: %w", err) } port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, nil, fmt.Errorf("failed to parse port: %w", err) } ip = net.ParseIP(host) if ip == nil { return nil, nil, fmt.Errorf("failed to parse ip address") } return ip, &port, nil } func ipVersion(ip net.IP) int { if ip.To4() == nil { return 6 } return 4 } func main() { testCases := []string{ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:443", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) writeTSV := func(w io.Writer, args ...interface{}) { fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...) fmt.Fprintf(w, "\n") } writeTSV(w, "Input", "Address", "Space", "Port") for _, addr := range testCases { ip, port, err := parseIPPort(addr) if err != nil { panic(err) } portStr := "n/a" if port != nil { portStr = fmt.Sprint(*port) } ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip)) writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr) } w.Flush() }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> #include <stdlib.h> #include <GL/glew.h> #include <GL/glut.h> GLuint ps, vs, prog, r_mod; float angle = 0; void render(void) { glClear(GL_COLOR_BUFFER_BIT); glUniform1f(r_mod, rand() / (float)RAND_MAX); glLoadIdentity(); glRotatef(angle, angle * .1, 1, 0); glBegin(GL_TRIANGLES); glVertex3f(-1, -.5, 0); glVertex3f(0, 1, 0); glVertex3f(1, 0, 0); glEnd(); angle += .02; glutSwapBuffers(); } void set_shader() { const char *f = "varying float x, y, z;" "uniform float r_mod;" "float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }" "void main() {" " gl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);" "}"; const char *v = "varying float x, y, z;" "void main() {" " gl_Position = ftransform();" " x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;" " x += y; y -= x; z += x - y;" "}"; vs = glCreateShader(GL_VERTEX_SHADER); ps = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(ps, 1, &f, 0); glShaderSource(vs, 1, &v, 0); glCompileShader(vs); glCompileShader(ps); prog = glCreateProgram(); glAttachShader(prog, ps); glAttachShader(prog, vs); glLinkProgram(prog); glUseProgram(prog); r_mod = glGetUniformLocation(prog, "r_mod"); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(200, 200); glutCreateWindow("Stuff"); glutIdleFunc(render); glewInit(); if (!glewIsSupported("GL_VERSION_2_0")) { fprintf(stderr, "GL 2.0 unsupported\n"); return 1; } set_shader(); glutMainLoop(); return 0; }
package main import "C" import "log" import "unsafe" var ps, vs, prog, r_mod C.GLuint var angle = float32(0) func render() { C.glClear(C.GL_COLOR_BUFFER_BIT) C.glUniform1f_macro(C.GLint(r_mod), C.GLfloat(C.rand())/C.GLfloat(C.RAND_MAX)) C.glLoadIdentity() C.glRotatef(C.float(angle), C.float(angle*0.1), 1, 0) C.glBegin(C.GL_TRIANGLES) C.glVertex3f(-1, -0.5, 0) C.glVertex3f(0, 1, 0) C.glVertex3f(1, 0, 0) C.glEnd() angle += 0.02 C.glutSwapBuffers() } func setShader() { f := "varying float x, y, z;" + "uniform float r_mod;" + "float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }" + "void main() {" + " gl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);" + "}" v := "varying float x, y, z;" + "void main() {" + " gl_Position = ftransform();" + " x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;" + " x += y; y -= x; z += x - y;" + "}" fc, vc := C.CString(f), C.CString(v) defer C.free(unsafe.Pointer(fc)) defer C.free(unsafe.Pointer(vc)) vs = C.glCreateShader_macro(C.GL_VERTEX_SHADER) ps = C.glCreateShader_macro(C.GL_FRAGMENT_SHADER) C.glShaderSource_macro(ps, 1, &fc, nil) C.glShaderSource_macro(vs, 1, &vc, nil) C.glCompileShader_macro(vs) C.glCompileShader_macro(ps) prog = C.glCreateProgram_macro() C.glAttachShader_macro(prog, ps) C.glAttachShader_macro(prog, vs) C.glLinkProgram_macro(prog) C.glUseProgram_macro(prog) rms := C.CString("r_mod") r_mod = C.GLuint(C.glGetUniformLocation_macro(prog, rms)) C.free(unsafe.Pointer(rms)) } func main() { argc := C.int(0) C.glutInit(&argc, nil) C.glutInitDisplayMode(C.GLUT_DOUBLE | C.GLUT_RGB) C.glutInitWindowSize(200, 200) tl := "Pixel Shader" tlc := C.CString(tl) C.glutCreateWindow(tlc) defer C.free(unsafe.Pointer(tlc)) C.glutIdleFunc(C.idleFunc()) C.glewInit() glv := C.CString("GL_VERSION_2_0") if C.glewIsSupported(glv) == 0 { log.Fatal("GL 2.0 unsupported") } defer C.free(unsafe.Pointer(glv)) setShader() C.glutMainLoop() }
Write a version of this C function in Go with identical behavior.
#include <unistd.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <ncurses.h> #define ROW_DELAY 40000 int get_rand_in_range(int min, int max) { return (rand() % ((max + 1) - min) + min); } int main(void) { srand(time(NULL)); char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; int total_chars = sizeof(chars); initscr(); noecho(); curs_set(FALSE); start_color(); init_pair(1, COLOR_GREEN, COLOR_BLACK); attron(COLOR_PAIR(1)); int max_x = 0, max_y = 0; getmaxyx(stdscr, max_y, max_x); int columns_row[max_x]; int columns_active[max_x]; int i; for (i = 0; i < max_x; i++) { columns_row[i] = -1; columns_active[i] = 0; } while (1) { for (i = 0; i < max_x; i++) { if (columns_row[i] == -1) { columns_row[i] = get_rand_in_range(0, max_y); columns_active[i] = get_rand_in_range(0, 1); } } for (i = 0; i < max_x; i++) { if (columns_active[i] == 1) { int char_index = get_rand_in_range(0, total_chars); mvprintw(columns_row[i], i, "%c", chars[char_index]); } else { mvprintw(columns_row[i], i, " "); } columns_row[i]++; if (columns_row[i] >= max_y) { columns_row[i] = -1; } if (get_rand_in_range(0, 1000) == 0) { columns_active[i] = (columns_active[i] == 0) ? 1 : 0; } } usleep(ROW_DELAY); refresh(); } endwin(); return 0; }
package main import ( gc "github.com/rthornton128/goncurses" "log" "math/rand" "time" ) const rowDelay = 40000 func main() { start := time.Now() rand.Seed(time.Now().UnixNano()) chars := []byte("0123456789") totalChars := len(chars) stdscr, err := gc.Init() if err != nil { log.Fatal("init", err) } defer gc.End() gc.Echo(false) gc.Cursor(0) if !gc.HasColors() { log.Fatal("Program requires a colour capable terminal") } if err := gc.StartColor(); err != nil { log.Fatal(err) } if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil { log.Fatal("InitPair failed: ", err) } stdscr.ColorOn(1) maxY, maxX := stdscr.MaxYX() columnsRow := make([]int, maxX) columnsActive := make([]int, maxX) for i := 0; i < maxX; i++ { columnsRow[i] = -1 columnsActive[i] = 0 } for { for i := 0; i < maxX; i++ { if columnsRow[i] == -1 { columnsRow[i] = rand.Intn(maxY + 1) columnsActive[i] = rand.Intn(2) } } for i := 0; i < maxX; i++ { if columnsActive[i] == 1 { charIndex := rand.Intn(totalChars) stdscr.MovePrintf(columnsRow[i], i, "%c", chars[charIndex]) } else { stdscr.MovePrintf(columnsRow[i], i, "%c", ' ') } columnsRow[i]++ if columnsRow[i] >= maxY { columnsRow[i] = -1 } if rand.Intn(1001) == 0 { if columnsActive[i] == 0 { columnsActive[i] = 1 } else { columnsActive[i] = 0 } } } time.Sleep(rowDelay * time.Microsecond) stdscr.Refresh() elapsed := time.Since(start) if elapsed.Minutes() >= 1 { break } } }
Translate the given C code snippet into Go without altering its behavior.
#include <unistd.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <ncurses.h> #define ROW_DELAY 40000 int get_rand_in_range(int min, int max) { return (rand() % ((max + 1) - min) + min); } int main(void) { srand(time(NULL)); char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; int total_chars = sizeof(chars); initscr(); noecho(); curs_set(FALSE); start_color(); init_pair(1, COLOR_GREEN, COLOR_BLACK); attron(COLOR_PAIR(1)); int max_x = 0, max_y = 0; getmaxyx(stdscr, max_y, max_x); int columns_row[max_x]; int columns_active[max_x]; int i; for (i = 0; i < max_x; i++) { columns_row[i] = -1; columns_active[i] = 0; } while (1) { for (i = 0; i < max_x; i++) { if (columns_row[i] == -1) { columns_row[i] = get_rand_in_range(0, max_y); columns_active[i] = get_rand_in_range(0, 1); } } for (i = 0; i < max_x; i++) { if (columns_active[i] == 1) { int char_index = get_rand_in_range(0, total_chars); mvprintw(columns_row[i], i, "%c", chars[char_index]); } else { mvprintw(columns_row[i], i, " "); } columns_row[i]++; if (columns_row[i] >= max_y) { columns_row[i] = -1; } if (get_rand_in_range(0, 1000) == 0) { columns_active[i] = (columns_active[i] == 0) ? 1 : 0; } } usleep(ROW_DELAY); refresh(); } endwin(); return 0; }
package main import ( gc "github.com/rthornton128/goncurses" "log" "math/rand" "time" ) const rowDelay = 40000 func main() { start := time.Now() rand.Seed(time.Now().UnixNano()) chars := []byte("0123456789") totalChars := len(chars) stdscr, err := gc.Init() if err != nil { log.Fatal("init", err) } defer gc.End() gc.Echo(false) gc.Cursor(0) if !gc.HasColors() { log.Fatal("Program requires a colour capable terminal") } if err := gc.StartColor(); err != nil { log.Fatal(err) } if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil { log.Fatal("InitPair failed: ", err) } stdscr.ColorOn(1) maxY, maxX := stdscr.MaxYX() columnsRow := make([]int, maxX) columnsActive := make([]int, maxX) for i := 0; i < maxX; i++ { columnsRow[i] = -1 columnsActive[i] = 0 } for { for i := 0; i < maxX; i++ { if columnsRow[i] == -1 { columnsRow[i] = rand.Intn(maxY + 1) columnsActive[i] = rand.Intn(2) } } for i := 0; i < maxX; i++ { if columnsActive[i] == 1 { charIndex := rand.Intn(totalChars) stdscr.MovePrintf(columnsRow[i], i, "%c", chars[charIndex]) } else { stdscr.MovePrintf(columnsRow[i], i, "%c", ' ') } columnsRow[i]++ if columnsRow[i] >= maxY { columnsRow[i] = -1 } if rand.Intn(1001) == 0 { if columnsActive[i] == 0 { columnsActive[i] = 1 } else { columnsActive[i] = 0 } } } time.Sleep(rowDelay * time.Microsecond) stdscr.Refresh() elapsed := time.Since(start) if elapsed.Minutes() >= 1 { break } } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdio_ext.h> #include <stdlib.h> #include <string.h> #include "wren.h" void C_getInput(WrenVM* vm) { int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2; char input[maxSize]; fgets(input, maxSize, stdin); __fpurge(stdin); input[strcspn(input, "\n")] = 0; wrenSetSlotString(vm, 0, (const char*)input); } void C_play(WrenVM* vm) { const char *args = wrenGetSlotString(vm, 1); char command[strlen(args) + 5]; strcpy(command, "play "); strcat(command, args); system(command); } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "C") == 0) { if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput; if (isStatic && strcmp(signature, "play(_)") == 0) return C_play; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "audio_overlap_loop.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { fileName := "loop.wav" scanner := bufio.NewScanner(os.Stdin) reps := 0 for reps < 1 || reps > 6 { fmt.Print("Enter number of repetitions (1 to 6) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) reps, _ = strconv.Atoi(input) } delay := 0 for delay < 50 || delay > 500 { fmt.Print("Enter delay between repetitions in microseconds (50 to 500) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) delay, _ = strconv.Atoi(input) } decay := 0.0 for decay < 0.2 || decay > 0.9 { fmt.Print("Enter decay between repetitions (0.2 to 0.9) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) decay, _ = strconv.ParseFloat(input, 64) } args := []string{fileName, "echo", "0.8", "0.7"} decay2 := 1.0 for i := 1; i <= reps; i++ { delayStr := strconv.Itoa(i * delay) decay2 *= decay decayStr := strconv.FormatFloat(decay2, 'f', -1, 64) args = append(args, delayStr, decayStr) } cmd := exec.Command("play", args...) err := cmd.Run() check(err) }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #include <stdio_ext.h> #include <stdlib.h> #include <string.h> #include "wren.h" void C_getInput(WrenVM* vm) { int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2; char input[maxSize]; fgets(input, maxSize, stdin); __fpurge(stdin); input[strcspn(input, "\n")] = 0; wrenSetSlotString(vm, 0, (const char*)input); } void C_play(WrenVM* vm) { const char *args = wrenGetSlotString(vm, 1); char command[strlen(args) + 5]; strcpy(command, "play "); strcat(command, args); system(command); } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "C") == 0) { if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput; if (isStatic && strcmp(signature, "play(_)") == 0) return C_play; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "audio_overlap_loop.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { fileName := "loop.wav" scanner := bufio.NewScanner(os.Stdin) reps := 0 for reps < 1 || reps > 6 { fmt.Print("Enter number of repetitions (1 to 6) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) reps, _ = strconv.Atoi(input) } delay := 0 for delay < 50 || delay > 500 { fmt.Print("Enter delay between repetitions in microseconds (50 to 500) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) delay, _ = strconv.Atoi(input) } decay := 0.0 for decay < 0.2 || decay > 0.9 { fmt.Print("Enter decay between repetitions (0.2 to 0.9) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) decay, _ = strconv.ParseFloat(input, 64) } args := []string{fileName, "echo", "0.8", "0.7"} decay2 := 1.0 for i := 1; i <= reps; i++ { delayStr := strconv.Itoa(i * delay) decay2 *= decay decayStr := strconv.FormatFloat(decay2, 'f', -1, 64) args = append(args, delayStr, decayStr) } cmd := exec.Command("play", args...) err := cmd.Run() check(err) }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; double value; double weight; double volume; } item_t; item_t items[] = { {"panacea", 3000.0, 0.3, 0.025}, {"ichor", 1800.0, 0.2, 0.015}, {"gold", 2500.0, 2.0, 0.002}, }; int n = sizeof (items) / sizeof (item_t); int *count; int *best; double best_value; void knapsack (int i, double value, double weight, double volume) { int j, m1, m2, m; if (i == n) { if (value > best_value) { best_value = value; for (j = 0; j < n; j++) { best[j] = count[j]; } } return; } m1 = weight / items[i].weight; m2 = volume / items[i].volume; m = m1 < m2 ? m1 : m2; for (count[i] = m; count[i] >= 0; count[i]--) { knapsack( i + 1, value + count[i] * items[i].value, weight - count[i] * items[i].weight, volume - count[i] * items[i].volume ); } } int main () { count = malloc(n * sizeof (int)); best = malloc(n * sizeof (int)); best_value = 0; knapsack(0, 0.0, 25.0, 0.25); int i; for (i = 0; i < n; i++) { printf("%d %s\n", best[i], items[i].name); } printf("best value: %.0f\n", best_value); free(count); free(best); return 0; }
package main import "fmt" type Item struct { Name string Value int Weight, Volume float64 } type Result struct { Counts []int Sum int } func min(a, b int) int { if a < b { return a } return b } func Knapsack(items []Item, weight, volume float64) (best Result) { if len(items) == 0 { return } n := len(items) - 1 maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume)) for count := 0; count <= maxCount; count++ { sol := Knapsack(items[:n], weight-float64(count)*items[n].Weight, volume-float64(count)*items[n].Volume) sol.Sum += items[n].Value * count if sol.Sum > best.Sum { sol.Counts = append(sol.Counts, count) best = sol } } return } func main() { items := []Item{ {"Panacea", 3000, 0.3, 0.025}, {"Ichor", 1800, 0.2, 0.015}, {"Gold", 2500, 2.0, 0.002}, } var sumCount, sumValue int var sumWeight, sumVolume float64 result := Knapsack(items, 25, 0.25) for i := range result.Counts { fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n", items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]), items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i]) sumCount += result.Counts[i] sumValue += items[i].Value * result.Counts[i] sumWeight += items[i].Weight * float64(result.Counts[i]) sumVolume += items[i].Volume * float64(result.Counts[i]) } fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n", sumCount, sumWeight, sumVolume, sumValue) }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define SIM_N 5 #define PRINT_DISCARDED 1 #define min(x,y) ((x<y)?(x):(y)) typedef uint8_t card_t; unsigned int rand_n(unsigned int n) { unsigned int out, mask = 1; while (mask < n) mask = mask<<1 | 1; do { out = rand() & mask; } while (out >= n); return out; } card_t rand_card() { return rand_n(52); } void print_card(card_t card) { static char *suits = "HCDS"; static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; printf(" %s%c", cards[card>>2], suits[card&3]); } void shuffle(card_t *pack) { int card; card_t temp, randpos; for (card=0; card<52; card++) { randpos = rand_card(); temp = pack[card]; pack[card] = pack[randpos]; pack[randpos] = temp; } } int trick() { card_t pack[52]; card_t blacks[52/4], reds[52/4]; card_t top, x, card; int blackn=0, redn=0, blacksw=0, redsw=0, result; for (card=0; card<52; card++) pack[card] = card; shuffle(pack); #if PRINT_DISCARDED printf("Discarded:"); #endif for (card=0; card<52; card += 2) { top = pack[card]; if (top & 1) { blacks[blackn++] = pack[card+1]; } else { reds[redn++] = pack[card+1]; } #if PRINT_DISCARDED print_card(top); #endif } #if PRINT_DISCARDED printf("\n"); #endif x = rand_n(min(blackn, redn)); for (card=0; card<x; card++) { blacksw = rand_n(blackn); redsw = rand_n(redn); top = blacks[blacksw]; blacks[blacksw] = reds[redsw]; reds[redsw] = top; } result = 0; for (card=0; card<blackn; card++) result += (blacks[card] & 1) == 1; for (card=0; card<redn; card++) result -= (reds[card] & 1) == 0; result = !result; printf("The number of black cards in the 'black' pile" " %s the number of red cards in the 'red' pile.\n", result? "equals" : "does not equal"); return result; } int main() { unsigned int seed, i, successes = 0; FILE *r; if ((r = fopen("/dev/urandom", "r")) == NULL) { fprintf(stderr, "cannot open /dev/urandom\n"); return 255; } if (fread(&seed, sizeof(unsigned int), 1, r) != 1) { fprintf(stderr, "failed to read from /dev/urandom\n"); return 255; } fclose(r); srand(seed); for (i=1; i<=SIM_N; i++) { printf("Simulation %d\n", i); successes += trick(); printf("\n"); } printf("Result: %d successes out of %d simulations\n", successes, SIM_N); return 0; }
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) var red, black, discard []byte for i := 0; i < 51; i += 2 { switch pack[i] { case 'B': black = append(black, pack[i+1]) case 'R': red = append(red, pack[i+1]) } discard = append(discard, pack[i]) } lr, lb, ld := len(red), len(black), len(discard) fmt.Println("After dealing the cards the state of the stacks is:") fmt.Printf(" Red  : %2d cards -> %c\n", lr, red) fmt.Printf(" Black  : %2d cards -> %c\n", lb, black) fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard) min := lr if lb < min { min = lb } n := 1 + rand.Intn(min) rp := rand.Perm(lr)[:n] bp := rand.Perm(lb)[:n] fmt.Printf("\n%d card(s) are to be swapped.\n\n", n) fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:") fmt.Printf(" Red  : %2d\n", rp) fmt.Printf(" Black  : %2d\n", bp) for i := 0; i < n; i++ { red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]] } fmt.Println("\nAfter swapping, the state of the red and black stacks is:") fmt.Printf(" Red  : %c\n", red) fmt.Printf(" Black  : %c\n", black) rcount, bcount := 0, 0 for _, c := range red { if c == 'R' { rcount++ } } for _, c := range black { if c == 'B' { bcount++ } } fmt.Println("\nThe number of red cards in the red stack =", rcount) fmt.Println("The number of black cards in the black stack =", bcount) if rcount == bcount { fmt.Println("So the asssertion is correct!") } else { fmt.Println("So the asssertion is incorrect!") } }
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define SIM_N 5 #define PRINT_DISCARDED 1 #define min(x,y) ((x<y)?(x):(y)) typedef uint8_t card_t; unsigned int rand_n(unsigned int n) { unsigned int out, mask = 1; while (mask < n) mask = mask<<1 | 1; do { out = rand() & mask; } while (out >= n); return out; } card_t rand_card() { return rand_n(52); } void print_card(card_t card) { static char *suits = "HCDS"; static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; printf(" %s%c", cards[card>>2], suits[card&3]); } void shuffle(card_t *pack) { int card; card_t temp, randpos; for (card=0; card<52; card++) { randpos = rand_card(); temp = pack[card]; pack[card] = pack[randpos]; pack[randpos] = temp; } } int trick() { card_t pack[52]; card_t blacks[52/4], reds[52/4]; card_t top, x, card; int blackn=0, redn=0, blacksw=0, redsw=0, result; for (card=0; card<52; card++) pack[card] = card; shuffle(pack); #if PRINT_DISCARDED printf("Discarded:"); #endif for (card=0; card<52; card += 2) { top = pack[card]; if (top & 1) { blacks[blackn++] = pack[card+1]; } else { reds[redn++] = pack[card+1]; } #if PRINT_DISCARDED print_card(top); #endif } #if PRINT_DISCARDED printf("\n"); #endif x = rand_n(min(blackn, redn)); for (card=0; card<x; card++) { blacksw = rand_n(blackn); redsw = rand_n(redn); top = blacks[blacksw]; blacks[blacksw] = reds[redsw]; reds[redsw] = top; } result = 0; for (card=0; card<blackn; card++) result += (blacks[card] & 1) == 1; for (card=0; card<redn; card++) result -= (reds[card] & 1) == 0; result = !result; printf("The number of black cards in the 'black' pile" " %s the number of red cards in the 'red' pile.\n", result? "equals" : "does not equal"); return result; } int main() { unsigned int seed, i, successes = 0; FILE *r; if ((r = fopen("/dev/urandom", "r")) == NULL) { fprintf(stderr, "cannot open /dev/urandom\n"); return 255; } if (fread(&seed, sizeof(unsigned int), 1, r) != 1) { fprintf(stderr, "failed to read from /dev/urandom\n"); return 255; } fclose(r); srand(seed); for (i=1; i<=SIM_N; i++) { printf("Simulation %d\n", i); successes += trick(); printf("\n"); } printf("Result: %d successes out of %d simulations\n", successes, SIM_N); return 0; }
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) var red, black, discard []byte for i := 0; i < 51; i += 2 { switch pack[i] { case 'B': black = append(black, pack[i+1]) case 'R': red = append(red, pack[i+1]) } discard = append(discard, pack[i]) } lr, lb, ld := len(red), len(black), len(discard) fmt.Println("After dealing the cards the state of the stacks is:") fmt.Printf(" Red  : %2d cards -> %c\n", lr, red) fmt.Printf(" Black  : %2d cards -> %c\n", lb, black) fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard) min := lr if lb < min { min = lb } n := 1 + rand.Intn(min) rp := rand.Perm(lr)[:n] bp := rand.Perm(lb)[:n] fmt.Printf("\n%d card(s) are to be swapped.\n\n", n) fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:") fmt.Printf(" Red  : %2d\n", rp) fmt.Printf(" Black  : %2d\n", bp) for i := 0; i < n; i++ { red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]] } fmt.Println("\nAfter swapping, the state of the red and black stacks is:") fmt.Printf(" Red  : %c\n", red) fmt.Printf(" Black  : %c\n", black) rcount, bcount := 0, 0 for _, c := range red { if c == 'R' { rcount++ } } for _, c := range black { if c == 'B' { bcount++ } } fmt.Println("\nThe number of red cards in the red stack =", rcount) fmt.Println("The number of black cards in the black stack =", bcount) if rcount == bcount { fmt.Println("So the asssertion is correct!") } else { fmt.Println("So the asssertion is incorrect!") } }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #define SIM_N 5 #define PRINT_DISCARDED 1 #define min(x,y) ((x<y)?(x):(y)) typedef uint8_t card_t; unsigned int rand_n(unsigned int n) { unsigned int out, mask = 1; while (mask < n) mask = mask<<1 | 1; do { out = rand() & mask; } while (out >= n); return out; } card_t rand_card() { return rand_n(52); } void print_card(card_t card) { static char *suits = "HCDS"; static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; printf(" %s%c", cards[card>>2], suits[card&3]); } void shuffle(card_t *pack) { int card; card_t temp, randpos; for (card=0; card<52; card++) { randpos = rand_card(); temp = pack[card]; pack[card] = pack[randpos]; pack[randpos] = temp; } } int trick() { card_t pack[52]; card_t blacks[52/4], reds[52/4]; card_t top, x, card; int blackn=0, redn=0, blacksw=0, redsw=0, result; for (card=0; card<52; card++) pack[card] = card; shuffle(pack); #if PRINT_DISCARDED printf("Discarded:"); #endif for (card=0; card<52; card += 2) { top = pack[card]; if (top & 1) { blacks[blackn++] = pack[card+1]; } else { reds[redn++] = pack[card+1]; } #if PRINT_DISCARDED print_card(top); #endif } #if PRINT_DISCARDED printf("\n"); #endif x = rand_n(min(blackn, redn)); for (card=0; card<x; card++) { blacksw = rand_n(blackn); redsw = rand_n(redn); top = blacks[blacksw]; blacks[blacksw] = reds[redsw]; reds[redsw] = top; } result = 0; for (card=0; card<blackn; card++) result += (blacks[card] & 1) == 1; for (card=0; card<redn; card++) result -= (reds[card] & 1) == 0; result = !result; printf("The number of black cards in the 'black' pile" " %s the number of red cards in the 'red' pile.\n", result? "equals" : "does not equal"); return result; } int main() { unsigned int seed, i, successes = 0; FILE *r; if ((r = fopen("/dev/urandom", "r")) == NULL) { fprintf(stderr, "cannot open /dev/urandom\n"); return 255; } if (fread(&seed, sizeof(unsigned int), 1, r) != 1) { fprintf(stderr, "failed to read from /dev/urandom\n"); return 255; } fclose(r); srand(seed); for (i=1; i<=SIM_N; i++) { printf("Simulation %d\n", i); successes += trick(); printf("\n"); } printf("Result: %d successes out of %d simulations\n", successes, SIM_N); return 0; }
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) var red, black, discard []byte for i := 0; i < 51; i += 2 { switch pack[i] { case 'B': black = append(black, pack[i+1]) case 'R': red = append(red, pack[i+1]) } discard = append(discard, pack[i]) } lr, lb, ld := len(red), len(black), len(discard) fmt.Println("After dealing the cards the state of the stacks is:") fmt.Printf(" Red  : %2d cards -> %c\n", lr, red) fmt.Printf(" Black  : %2d cards -> %c\n", lb, black) fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard) min := lr if lb < min { min = lb } n := 1 + rand.Intn(min) rp := rand.Perm(lr)[:n] bp := rand.Perm(lb)[:n] fmt.Printf("\n%d card(s) are to be swapped.\n\n", n) fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:") fmt.Printf(" Red  : %2d\n", rp) fmt.Printf(" Black  : %2d\n", bp) for i := 0; i < n; i++ { red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]] } fmt.Println("\nAfter swapping, the state of the red and black stacks is:") fmt.Printf(" Red  : %c\n", red) fmt.Printf(" Black  : %c\n", black) rcount, bcount := 0, 0 for _, c := range red { if c == 'R' { rcount++ } } for _, c := range black { if c == 'B' { bcount++ } } fmt.Println("\nThe number of red cards in the red stack =", rcount) fmt.Println("The number of black cards in the black stack =", bcount) if rcount == bcount { fmt.Println("So the asssertion is correct!") } else { fmt.Println("So the asssertion is incorrect!") } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> char text_char(char c) { switch (c) { case 'a': case 'b': case 'c': return '2'; case 'd': case 'e': case 'f': return '3'; case 'g': case 'h': case 'i': return '4'; case 'j': case 'k': case 'l': return '5'; case 'm': case 'n': case 'o': return '6'; case 'p': case 'q': case 'r': case 's': return '7'; case 't': case 'u': case 'v': return '8'; case 'w': case 'x': case 'y': case 'z': return '9'; default: return 0; } } bool text_string(const GString* word, GString* text) { g_string_set_size(text, word->len); for (size_t i = 0; i < word->len; ++i) { char c = text_char(g_ascii_tolower(word->str[i])); if (c == 0) return false; text->str[i] = c; } return true; } typedef struct textonym_tag { const char* text; size_t length; GPtrArray* words; } textonym_t; int compare_by_text_length(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->length > t2->length) return -1; if (t1->length < t2->length) return 1; return strcmp(t1->text, t2->text); } int compare_by_word_count(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->words->len > t2->words->len) return -1; if (t1->words->len < t2->words->len) return 1; return strcmp(t1->text, t2->text); } void print_words(GPtrArray* words) { for (guint i = 0, n = words->len; i < n; ++i) { if (i > 0) printf(", "); printf("%s", g_ptr_array_index(words, i)); } printf("\n"); } void print_top_words(GArray* textonyms, guint top) { for (guint i = 0; i < top; ++i) { const textonym_t* t = &g_array_index(textonyms, textonym_t, i); printf("%s = ", t->text); print_words(t->words); } } void free_strings(gpointer ptr) { g_ptr_array_free(ptr, TRUE); } bool find_textonyms(const char* filename, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(filename, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return false; } GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, free_strings); GString* word = g_string_sized_new(64); GString* text = g_string_sized_new(64); guint count = 0; gsize term_pos; while (g_io_channel_read_line_string(channel, word, &term_pos, &error) == G_IO_STATUS_NORMAL) { g_string_truncate(word, term_pos); if (!text_string(word, text)) continue; GPtrArray* words = g_hash_table_lookup(ht, text->str); if (words == NULL) { words = g_ptr_array_new_full(1, g_free); g_hash_table_insert(ht, g_strdup(text->str), words); } g_ptr_array_add(words, g_strdup(word->str)); ++count; } g_io_channel_unref(channel); g_string_free(word, TRUE); g_string_free(text, TRUE); if (error != NULL) { g_propagate_error(error_ptr, error); g_hash_table_destroy(ht); return false; } GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t)); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, ht); while (g_hash_table_iter_next(&iter, &key, &value)) { GPtrArray* v = value; if (v->len > 1) { textonym_t textonym; textonym.text = key; textonym.length = strlen(key); textonym.words = v; g_array_append_val(words, textonym); } } printf("There are %u words in '%s' which can be represented by the digit key mapping.\n", count, filename); guint size = g_hash_table_size(ht); printf("They require %u digit combinations to represent them.\n", size); guint textonyms = words->len; printf("%u digit combinations represent Textonyms.\n", textonyms); guint top = 5; if (textonyms < top) top = textonyms; printf("\nTop %u by number of words:\n", top); g_array_sort(words, compare_by_word_count); print_top_words(words, top); printf("\nTop %u by length:\n", top); g_array_sort(words, compare_by_text_length); print_top_words(words, top); g_array_free(words, TRUE); g_hash_table_destroy(ht); return true; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s word-list\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; if (!find_textonyms(argv[1], &error)) { if (error != NULL) { fprintf(stderr, "%s: %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } return EXIT_SUCCESS; }
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t := NewTextonym(phoneMap) _, err := ReadFromFile(t, *wordlist) if err != nil { log.Fatal(err) } t.Report(os.Stdout, *wordlist) } var phoneMap = map[byte][]rune{ '2': []rune("ABC"), '3': []rune("DEF"), '4': []rune("GHI"), '5': []rune("JKL"), '6': []rune("MNO"), '7': []rune("PQRS"), '8': []rune("TUV"), '9': []rune("WXYZ"), } func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) { f, err := os.Open(filename) if err != nil { return 0, err } n, err := r.ReadFrom(f) if cerr := f.Close(); err == nil && cerr != nil { err = cerr } return n, err } type Textonym struct { numberMap map[string][]string letterMap map[rune]byte count int textonyms int } func NewTextonym(dm map[byte][]rune) *Textonym { lm := make(map[rune]byte, 26) for d, ll := range dm { for _, l := range ll { lm[l] = d } } return &Textonym{letterMap: lm} } func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) { t.numberMap = make(map[string][]string) buf := make([]byte, 0, 32) sc := bufio.NewScanner(r) sc.Split(bufio.ScanWords) scan: for sc.Scan() { buf = buf[:0] word := sc.Text() n += int64(len(word)) + 1 for _, r := range word { d, ok := t.letterMap[unicode.ToUpper(r)] if !ok { continue scan } buf = append(buf, d) } num := string(buf) t.numberMap[num] = append(t.numberMap[num], word) t.count++ if len(t.numberMap[num]) == 2 { t.textonyms++ } } return n, sc.Err() } func (t *Textonym) Most() (most int, subset map[string][]string) { for k, v := range t.numberMap { switch { case len(v) > most: subset = make(map[string][]string) most = len(v) fallthrough case len(v) == most: subset[k] = v } } return most, subset } func (t *Textonym) Report(w io.Writer, name string) { fmt.Fprintf(w, ` There are %v words in %q which can be represented by the digit key mapping. They require %v digit combinations to represent them. %v digit combinations represent Textonyms. `, t.count, name, len(t.numberMap), t.textonyms) n, sub := t.Most() fmt.Fprintln(w, "\nThe numbers mapping to the most words map to", n, "words each:") for k, v := range sub { fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", ")) } }
Generate a Go translation of this C snippet without changing its computational steps.
void quad_bezier( image img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int x3, unsigned int y3, color_component r, color_component g, color_component b );
package raster const b2Seg = 20 func (b *Bitmap) Bézier2(x1, y1, x2, y2, x3, y3 int, p Pixel) { var px, py [b2Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) for i := range px { c := float64(i) / b2Seg a := 1 - c a, b, c := a*a, 2 * c * a, c*c px[i] = int(a*fx1 + b*fx2 + c*fx3) py[i] = int(a*fy1 + b*fy2 + c*fy3) } x0, y0 := px[0], py[0] for i := 1; i <= b2Seg; i++ { x1, y1 := px[i], py[i] b.Line(x0, y0, x1, y1, p) x0, y0 = x1, y1 } } func (b *Bitmap) Bézier2Rgb(x1, y1, x2, y2, x3, y3 int, c Rgb) { b.Bézier2(x1, y1, x2, y2, x3, y3, c.Pixel()) }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdio.h> #include <stdio_ext.h> #include <stdlib.h> #include <string.h> #include "wren.h" void C_getInput(WrenVM* vm) { int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2; char input[maxSize]; fgets(input, maxSize, stdin); __fpurge(stdin); input[strcspn(input, "\n")] = 0; wrenSetSlotString(vm, 0, (const char*)input); } void C_sox(WrenVM* vm) { const char *args = wrenGetSlotString(vm, 1); char command[strlen(args) + 4]; strcpy(command, "sox "); strcat(command, args); system(command); } void C_removeFile(WrenVM* vm) { const char *name = wrenGetSlotString(vm, 1); if (remove(name) != 0) perror("Error deleting file."); } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "C") == 0) { if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput; if (isStatic && strcmp(signature, "sox(_)") == 0) return C_sox; if (isStatic && strcmp(signature, "removeFile(_)") == 0) return C_removeFile; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "waveform_analysis_top_and_tail.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { const sec = "00:00:01" scanner := bufio.NewScanner(os.Stdin) name := "" for name == "" { fmt.Print("Enter name of audio file to be trimmed : ") scanner.Scan() name = scanner.Text() check(scanner.Err()) } name2 := "" for name2 == "" { fmt.Print("Enter name of output file  : ") scanner.Scan() name2 = scanner.Text() check(scanner.Err()) } squelch := 0.0 for squelch < 1 || squelch > 10 { fmt.Print("Enter squelch level % max (1 to 10)  : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) squelch, _ = strconv.ParseFloat(input, 64) } squelchS := strconv.FormatFloat(squelch, 'f', -1, 64) + "%" tmp1 := "tmp1_" + name tmp2 := "tmp2_" + name args := []string{name, tmp1, "silence", "1", sec, squelchS} cmd := exec.Command("sox", args...) err := cmd.Run() check(err) args = []string{tmp1, tmp2, "reverse"} cmd = exec.Command("sox", args...) err = cmd.Run() check(err) args = []string{tmp2, tmp1, "silence", "1", sec, squelchS} cmd = exec.Command("sox", args...) err = cmd.Run() check(err) args = []string{tmp1, name2, "reverse"} cmd = exec.Command("sox", args...) err = cmd.Run() check(err) err = os.Remove(tmp1) check(err) err = os.Remove(tmp2) check(err) }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <float.h> #include <iso646.h> #include <math.h> #define map_size_rows 10 #define map_size_cols 10 char map[map_size_rows][map_size_cols] = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 1, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} }; struct stop { double col, row; int * n; int n_len; double f, g, h; int from; }; int ind[map_size_rows][map_size_cols] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1} }; struct route { int x; int y; double d; }; int main() { int i, j, k, l, b, found; int p_len = 0; int * path = NULL; int c_len = 0; int * closed = NULL; int o_len = 1; int * open = (int*)calloc(o_len, sizeof(int)); double min, tempg; int s; int e; int current; int s_len = 0; struct stop * stops = NULL; int r_len = 0; struct route * routes = NULL; for (i = 1; i < map_size_rows - 1; i++) { for (j = 1; j < map_size_cols - 1; j++) { if (!map[i][j]) { ++s_len; stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop)); int t = s_len - 1; stops[t].col = j; stops[t].row = i; stops[t].from = -1; stops[t].g = DBL_MAX; stops[t].n_len = 0; stops[t].n = NULL; ind[i][j] = t; } } } s = 0; e = s_len - 1; for (i = 0; i < s_len; i++) { stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2)); } for (i = 1; i < map_size_rows - 1; i++) { for (j = 1; j < map_size_cols - 1; j++) { if (ind[i][j] >= 0) { for (k = i - 1; k <= i + 1; k++) { for (l = j - 1; l <= j + 1; l++) { if ((k == i) and (l == j)) { continue; } if (ind[k][l] >= 0) { ++r_len; routes = (struct route *)realloc(routes, r_len * sizeof(struct route)); int t = r_len - 1; routes[t].x = ind[i][j]; routes[t].y = ind[k][l]; routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2)); ++stops[routes[t].x].n_len; stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int)); stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t; } } } } } } open[0] = s; stops[s].g = 0; stops[s].f = stops[s].g + stops[s].h; found = 0; while (o_len and not found) { min = DBL_MAX; for (i = 0; i < o_len; i++) { if (stops[open[i]].f < min) { current = open[i]; min = stops[open[i]].f; } } if (current == e) { found = 1; ++p_len; path = (int*)realloc(path, p_len * sizeof(int)); path[p_len - 1] = current; while (stops[current].from >= 0) { current = stops[current].from; ++p_len; path = (int*)realloc(path, p_len * sizeof(int)); path[p_len - 1] = current; } } for (i = 0; i < o_len; i++) { if (open[i] == current) { if (i not_eq (o_len - 1)) { for (j = i; j < (o_len - 1); j++) { open[j] = open[j + 1]; } } --o_len; open = (int*)realloc(open, o_len * sizeof(int)); break; } } ++c_len; closed = (int*)realloc(closed, c_len * sizeof(int)); closed[c_len - 1] = current; for (i = 0; i < stops[current].n_len; i++) { b = 0; for (j = 0; j < c_len; j++) { if (routes[stops[current].n[i]].y == closed[j]) { b = 1; } } if (b) { continue; } tempg = stops[current].g + routes[stops[current].n[i]].d; b = 1; if (o_len > 0) { for (j = 0; j < o_len; j++) { if (routes[stops[current].n[i]].y == open[j]) { b = 0; } } } if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) { stops[routes[stops[current].n[i]].y].from = current; stops[routes[stops[current].n[i]].y].g = tempg; stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h; if (b) { ++o_len; open = (int*)realloc(open, o_len * sizeof(int)); open[o_len - 1] = routes[stops[current].n[i]].y; } } } } for (i = 0; i < map_size_rows; i++) { for (j = 0; j < map_size_cols; j++) { if (map[i][j]) { putchar(0xdb); } else { b = 0; for (k = 0; k < p_len; k++) { if (ind[i][j] == path[k]) { ++b; } } if (b) { putchar('x'); } else { putchar('.'); } } } putchar('\n'); } if (not found) { puts("IMPOSSIBLE"); } else { printf("path cost is %d:\n", p_len); for (i = p_len - 1; i >= 0; i--) { printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row); } } for (i = 0; i < s_len; ++i) { free(stops[i].n); } free(stops); free(routes); free(path); free(open); free(closed); return 0; }
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
Write the same code in Go as shown below in C.
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <float.h> #include <iso646.h> #include <math.h> #define map_size_rows 10 #define map_size_cols 10 char map[map_size_rows][map_size_cols] = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 1, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} }; struct stop { double col, row; int * n; int n_len; double f, g, h; int from; }; int ind[map_size_rows][map_size_cols] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1} }; struct route { int x; int y; double d; }; int main() { int i, j, k, l, b, found; int p_len = 0; int * path = NULL; int c_len = 0; int * closed = NULL; int o_len = 1; int * open = (int*)calloc(o_len, sizeof(int)); double min, tempg; int s; int e; int current; int s_len = 0; struct stop * stops = NULL; int r_len = 0; struct route * routes = NULL; for (i = 1; i < map_size_rows - 1; i++) { for (j = 1; j < map_size_cols - 1; j++) { if (!map[i][j]) { ++s_len; stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop)); int t = s_len - 1; stops[t].col = j; stops[t].row = i; stops[t].from = -1; stops[t].g = DBL_MAX; stops[t].n_len = 0; stops[t].n = NULL; ind[i][j] = t; } } } s = 0; e = s_len - 1; for (i = 0; i < s_len; i++) { stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2)); } for (i = 1; i < map_size_rows - 1; i++) { for (j = 1; j < map_size_cols - 1; j++) { if (ind[i][j] >= 0) { for (k = i - 1; k <= i + 1; k++) { for (l = j - 1; l <= j + 1; l++) { if ((k == i) and (l == j)) { continue; } if (ind[k][l] >= 0) { ++r_len; routes = (struct route *)realloc(routes, r_len * sizeof(struct route)); int t = r_len - 1; routes[t].x = ind[i][j]; routes[t].y = ind[k][l]; routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2)); ++stops[routes[t].x].n_len; stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int)); stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t; } } } } } } open[0] = s; stops[s].g = 0; stops[s].f = stops[s].g + stops[s].h; found = 0; while (o_len and not found) { min = DBL_MAX; for (i = 0; i < o_len; i++) { if (stops[open[i]].f < min) { current = open[i]; min = stops[open[i]].f; } } if (current == e) { found = 1; ++p_len; path = (int*)realloc(path, p_len * sizeof(int)); path[p_len - 1] = current; while (stops[current].from >= 0) { current = stops[current].from; ++p_len; path = (int*)realloc(path, p_len * sizeof(int)); path[p_len - 1] = current; } } for (i = 0; i < o_len; i++) { if (open[i] == current) { if (i not_eq (o_len - 1)) { for (j = i; j < (o_len - 1); j++) { open[j] = open[j + 1]; } } --o_len; open = (int*)realloc(open, o_len * sizeof(int)); break; } } ++c_len; closed = (int*)realloc(closed, c_len * sizeof(int)); closed[c_len - 1] = current; for (i = 0; i < stops[current].n_len; i++) { b = 0; for (j = 0; j < c_len; j++) { if (routes[stops[current].n[i]].y == closed[j]) { b = 1; } } if (b) { continue; } tempg = stops[current].g + routes[stops[current].n[i]].d; b = 1; if (o_len > 0) { for (j = 0; j < o_len; j++) { if (routes[stops[current].n[i]].y == open[j]) { b = 0; } } } if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) { stops[routes[stops[current].n[i]].y].from = current; stops[routes[stops[current].n[i]].y].g = tempg; stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h; if (b) { ++o_len; open = (int*)realloc(open, o_len * sizeof(int)); open[o_len - 1] = routes[stops[current].n[i]].y; } } } } for (i = 0; i < map_size_rows; i++) { for (j = 0; j < map_size_cols; j++) { if (map[i][j]) { putchar(0xdb); } else { b = 0; for (k = 0; k < p_len; k++) { if (ind[i][j] == path[k]) { ++b; } } if (b) { putchar('x'); } else { putchar('.'); } } } putchar('\n'); } if (not found) { puts("IMPOSSIBLE"); } else { printf("path cost is %d:\n", p_len); for (i = p_len - 1; i >= 0; i--) { printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row); } } for (i = 0; i < s_len; ++i) { free(stops[i].n); } free(stops); free(routes); free(path); free(open); free(closed); return 0; }
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
Produce a functionally identical Go code for the snippet given in C.
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <float.h> #include <iso646.h> #include <math.h> #define map_size_rows 10 #define map_size_cols 10 char map[map_size_rows][map_size_cols] = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 1, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} }; struct stop { double col, row; int * n; int n_len; double f, g, h; int from; }; int ind[map_size_rows][map_size_cols] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1} }; struct route { int x; int y; double d; }; int main() { int i, j, k, l, b, found; int p_len = 0; int * path = NULL; int c_len = 0; int * closed = NULL; int o_len = 1; int * open = (int*)calloc(o_len, sizeof(int)); double min, tempg; int s; int e; int current; int s_len = 0; struct stop * stops = NULL; int r_len = 0; struct route * routes = NULL; for (i = 1; i < map_size_rows - 1; i++) { for (j = 1; j < map_size_cols - 1; j++) { if (!map[i][j]) { ++s_len; stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop)); int t = s_len - 1; stops[t].col = j; stops[t].row = i; stops[t].from = -1; stops[t].g = DBL_MAX; stops[t].n_len = 0; stops[t].n = NULL; ind[i][j] = t; } } } s = 0; e = s_len - 1; for (i = 0; i < s_len; i++) { stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2)); } for (i = 1; i < map_size_rows - 1; i++) { for (j = 1; j < map_size_cols - 1; j++) { if (ind[i][j] >= 0) { for (k = i - 1; k <= i + 1; k++) { for (l = j - 1; l <= j + 1; l++) { if ((k == i) and (l == j)) { continue; } if (ind[k][l] >= 0) { ++r_len; routes = (struct route *)realloc(routes, r_len * sizeof(struct route)); int t = r_len - 1; routes[t].x = ind[i][j]; routes[t].y = ind[k][l]; routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2)); ++stops[routes[t].x].n_len; stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int)); stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t; } } } } } } open[0] = s; stops[s].g = 0; stops[s].f = stops[s].g + stops[s].h; found = 0; while (o_len and not found) { min = DBL_MAX; for (i = 0; i < o_len; i++) { if (stops[open[i]].f < min) { current = open[i]; min = stops[open[i]].f; } } if (current == e) { found = 1; ++p_len; path = (int*)realloc(path, p_len * sizeof(int)); path[p_len - 1] = current; while (stops[current].from >= 0) { current = stops[current].from; ++p_len; path = (int*)realloc(path, p_len * sizeof(int)); path[p_len - 1] = current; } } for (i = 0; i < o_len; i++) { if (open[i] == current) { if (i not_eq (o_len - 1)) { for (j = i; j < (o_len - 1); j++) { open[j] = open[j + 1]; } } --o_len; open = (int*)realloc(open, o_len * sizeof(int)); break; } } ++c_len; closed = (int*)realloc(closed, c_len * sizeof(int)); closed[c_len - 1] = current; for (i = 0; i < stops[current].n_len; i++) { b = 0; for (j = 0; j < c_len; j++) { if (routes[stops[current].n[i]].y == closed[j]) { b = 1; } } if (b) { continue; } tempg = stops[current].g + routes[stops[current].n[i]].d; b = 1; if (o_len > 0) { for (j = 0; j < o_len; j++) { if (routes[stops[current].n[i]].y == open[j]) { b = 0; } } } if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) { stops[routes[stops[current].n[i]].y].from = current; stops[routes[stops[current].n[i]].y].g = tempg; stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h; if (b) { ++o_len; open = (int*)realloc(open, o_len * sizeof(int)); open[o_len - 1] = routes[stops[current].n[i]].y; } } } } for (i = 0; i < map_size_rows; i++) { for (j = 0; j < map_size_cols; j++) { if (map[i][j]) { putchar(0xdb); } else { b = 0; for (k = 0; k < p_len; k++) { if (ind[i][j] == path[k]) { ++b; } } if (b) { putchar('x'); } else { putchar('.'); } } } putchar('\n'); } if (not found) { puts("IMPOSSIBLE"); } else { printf("path cost is %d:\n", p_len); for (i = p_len - 1; i >= 0; i--) { printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row); } } for (i = 0; i < s_len; ++i) { free(stops[i].n); } free(stops); free(routes); free(path); free(open); free(closed); return 0; }
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func Route(start, end Node) (route []Node, cost int) { cr := &rNode{n: start, l: 1, f: end.Heuristic(start)} r := map[Node]*rNode{start: cr} oh := openHeap{cr} for len(oh) > 0 { bestRoute := heap.Pop(&oh).(*rNode) bestNode := bestRoute.n if bestNode == end { cost = bestRoute.g route = make([]Node, bestRoute.l) for i := len(route) - 1; i >= 0; i-- { route[i] = bestRoute.n bestRoute = r[bestRoute.from] } return } l := bestRoute.l + 1 for _, to := range bestNode.To() { g := bestRoute.g + to.Cost if alt, ok := r[to.To]; !ok { alt = &rNode{n: to.To, from: bestNode, l: l, g: g, f: g + end.Heuristic(to.To)} r[to.To] = alt heap.Push(&oh, alt) } else { if g >= alt.g { continue } alt.from = bestNode alt.l = l alt.g = g alt.f = end.Heuristic(alt.n) if alt.fx < 0 { heap.Push(&oh, alt) } else { heap.Fix(&oh, alt.fx) } } } } return nil, 0 } func (h openHeap) Len() int { return len(h) } func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f } func (h openHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] h[i].fx = i h[j].fx = j } func (p *openHeap) Push(x interface{}) { h := *p fx := len(h) h = append(h, x.(*rNode)) h[fx].fx = fx *p = h } func (p *openHeap) Pop() interface{} { h := *p last := len(h) - 1 *p = h[:last] h[last].fx = -1 return h[last] }
Translate the given C code snippet into Go without altering its behavior.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(file, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return NULL; } GPtrArray* dict = g_ptr_array_new_full(1024, g_free); GString* line = g_string_sized_new(64); gsize term_pos; while (g_io_channel_read_line_string(channel, line, &term_pos, &error) == G_IO_STATUS_NORMAL) { char* word = g_strdup(line->str); word[term_pos] = '\0'; g_ptr_array_add(dict, word); } g_string_free(line, TRUE); g_io_channel_unref(channel); if (error != NULL) { g_propagate_error(error_ptr, error); g_ptr_array_free(dict, TRUE); return NULL; } g_ptr_array_sort(dict, string_compare); return dict; } void rotate(char* str, size_t len) { char c = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = c; } char* dictionary_search(const GPtrArray* dictionary, const char* word) { char** result = bsearch(&word, dictionary->pdata, dictionary->len, sizeof(char*), string_compare); return result != NULL ? *result : NULL; } void find_teacup_words(GPtrArray* dictionary) { GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal); GPtrArray* teacup_words = g_ptr_array_new(); GString* temp = g_string_sized_new(8); for (size_t i = 0, n = dictionary->len; i < n; ++i) { char* word = g_ptr_array_index(dictionary, i); size_t len = strlen(word); if (len < 3 || g_hash_table_contains(found, word)) continue; g_ptr_array_set_size(teacup_words, 0); g_string_assign(temp, word); bool is_teacup_word = true; for (size_t i = 0; i < len - 1; ++i) { rotate(temp->str, len); char* w = dictionary_search(dictionary, temp->str); if (w == NULL) { is_teacup_word = false; break; } if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL)) g_ptr_array_add(teacup_words, w); } if (is_teacup_word && teacup_words->len > 0) { printf("%s", word); g_hash_table_add(found, word); for (size_t i = 0; i < teacup_words->len; ++i) { char* teacup_word = g_ptr_array_index(teacup_words, i); printf(" %s", teacup_word); g_hash_table_add(found, teacup_word); } printf("\n"); } } g_string_free(temp, TRUE); g_ptr_array_free(teacup_words, TRUE); g_hash_table_destroy(found); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s dictionary\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; GPtrArray* dictionary = load_dictionary(argv[1], &error); if (dictionary == NULL) { if (error != NULL) { fprintf(stderr, "Cannot load dictionary file '%s': %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } find_teacup_words(dictionary); g_ptr_array_free(dictionary, TRUE); return EXIT_SUCCESS; }
package main import ( "bufio" "fmt" "log" "os" "sort" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func readWords(fileName string) []string { file, err := os.Open(fileName) check(err) defer file.Close() var words []string scanner := bufio.NewScanner(file) for scanner.Scan() { word := strings.ToLower(strings.TrimSpace(scanner.Text())) if len(word) >= 3 { words = append(words, word) } } check(scanner.Err()) return words } func rotate(runes []rune) { first := runes[0] copy(runes, runes[1:]) runes[len(runes)-1] = first } func main() { dicts := []string{"mit_10000.txt", "unixdict.txt"} for _, dict := range dicts { fmt.Printf("Using %s:\n\n", dict) words := readWords(dict) n := len(words) used := make(map[string]bool) outer: for _, word := range words { runes := []rune(word) variants := []string{word} for i := 0; i < len(runes)-1; i++ { rotate(runes) word2 := string(runes) if word == word2 || used[word2] { continue outer } ix := sort.SearchStrings(words, word2) if ix == n || words[ix] != word2 { continue outer } variants = append(variants, word2) } for _, variant := range variants { used[variant] = true } fmt.Println(variants) } fmt.Println() } }
Write the same code in Go as shown below in C.
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false; return n % d == 0; } int main() { setlocale(LC_ALL, ""); uint64_t previous = 1, gap = 0, sum = 0; int niven_index = 0, gap_index = 1; printf("Gap index Gap Niven index Niven number\n"); for (uint64_t niven = 1; gap_index <= 32; ++niven) { sum = digit_sum(niven, sum); if (divisible(niven, sum)) { if (niven > previous + gap) { gap = niven - previous; printf("%'9d %'4llu %'14d %'15llu\n", gap_index++, gap, niven_index, previous); } previous = niven; ++niven_index; } } return 0; }
package main import "fmt" type is func() uint64 func newSum() is { var ms is ms = func() uint64 { ms = newSum() return ms() } var msd, d uint64 return func() uint64 { if d < 9 { d++ } else { d = 0 msd = ms() } return msd + d } } func newHarshard() is { i := uint64(0) sum := newSum() return func() uint64 { for i++; i%sum() != 0; i++ { } return i } } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { fmt.Println("Gap Index of gap Starting Niven") fmt.Println("=== ============= ==============") h := newHarshard() pg := uint64(0) pn := h() for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() { g := n - pn if g > pg { fmt.Printf("%3d %13s %14s\n", g, commatize(i), commatize(pn)) pg = g } pn = n } }
Maintain the same structure and functionality when rewriting this code in Go.
#include <stdio.h> #define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x) int add(int x, int y) { int result = x + y; DEBUG_INT(x); DEBUG_INT(y); DEBUG_INT(result); DEBUG_INT(result+1); return result; } int main() { add(2, 7); return 0; }
package main import ( "fmt" "runtime" ) type point struct { x, y float64 } func add(x, y int) int { result := x + y debug("x", x) debug("y", y) debug("result", result) debug("result+1", result+1) return result } func debug(s string, x interface{}) { _, _, lineNo, _ := runtime.Caller(1) fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x) } func main() { add(2, 7) b := true debug("b", b) s := "Hello" debug("s", s) p := point{2, 3} debug("p", p) q := &p debug("q", q) }
Keep all operations the same but rewrite the snippet in Go.
#include <stdbool.h> #include <stdio.h> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } unsigned int reverse(unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= 10) rev = rev * 10 + n % 10; return rev; } int main() { unsigned int count = 0; for (unsigned int n = 1; n < 500; ++n) { if (is_prime(n) && is_prime(reverse(n))) printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' '); } printf("\nCount = %u\n", count); return 0; }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { c := sieve(999) reversedPrimes := []int{2} for i := 3; i < 500; i += 2 { if !c[i] && !c[reversed(i)] { reversedPrimes = append(reversedPrimes, i) } } fmt.Println("Primes under 500 which are also primes when the digits are reversed:") for i, p := range reversedPrimes { fmt.Printf("%5d", p) if (i+1) % 10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such primes found.\n", len(reversedPrimes)) }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdbool.h> #include <stdio.h> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } unsigned int reverse(unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= 10) rev = rev * 10 + n % 10; return rev; } int main() { unsigned int count = 0; for (unsigned int n = 1; n < 500; ++n) { if (is_prime(n) && is_prime(reverse(n))) printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' '); } printf("\nCount = %u\n", count); return 0; }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := 4; i < limit; i += 2 { c[i] = true } p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { c := sieve(999) reversedPrimes := []int{2} for i := 3; i < 500; i += 2 { if !c[i] && !c[reversed(i)] { reversedPrimes = append(reversedPrimes, i) } } fmt.Println("Primes under 500 which are also primes when the digits are reversed:") for i, p := range reversedPrimes { fmt.Printf("%5d", p) if (i+1) % 10 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such primes found.\n", len(reversedPrimes)) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ double a,b,n,i,incr = 0.0001; printf("Enter major and minor axes of the SuperEllipse : "); scanf("%lf%lf",&a,&b); printf("Enter n : "); scanf("%lf",&n); initwindow(500,500,"Superellipse"); for(i=0;i<2*pi;i+=incr){ putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15); } printf("Done. %lf",i); getch(); closegraph(); }
package main import ( "github.com/fogleman/gg" "math" ) func superEllipse(dc *gg.Context, n float64, a int) { hw := float64(dc.Width() / 2) hh := float64(dc.Height() / 2) y := make([]float64, a+1) for x := 0; x <= a; x++ { aa := math.Pow(float64(a), n) xx := math.Pow(float64(x), n) y[x] = math.Pow(aa-xx, 1.0/n) } for x := a; x >= 0; x-- { dc.LineTo(hw+float64(x), hh-y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw+float64(x), hh+y[x]) } for x := a; x >= 0; x-- { dc.LineTo(hw-float64(x), hh+y[x]) } for x := 0; x <= a; x++ { dc.LineTo(hw-float64(x), hh-y[x]) } dc.SetRGB(1, 1, 1) dc.Fill() } func main() { dc := gg.NewContext(500, 500) dc.SetRGB(0, 0, 0) dc.Clear() superEllipse(dc, 2.5, 200) dc.SavePNG("superellipse.png") }
Write a version of this C function in Go with identical behavior.
#include <stdio.h> #include <stdlib.h> #define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0) void _mr_unrank1(int rank, int n, int *vec) { int t, q, r; if (n < 1) return; q = rank / n; r = rank % n; SWAP(vec[r], vec[n-1]); _mr_unrank1(q, n-1, vec); } int _mr_rank1(int n, int *vec, int *inv) { int s, t; if (n < 2) return 0; s = vec[n-1]; SWAP(vec[n-1], vec[inv[n-1]]); SWAP(inv[s], inv[n-1]); return s + n * _mr_rank1(n-1, vec, inv); } void get_permutation(int rank, int n, int *vec) { int i; for (i = 0; i < n; ++i) vec[i] = i; _mr_unrank1(rank, n, vec); } int get_rank(int n, int *vec) { int i, r, *v, *inv; v = malloc(n * sizeof(int)); inv = malloc(n * sizeof(int)); for (i = 0; i < n; ++i) { v[i] = vec[i]; inv[vec[i]] = i; } r = _mr_rank1(n, v, inv); free(inv); free(v); return r; } int main(int argc, char *argv[]) { int i, r, tv[4]; for (r = 0; r < 24; ++r) { printf("%3d: ", r); get_permutation(r, 4, tv); for (i = 0; i < 4; ++i) { if (0 == i) printf("[ "); else printf(", "); printf("%d", tv[i]); } printf(" ] = %d\n", get_rank(4, tv)); } }
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } return p } func MRRank(p []int) (r int) { p = append([]int{}, p...) inv := inverse(p) for i := len(p) - 1; i > 0; i-- { s := p[i] p[inv[i]] = s inv[s] = inv[i] } for i := 1; i < len(p); i++ { r = r*(i+1) + p[i] } return } func inverse(p []int) []int { r := make([]int, len(p)) for i, x := range p { r[x] = i } return r } func fact(n int) (f int) { for f = n; n > 2; { n-- f *= n } return } func main() { n := 3 fmt.Println("permutations of", n, "items") f := fact(n) for i := 0; i < f; i++ { p := MRPerm(i, n) fmt.Println(i, p, MRRank(p)) } n = 12 fmt.Println("permutations of", n, "items") f = fact(n) m := map[int]bool{} for len(m) < 4 { r := rand.Intn(f) if m[r] { continue } m[r] = true fmt.Println(r, MRPerm(r, n)) } }
Change the programming language of this snippet from C to Go without modifying what it does.
#include <stdio.h> #include <stdlib.h> #define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0) void _mr_unrank1(int rank, int n, int *vec) { int t, q, r; if (n < 1) return; q = rank / n; r = rank % n; SWAP(vec[r], vec[n-1]); _mr_unrank1(q, n-1, vec); } int _mr_rank1(int n, int *vec, int *inv) { int s, t; if (n < 2) return 0; s = vec[n-1]; SWAP(vec[n-1], vec[inv[n-1]]); SWAP(inv[s], inv[n-1]); return s + n * _mr_rank1(n-1, vec, inv); } void get_permutation(int rank, int n, int *vec) { int i; for (i = 0; i < n; ++i) vec[i] = i; _mr_unrank1(rank, n, vec); } int get_rank(int n, int *vec) { int i, r, *v, *inv; v = malloc(n * sizeof(int)); inv = malloc(n * sizeof(int)); for (i = 0; i < n; ++i) { v[i] = vec[i]; inv[vec[i]] = i; } r = _mr_rank1(n, v, inv); free(inv); free(v); return r; } int main(int argc, char *argv[]) { int i, r, tv[4]; for (r = 0; r < 24; ++r) { printf("%3d: ", r); get_permutation(r, 4, tv); for (i = 0; i < 4; ++i) { if (0 == i) printf("[ "); else printf(", "); printf("%d", tv[i]); } printf(" ] = %d\n", get_rank(4, tv)); } }
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } return p } func MRRank(p []int) (r int) { p = append([]int{}, p...) inv := inverse(p) for i := len(p) - 1; i > 0; i-- { s := p[i] p[inv[i]] = s inv[s] = inv[i] } for i := 1; i < len(p); i++ { r = r*(i+1) + p[i] } return } func inverse(p []int) []int { r := make([]int, len(p)) for i, x := range p { r[x] = i } return r } func fact(n int) (f int) { for f = n; n > 2; { n-- f *= n } return } func main() { n := 3 fmt.Println("permutations of", n, "items") f := fact(n) for i := 0; i < f; i++ { p := MRPerm(i, n) fmt.Println(i, p, MRRank(p)) } n = 12 fmt.Println("permutations of", n, "items") f = fact(n) m := map[int]bool{} for len(m) < 4 { r := rand.Intn(f) if m[r] { continue } m[r] = true fmt.Println(r, MRPerm(r, n)) } }
Preserve the algorithm and functionality while converting the code from C to Go.
#include <stdio.h> #include <stdbool.h> int main() { int curr[5][5]; int max_claim[5][5]; int avl[5]; int alloc[5] = {0, 0, 0, 0, 0}; int max_res[5]; int running[5]; int i, j, exec, r, p; int count = 0; bool safe = false; printf("\nEnter the number of resources: "); scanf("%d", &r); printf("\nEnter the number of processes: "); scanf("%d", &p); for (i = 0; i < p; i++) { running[i] = 1; count++; } printf("\nEnter Claim Vector: "); for (i = 0; i < r; i++) scanf("%d", &max_res[i]); printf("\nEnter Allocated Resource Table: "); for (i = 0; i < p; i++) { for (j = 0; j < r; j++) scanf("%d", &curr[i][j]); } printf("\nEnter Maximum Claim table: "); for (i = 0; i < p; i++) { for (j = 0; j < r; j++) scanf("%d", &max_claim[i][j]); } printf("\nThe Claim Vector is: "); for (i = 0; i < r; i++) printf("%d ", max_res[i]); printf("\nThe Allocated Resource Table:\n"); for (i = 0; i < p; i++) { for (j = 0; j < r; j++) printf("\t%d", curr[i][j]); printf("\n"); } printf("\nThe Maximum Claim Table:\n"); for (i = 0; i < p; i++) { for (j = 0; j < r; j++) printf("\t%d", max_claim[i][j]); printf("\n"); } for (i = 0; i < p; i++) for (j = 0; j < r; j++) alloc[j] += curr[i][j]; printf("\nAllocated resources: "); for (i = 0; i < r; i++) printf("%d ", alloc[i]); for (i = 0; i < r; i++) avl[i] = max_res[i] - alloc[i]; printf("\nAvailable resources: "); for (i = 0; i < r; i++) printf("%d ", avl[i]); printf("\n"); while (count != 0) { safe = false; for (i = 0; i < p; i++) { if (running[i]) { exec = 1; for (j = 0; j < r; j++) { if (max_claim[i][j] - curr[i][j] > avl[j]) { exec = 0; break; } } if (exec) { printf("\nProcess%d is executing.\n", i + 1); running[i] = 0; count--; safe = true; for (j = 0; j < r; j++) avl[j] += curr[i][j]; break; } } } if (!safe) { printf("\nThe processes are in unsafe state."); break; } if (safe) printf("\nThe process is in safe state."); printf("\nAvailable vector: "); for (i = 0; i < r; i++) printf("%d ", avl[i]); } return 0; }
package bank import ( "bytes" "errors" "fmt" "log" "sort" "sync" ) type PID string type RID string type RMap map[RID]int func (m RMap) String() string { rs := make([]string, len(m)) i := 0 for r := range m { rs[i] = string(r) i++ } sort.Strings(rs) var b bytes.Buffer b.WriteString("{") for _, r := range rs { fmt.Fprintf(&b, "%q: %d, ", r, m[RID(r)]) } bb := b.Bytes() if len(bb) > 1 { bb[len(bb)-2] = '}' } return string(bb) } type Bank struct { available RMap max map[PID]RMap allocation map[PID]RMap sync.Mutex } func (b *Bank) need(p PID, r RID) int { return b.max[p][r] - b.allocation[p][r] } func New(available RMap) (b *Bank, err error) { for r, a := range available { if a < 0 { return nil, fmt.Errorf("negative resource %s: %d", r, a) } } return &Bank{ available: available, max: map[PID]RMap{}, allocation: map[PID]RMap{}, }, nil } func (b *Bank) NewProcess(p PID, max RMap) (err error) { b.Lock() defer b.Unlock() if _, ok := b.max[p]; ok { return fmt.Errorf("process %s already registered", p) } for r, m := range max { switch a, ok := b.available[r]; { case !ok: return fmt.Errorf("resource %s unknown", r) case m > a: return fmt.Errorf("resource %s: process %s max %d > available %d", r, p, m, a) } } b.max[p] = max b.allocation[p] = RMap{} return } func (b *Bank) Request(pid PID, change RMap) (err error) { b.Lock() defer b.Unlock() if _, ok := b.max[pid]; !ok { return fmt.Errorf("process %s unknown", pid) } for r, c := range change { if c < 0 { return errors.New("decrease not allowed") } if _, ok := b.available[r]; !ok { return fmt.Errorf("resource %s unknown", r) } if c > b.need(pid, r) { return errors.New("increase exceeds declared max") } } for r, c := range change { b.allocation[pid][r] += c } defer func() { if err != nil { for r, c := range change { b.allocation[pid][r] -= c } } }() cash := RMap{} for r, a := range b.available { cash[r] = a } perm := make([]PID, len(b.allocation)) i := 1 for pr, a := range b.allocation { if pr == pid { perm[0] = pr } else { perm[i] = pr i++ } for r, a := range a { cash[r] -= a } } ret := RMap{} m := len(perm) for { h := 0 h: for ; ; h++ { if h == m { return errors.New("request would make deadlock possible") } for r := range b.available { if b.need(perm[h], r) > cash[r]+ret[r] { continue h } } log.Println(" ", perm[h], "could terminate") break } if h == 0 { return nil } for r, a := range b.allocation[perm[h]] { ret[r] += a } m-- perm[h] = perm[m] } }
Please provide an equivalent version of this C code in Go.
#include <stdio.h> #include <stdlib.h> size_t rprint(char *s, int *x, int len) { #define sep (a > s ? "," : "") #define ol (s ? 100 : 0) int i, j; char *a = s; for (i = j = 0; i < len; i = ++j) { for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); if (i + 1 < j) a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]); else while (i <= j) a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]); } return a - s; #undef sep #undef ol } int main() { int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1); rprint(s, x, sizeof(x) / sizeof(int)); printf("%s\n", s); return 0; }
package main import ( "errors" "fmt" "strconv" "strings" ) func main() { rf, err := rangeFormat([]int{ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, }) if err != nil { fmt.Println(err) return } fmt.Println("range format:", rf) } func rangeFormat(a []int) (string, error) { if len(a) == 0 { return "", nil } var parts []string for n1 := 0; ; { n2 := n1 + 1 for n2 < len(a) && a[n2] == a[n2-1]+1 { n2++ } s := strconv.Itoa(a[n1]) if n2 == n1+2 { s += "," + strconv.Itoa(a[n2-1]) } else if n2 > n1+2 { s += "-" + strconv.Itoa(a[n2-1]) } parts = append(parts, s) if n2 == len(a) { break } if a[n2] == a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence repeats value %d", a[n2])) } if a[n2] < a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence not ordered: %d < %d", a[n2], a[n2-1])) } n1 = n2 } return strings.Join(parts, ","), nil }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> #include <sys/mman.h> #include <string.h> int test (int a, int b) { char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3}; void *buf; int c; buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON,-1,0); memcpy (buf, code, sizeof(code)); c = ((int (*) (int, int))buf)(a, b); munmap (buf, sizeof(code)); return c; } int main () { printf("%d\n", test(7,12)); return 0; }
package main import "fmt" import "C" func main() { code := []byte{ 0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75, 0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75, 0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3, } le := len(code) buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC, C.MAP_PRIVATE|C.MAP_ANON, -1, 0) codePtr := C.CBytes(code) C.memcpy(buf, codePtr, C.size_t(le)) var a, b byte = 7, 12 fmt.Printf("%d + %d = ", a, b) C.runMachineCode(buf, C.byte(a), C.byte(b)) C.munmap(buf, C.size_t(le)) C.free(codePtr) }
Keep all operations the same but rewrite the snippet in Go.
#include<stdio.h> #include<ctype.h> void typeDetector(char* str){ if(isalnum(str[0])!=0) printf("\n%c is alphanumeric",str[0]); if(isalpha(str[0])!=0) printf("\n%c is alphabetic",str[0]); if(iscntrl(str[0])!=0) printf("\n%c is a control character",str[0]); if(isdigit(str[0])!=0) printf("\n%c is a digit",str[0]); if(isprint(str[0])!=0) printf("\n%c is printable",str[0]); if(ispunct(str[0])!=0) printf("\n%c is a punctuation character",str[0]); if(isxdigit(str[0])!=0) printf("\n%c is a hexadecimal digit",str[0]); } int main(int argC, char* argV[]) { int i; if(argC==1) printf("Usage : %s <followed by ASCII characters>"); else{ for(i=1;i<argC;i++) typeDetector(argV[i]); } return 0; }
package main import "fmt" type any = interface{} func showType(a any) { switch a.(type) { case rune: fmt.Printf("The type of '%c' is %T\n", a, a) default: fmt.Printf("The type of '%v' is %T\n", a, a) } } func main() { values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"} for _, value := range values { showType(value) } }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <stdio.h> #include <math.h> #define max(x,y) ((x) > (y) ? (x) : (y)) int tri[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; int main(void) { const int len = sizeof(tri) / sizeof(tri[0]); const int base = (sqrt(8*len + 1) - 1) / 2; int step = base - 1; int stepc = 0; int i; for (i = len - base - 1; i >= 0; --i) { tri[i] += max(tri[i + step], tri[i + step + 1]); if (++stepc == step) { step--; stepc = 0; } } printf("%d\n", tri[0]); return 0; }
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
Change the programming language of this snippet from C to Go without modifying what it does.
#include<stdlib.h> #include<stdio.h> char** imageMatrix; char blankPixel,imagePixel; typedef struct{ int row,col; }pixel; int getBlackNeighbours(int row,int col){ int i,j,sum = 0; for(i=-1;i<=1;i++){ for(j=-1;j<=1;j++){ if(i!=0 || j!=0) sum+= (imageMatrix[row+i][col+j]==imagePixel); } } return sum; } int getBWTransitions(int row,int col){ return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel) +(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel) +(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel) +(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel) +(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel) +(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel) +(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel) +(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel)); } int zhangSuenTest1(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) && (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel)); } int zhangSuenTest2(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel)); } void zhangSuen(char* inputFile, char* outputFile){ int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed; pixel* markers; FILE* inputP = fopen(inputFile,"r"); fscanf(inputP,"%d%d",&rows,&cols); fscanf(inputP,"%d%d",&blankPixel,&imagePixel); blankPixel<=9?blankPixel+='0':blankPixel; imagePixel<=9?imagePixel+='0':imagePixel; printf("\nPrinting original image :\n"); imageMatrix = (char**)malloc(rows*sizeof(char*)); for(i=0;i<rows;i++){ imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char)); fscanf(inputP,"%s\n",imageMatrix[i]); printf("\n%s",imageMatrix[i]); } fclose(inputP); endRow = rows-2; endCol = cols-2; do{ markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } if(processed==0) processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); }while(processed==1); FILE* outputP = fopen(outputFile,"w"); printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n"); for(i=0;i<rows;i++){ for(j=0;j<cols;j++){ printf("%c",imageMatrix[i][j]); fprintf(outputP,"%c",imageMatrix[i][j]); } printf("\n"); fprintf(outputP,"\n"); } fclose(outputP); printf("\nImage also written to : %s",outputFile); } int main() { char inputFile[100],outputFile[100]; printf("Enter full path of input image file : "); scanf("%s",inputFile); printf("Enter full path of output image file : "); scanf("%s",outputFile); zhangSuen(inputFile,outputFile); return 0; }
package main import ( "bytes" "fmt" "strings" ) var in = ` 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000` func main() { b := wbFromString(in, '1') b.zhangSuen() fmt.Println(b) } const ( white = 0 black = 1 ) type wbArray [][]byte func wbFromString(s string, blk byte) wbArray { lines := strings.Split(s, "\n")[1:] b := make(wbArray, len(lines)) for i, sl := range lines { bl := make([]byte, len(sl)) for j := 0; j < len(sl); j++ { bl[j] = sl[j] & 1 } b[i] = bl } return b } var sym = [2]byte{ white: ' ', black: '#', } func (b wbArray) String() string { b2 := bytes.Join(b, []byte{'\n'}) for i, b1 := range b2 { if b1 > 1 { continue } b2[i] = sym[b1] } return string(b2) } var nb = [...][2]int{ 2: {-1, 0}, 3: {-1, 1}, 4: {0, 1}, 5: {1, 1}, 6: {1, 0}, 7: {1, -1}, 8: {0, -1}, 9: {-1, -1}, } func (b wbArray) reset(en []int) (rs bool) { var r, c int var p [10]byte readP := func() { for nx := 1; nx <= 9; nx++ { n := nb[nx] p[nx] = b[r+n[0]][c+n[1]] } } shiftRead := func() { n := nb[3] p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]] n = nb[4] p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]] n = nb[5] p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]] } countA := func() (ct byte) { bit := p[9] for nx := 2; nx <= 9; nx++ { last := bit bit = p[nx] if last == white { ct += bit } } return ct } countB := func() (ct byte) { for nx := 2; nx <= 9; nx++ { ct += p[nx] } return ct } lastRow := len(b) - 1 lastCol := len(b[0]) - 1 mark := make([][]bool, lastRow) for r = range mark { mark[r] = make([]bool, lastCol) } for r = 1; r < lastRow; r++ { c = 1 readP() for { m := false if !(p[1] == black) { goto markDone } if b1 := countB(); !(2 <= b1 && b1 <= 6) { goto markDone } if !(countA() == 1) { goto markDone } { e1, e2 := p[en[1]], p[en[2]] if !(p[en[0]]&e1&e2 == 0) { goto markDone } if !(e1&e2&p[en[3]] == 0) { goto markDone } } m = true rs = true markDone: mark[r][c] = m c++ if c == lastCol { break } shiftRead() } } if rs { for r = 1; r < lastRow; r++ { for c = 1; c < lastCol; c++ { if mark[r][c] { b[r][c] = white } } } } return rs } var step1 = []int{2, 4, 6, 8} var step2 = []int{4, 2, 8, 6} func (b wbArray) zhangSuen() { for { rs1 := b.reset(step1) rs2 := b.reset(step2) if !rs1 && !rs2 { break } } }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <ctype.h> #include <string.h> typedef struct { unsigned char r, g, b; } rgb_t; typedef struct { int w, h; rgb_t **pix; } image_t, *image; typedef struct { int r[256], g[256], b[256]; int n; } color_histo_t; int write_ppm(image im, char *fn) { FILE *fp = fopen(fn, "w"); if (!fp) return 0; fprintf(fp, "P6\n%d %d\n255\n", im->w, im->h); fwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp); fclose(fp); return 1; } image img_new(int w, int h) { int i; image im = malloc(sizeof(image_t) + h * sizeof(rgb_t*) + sizeof(rgb_t) * w * h); im->w = w; im->h = h; im->pix = (rgb_t**)(im + 1); for (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++) im->pix[i] = im->pix[i - 1] + w; return im; } int read_num(FILE *f) { int n; while (!fscanf(f, "%d ", &n)) { if ((n = fgetc(f)) == '#') { while ((n = fgetc(f)) != '\n') if (n == EOF) break; if (n == '\n') continue; } else return 0; } return n; } image read_ppm(char *fn) { FILE *fp = fopen(fn, "r"); int w, h, maxval; image im = 0; if (!fp) return 0; if (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp))) goto bail; w = read_num(fp); h = read_num(fp); maxval = read_num(fp); if (!w || !h || !maxval) goto bail; im = img_new(w, h); fread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp); bail: if (fp) fclose(fp); return im; } void del_pixels(image im, int row, int col, int size, color_histo_t *h) { int i; rgb_t *pix; if (col < 0 || col >= im->w) return; for (i = row - size; i <= row + size && i < im->h; i++) { if (i < 0) continue; pix = im->pix[i] + col; h->r[pix->r]--; h->g[pix->g]--; h->b[pix->b]--; h->n--; } } void add_pixels(image im, int row, int col, int size, color_histo_t *h) { int i; rgb_t *pix; if (col < 0 || col >= im->w) return; for (i = row - size; i <= row + size && i < im->h; i++) { if (i < 0) continue; pix = im->pix[i] + col; h->r[pix->r]++; h->g[pix->g]++; h->b[pix->b]++; h->n++; } } void init_histo(image im, int row, int size, color_histo_t*h) { int j; memset(h, 0, sizeof(color_histo_t)); for (j = 0; j < size && j < im->w; j++) add_pixels(im, row, j, size, h); } int median(const int *x, int n) { int i; for (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++); return i; } void median_color(rgb_t *pix, const color_histo_t *h) { pix->r = median(h->r, h->n); pix->g = median(h->g, h->n); pix->b = median(h->b, h->n); } image median_filter(image in, int size) { int row, col; image out = img_new(in->w, in->h); color_histo_t h; for (row = 0; row < in->h; row ++) { for (col = 0; col < in->w; col++) { if (!col) init_histo(in, row, size, &h); else { del_pixels(in, row, col - size, size, &h); add_pixels(in, row, col + size, size, &h); } median_color(out->pix[row] + col, &h); } } return out; } int main(int c, char **v) { int size; image in, out; if (c <= 3) { printf("Usage: %s size ppm_in ppm_out\n", v[0]); return 0; } size = atoi(v[1]); printf("filter size %d\n", size); if (size < 0) size = 1; in = read_ppm(v[2]); out = median_filter(in, size); write_ppm(out, v[3]); free(in); free(out); return 0; }
package main import ( "fmt" "raster" ) var g0, g1 *raster.Grmap var ko [][]int var kc []uint16 var mid int func init() { ko = [][]int{ {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}} kc = make([]uint16, len(ko)) mid = len(ko) / 2 } func main() { b, err := raster.ReadPpmFile("Lenna50.ppm") if err != nil { fmt.Println(err) return } g0 = b.Grmap() w, h := g0.Extent() g1 = raster.NewGrmap(w, h) for y := 0; y < h; y++ { for x := 0; x < w; x++ { g1.SetPx(x, y, median(x, y)) } } err = g1.Bitmap().WritePpmFile("median.ppm") if err != nil { fmt.Println(err) } } func median(x, y int) uint16 { var n int for _, o := range ko { c, ok := g0.GetPx(x+o[0], y+o[1]) if !ok { continue } var i int for ; i < n; i++ { if c < kc[i] { for j := n; j > i; j-- { kc[j] = kc[j-1] } break } } kc[i] = c n++ } switch { case n == len(kc): return kc[mid] case n%2 == 1: return kc[n/2] } m := n / 2 return (kc[m-1] + kc[m]) / 2 }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include <err.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <time.h> #include <unistd.h> int main(int argc, char **argv) { extern char *__progname; time_t clock; int fd; if (argc != 2) { fprintf(stderr, "usage: %s file\n", __progname); exit(1); } fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666); if (fd < 0) err(1, argv[1]); if (daemon(0, 0) < 0) err(1, "daemon"); if (dup2(fd, STDOUT_FILENO) < 0) { syslog(LOG_ERR, "dup2: %s", strerror(errno)); exit(1); } close(fd); for (;;) { time(&clock); fputs(ctime(&clock), stdout); if (fflush(stdout) == EOF) { syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno)); exit(1); } sleep(1); } }
package main import ( "fmt" "github.com/sevlyar/go-daemon" "log" "os" "time" ) func work() { f, err := os.Create("daemon_output.txt") if err != nil { log.Fatal(err) } defer f.Close() ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C { fmt.Fprintln(f, t) } }() time.Sleep(60 * time.Second) ticker.Stop() log.Print("ticker stopped") } func main() { cntxt := &daemon.Context{ PidFileName: "pid", PidFilePerm: 0644, LogFileName: "log", LogFilePerm: 0640, WorkDir: "./", Umask: 027, Args: []string{"[Rosetta Code daemon example]"}, } d, err := cntxt.Reborn() if err != nil { log.Fatal("Unable to run: ", err) } if d != nil { return } defer cntxt.Release() log.Print("- - - - - - - - - - - - - - -") log.Print("daemon started") work() }
Please provide an equivalent version of this C code in Go.
#include <err.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <syslog.h> #include <time.h> #include <unistd.h> int main(int argc, char **argv) { extern char *__progname; time_t clock; int fd; if (argc != 2) { fprintf(stderr, "usage: %s file\n", __progname); exit(1); } fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666); if (fd < 0) err(1, argv[1]); if (daemon(0, 0) < 0) err(1, "daemon"); if (dup2(fd, STDOUT_FILENO) < 0) { syslog(LOG_ERR, "dup2: %s", strerror(errno)); exit(1); } close(fd); for (;;) { time(&clock); fputs(ctime(&clock), stdout); if (fflush(stdout) == EOF) { syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno)); exit(1); } sleep(1); } }
package main import ( "fmt" "github.com/sevlyar/go-daemon" "log" "os" "time" ) func work() { f, err := os.Create("daemon_output.txt") if err != nil { log.Fatal(err) } defer f.Close() ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C { fmt.Fprintln(f, t) } }() time.Sleep(60 * time.Second) ticker.Stop() log.Print("ticker stopped") } func main() { cntxt := &daemon.Context{ PidFileName: "pid", PidFilePerm: 0644, LogFileName: "log", LogFilePerm: 0640, WorkDir: "./", Umask: 027, Args: []string{"[Rosetta Code daemon example]"}, } d, err := cntxt.Reborn() if err != nil { log.Fatal("Unable to run: ", err) } if d != nil { return } defer cntxt.Release() log.Print("- - - - - - - - - - - - - - -") log.Print("daemon started") work() }
Write the same algorithm in Go as shown in this C implementation.
#include <stdio.h> #include <string.h> #include <ctype.h> #include <setjmp.h> #define AT(CHAR) ( *pos == CHAR && ++pos ) #define TEST(STR) ( strncmp( pos, STR, strlen(STR) ) == 0 \ && ! isalnum(pos[strlen(STR)]) && pos[strlen(STR)] != '_' ) #define IS(STR) ( TEST(STR) && (pos += strlen(STR)) ) static char *pos; static char *startpos; static jmp_buf jmpenv; static int error(char *message) { printf("false %s\n%*s^ %s\n", startpos, pos - startpos + 7, "", message); longjmp( jmpenv, 1 ); } static int expr(int level) { while( isspace(*pos) ) ++pos; if( AT('(') ) { if( expr(0) && ! AT(')') ) error("missing close paren"); } else if( level <= 4 && IS("not") && expr(6) ) { } else if( TEST("or") || TEST("and") || TEST("not") ) { error("expected a primary, found an operator"); } else if( isdigit(*pos) ) pos += strspn( pos, "0123456789" ); else if( isalpha(*pos) ) pos += strspn( pos, "0123456789_" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ); else error("expected a primary"); do { while( isspace(*pos) ) ++pos; } while( level <= 2 && IS("or") ? expr(3) : level <= 3 && IS("and") ? expr(4) : level <= 4 && (AT('=') || AT('<')) ? expr(5) : level == 5 && (*pos == '=' || *pos == '<') ? error("non-associative") : level <= 6 && (AT('+') || AT('-')) ? expr(7) : level <= 7 && (AT('*') || AT('/')) ? expr(8) : 0 ); return 1; } static void parse(char *source) { startpos = pos = source; if( setjmp(jmpenv) ) return; expr(0); if( *pos ) error("unexpected character following valid parse"); printf(" true %s\n", source); } static char *tests[] = { "3 + not 5", "3 + (not 5)", "(42 + 3", "(42 + 3 some_other_syntax_error", "not 3 < 4 or (true or 3/4+8*5-5*2 < 56) and 4*3 < 12 or not true", "and 3 < 2", "not 7 < 2", "2 < 3 < 4", "2 < foobar - 3 < 4", "2 < foobar and 3 < 4", "4 * (32 - 16) + 9 = 73", "235 76 + 1", "a + b = not c and false", "a + b = (not c) and false", "a + b = (not c and false)", "ab_c / bd2 or < e_f7", "g not = h", "i++", "j & k", "l or _m", "wombat", "WOMBAT or monotreme", "a + b - c * d / e < f and not ( g = h )", "$", }; int main(int argc, char *argv[]) { for( int i = 0; i < sizeof(tests)/sizeof(*tests); i++ ) parse(tests[i]); }
package main import ( "fmt" "go/parser" "regexp" "strings" ) var ( re1 = regexp.MustCompile(`[^_a-zA-Z0-9\+\-\*/=<\(\)\s]`) re2 = regexp.MustCompile(`\b_\w*\b`) re3 = regexp.MustCompile(`[=<+*/-]\s*not`) re4 = regexp.MustCompile(`(=|<)\s*[^(=< ]+\s*([=<+*/-])`) ) var subs = [][2]string{ {"=", "=="}, {" not ", " ! "}, {"(not ", "(! "}, {" or ", " || "}, {" and ", " && "}, } func possiblyValid(expr string) error { matches := re1.FindStringSubmatch(expr) if matches != nil { return fmt.Errorf("invalid character %q found", []rune(matches[0])[0]) } if re2.MatchString(expr) { return fmt.Errorf("identifier cannot begin with an underscore") } if re3.MatchString(expr) { return fmt.Errorf("expected operand, found 'not'") } matches = re4.FindStringSubmatch(expr) if matches != nil { return fmt.Errorf("operator %q is non-associative", []rune(matches[1])[0]) } return nil } func modify(err error) string { e := err.Error() for _, sub := range subs { e = strings.ReplaceAll(e, strings.TrimSpace(sub[1]), strings.TrimSpace(sub[0])) } return strings.Split(e, ":")[2][1:] } func main() { exprs := []string{ "$", "one", "either or both", "a + 1", "a + b < c", "a = b", "a or b = c", "3 + not 5", "3 + (not 5)", "(42 + 3", "(42 + 3)", " not 3 < 4 or (true or 3 / 4 + 8 * 5 - 5 * 2 < 56) and 4 * 3 < 12 or not true", " and 3 < 2", "not 7 < 2", "2 < 3 < 4", "2 < (3 < 4)", "2 < foobar - 3 < 4", "2 < foobar and 3 < 4", "4 * (32 - 16) + 9 = 73", "235 76 + 1", "true or false = not true", "true or false = (not true)", "not true or false = false", "not true = false", "a + b = not c and false", "a + b = (not c) and false", "a + b = (not c and false)", "ab_c / bd2 or < e_f7", "g not = h", "été = false", "i++", "j & k", "l or _m", } for _, expr := range exprs { fmt.Printf("Statement to verify: %q\n", expr) if err := possiblyValid(expr); err != nil { fmt.Printf("\"false\" -> %s\n\n", err.Error()) continue } expr = fmt.Sprintf(" %s ", expr) for _, sub := range subs { expr = strings.ReplaceAll(expr, sub[0], sub[1]) } _, err := parser.ParseExpr(expr) if err != nil { fmt.Println(`"false" ->`, modify(err)) } else { fmt.Println(`"true"`) } fmt.Println() } }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> int Gcd(int v1, int v2) { int a, b, r; if (v1 < v2) { a = v2; b = v1; } else { a = v1; b = v2; } do { r = a % b; if (r == 0) { break; } else { a = b; b = r; } } while (1 == 1); return b; } int NotInList(int num, int numtrip, int *tripletslist) { for (int i = 0; i < numtrip; i++) { if (num == tripletslist[i]) { return 0; } } return 1; } int main() { int coprime[50]; int gcd1, gcd2; int ntrip = 2; int n = 3; coprime[0] = 1; coprime[1] = 2; while ( n < 50) { gcd1 = Gcd(n, coprime[ntrip-1]); gcd2 = Gcd(n, coprime[ntrip-2]); if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime)) { coprime[ntrip++] = n; n = 3; } else { n++; } } printf("\n"); for (int i = 0; i < ntrip; i++) { printf("%2d ", coprime[i]); if ((i+1) % 10 == 0) { printf("\n"); } } printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip); return 0; }
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 { m++ } if m >= limit { break } cpt = append(cpt, m) } fmt.Printf("Coprime triplets under %d:\n", limit) for i, t := range cpt { fmt.Printf("%2d ", t) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\nFound %d such numbers\n", len(cpt)) }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> int Gcd(int v1, int v2) { int a, b, r; if (v1 < v2) { a = v2; b = v1; } else { a = v1; b = v2; } do { r = a % b; if (r == 0) { break; } else { a = b; b = r; } } while (1 == 1); return b; } int NotInList(int num, int numtrip, int *tripletslist) { for (int i = 0; i < numtrip; i++) { if (num == tripletslist[i]) { return 0; } } return 1; } int main() { int coprime[50]; int gcd1, gcd2; int ntrip = 2; int n = 3; coprime[0] = 1; coprime[1] = 2; while ( n < 50) { gcd1 = Gcd(n, coprime[ntrip-1]); gcd2 = Gcd(n, coprime[ntrip-2]); if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime)) { coprime[ntrip++] = n; n = 3; } else { n++; } } printf("\n"); for (int i = 0; i < ntrip; i++) { printf("%2d ", coprime[i]); if ((i+1) % 10 == 0) { printf("\n"); } } printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip); return 0; }
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 { m++ } if m >= limit { break } cpt = append(cpt, m) } fmt.Printf("Coprime triplets under %d:\n", limit) for i, t := range cpt { fmt.Printf("%2d ", t) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\nFound %d such numbers\n", len(cpt)) }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> int Gcd(int v1, int v2) { int a, b, r; if (v1 < v2) { a = v2; b = v1; } else { a = v1; b = v2; } do { r = a % b; if (r == 0) { break; } else { a = b; b = r; } } while (1 == 1); return b; } int NotInList(int num, int numtrip, int *tripletslist) { for (int i = 0; i < numtrip; i++) { if (num == tripletslist[i]) { return 0; } } return 1; } int main() { int coprime[50]; int gcd1, gcd2; int ntrip = 2; int n = 3; coprime[0] = 1; coprime[1] = 2; while ( n < 50) { gcd1 = Gcd(n, coprime[ntrip-1]); gcd2 = Gcd(n, coprime[ntrip-2]); if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime)) { coprime[ntrip++] = n; n = 3; } else { n++; } } printf("\n"); for (int i = 0; i < ntrip; i++) { printf("%2d ", coprime[i]); if ((i+1) % 10 == 0) { printf("\n"); } } printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip); return 0; }
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 { m++ } if m >= limit { break } cpt = append(cpt, m) } fmt.Printf("Coprime triplets under %d:\n", limit) for i, t := range cpt { fmt.Printf("%2d ", t) if (i+1)%10 == 0 { fmt.Println() } } fmt.Printf("\n\nFound %d such numbers\n", len(cpt)) }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdio.h> int main() { int i, gprev = 0; int s[7] = {1, 2, 2, 3, 4, 4, 5}; for (i = 0; i < 7; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) printf("%d\n", i); prev = curr; } for (i = 0; i < 7; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) printf("%d\n", i); gprev = curr; } return 0; }
package main import "fmt" func main() { s := []int{1, 2, 2, 3, 4, 4, 5} for i := 0; i < len(s); i++ { curr := s[i] var prev int if i > 0 && curr == prev { fmt.Println(i) } prev = curr } var prev int for i := 0; i < len(s); i++ { curr := s[i] if i > 0 && curr == prev { fmt.Println(i) } prev = curr } }
Translate this program into Go but keep the logic exactly as in C.
#include <curl/curl.h> #include <string.h> #include <stdio.h> size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){ return fwrite(ptr,size,nmeb,stream); } size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){ return fread(ptr,size,nmeb,stream); } void callSOAP(char* URL, char * inFile, char * outFile) { FILE * rfp = fopen(inFile, "r"); if(!rfp) perror("Read File Open:"); FILE * wfp = fopen(outFile, "w+"); if(!wfp) perror("Write File Open:"); struct curl_slist *header = NULL; header = curl_slist_append (header, "Content-Type:text/xml"); header = curl_slist_append (header, "SOAPAction: rsc"); header = curl_slist_append (header, "Transfer-Encoding: chunked"); header = curl_slist_append (header, "Expect:"); CURL *curl; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, URL); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data); curl_easy_setopt(curl, CURLOPT_READDATA, rfp); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1); curl_easy_setopt(curl, CURLOPT_VERBOSE,1L); curl_easy_perform(curl); curl_easy_cleanup(curl); } } int main(int argC,char* argV[]) { if(argC!=4) printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]); else callSOAP(argV[1],argV[2],argV[3]); return 0; }
package main import ( "fmt" "github.com/tiaguinho/gosoap" "log" ) type CheckVatResponse struct { CountryCode string `xml:"countryCode"` VatNumber string `xml:"vatNumber"` RequestDate string `xml:"requestDate"` Valid string `xml:"valid"` Name string `xml:"name"` Address string `xml:"address"` } var ( rv CheckVatResponse ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { soap, err := gosoap.SoapClient("http: params := gosoap.Params{ "vatNumber": "6388047V", "countryCode": "IE", } err = soap.Call("checkVat", params) check(err) err = soap.Unmarshal(&rv) check(err) fmt.Println("Country Code  : ", rv.CountryCode) fmt.Println("Vat Number  : ", rv.VatNumber) fmt.Println("Request Date  : ", rv.RequestDate) fmt.Println("Valid  : ", rv.Valid) fmt.Println("Name  : ", rv.Name) fmt.Println("Address  : ", rv.Address) }
Change the programming language of this snippet from C to Go without modifying what it does.
#include<stdio.h> #define Hi printf("Hi There."); #define start int main(){ #define end return 0;} start Hi #warning "Don't you have anything better to do ?" #ifdef __unix__ #warning "What are you doing still working on Unix ?" printf("\nThis is an Unix system."); #elif _WIN32 #warning "You couldn't afford a 64 bit ?" printf("\nThis is a 32 bit Windows system."); #elif _WIN64 #warning "You couldn't afford an Apple ?" printf("\nThis is a 64 bit Windows system."); #endif end
Transform the following C implementation into Go, maintaining the same output and logic.
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } #define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) ) inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); } int main() { int32_t n; int i; for (i = 0, n = 1; ; i++, n *= 42) { printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n, n, msb32(n), msb32_idx(n), lsb32(n), lsb32_idx(n)); if (n >= INT32_MAX / 42) break; } return 0; }
package main import ( "fmt" "math/big" ) const ( mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota mask1, bit1 mask2, bit2 mask3, bit3 mask4, bit4 mask5, bit5 ) func rupb(x uint64) (out int) { if x == 0 { return -1 } if x&^mask5 != 0 { x >>= bit5 out |= bit5 } if x&^mask4 != 0 { x >>= bit4 out |= bit4 } if x&^mask3 != 0 { x >>= bit3 out |= bit3 } if x&^mask2 != 0 { x >>= bit2 out |= bit2 } if x&^mask1 != 0 { x >>= bit1 out |= bit1 } if x&^mask0 != 0 { out |= bit0 } return } func rlwb(x uint64) (out int) { if x == 0 { return 0 } if x&mask5 == 0 { x >>= bit5 out |= bit5 } if x&mask4 == 0 { x >>= bit4 out |= bit4 } if x&mask3 == 0 { x >>= bit3 out |= bit3 } if x&mask2 == 0 { x >>= bit2 out |= bit2 } if x&mask1 == 0 { x >>= bit1 out |= bit1 } if x&mask0 == 0 { out |= bit0 } return } func rupbBig(x *big.Int) int { return x.BitLen() - 1 } func rlwbBig(x *big.Int) int { if x.BitLen() < 2 { return 0 } bit := uint(1) mask := big.NewInt(1) var ms []*big.Int var y, z big.Int for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 { ms = append(ms, mask) mask = new(big.Int).Or(mask, &z) bit <<= 1 } out := bit for i := len(ms) - 1; i >= 0; i-- { bit >>= 1 if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 { out |= bit } } return int(out) } func main() { show() showBig() } func show() { fmt.Println("uint64:") fmt.Println("power number rupb rlwb") const base = 42 n := uint64(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n)) n *= base } } func showBig() { fmt.Println("\nbig numbers:") fmt.Println(" power number rupb rlwb") base := big.NewInt(1302) n := big.NewInt(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n)) n.Mul(n, base) } }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } #define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) ) inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); } int main() { int32_t n; int i; for (i = 0, n = 1; ; i++, n *= 42) { printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n, n, msb32(n), msb32_idx(n), lsb32(n), lsb32_idx(n)); if (n >= INT32_MAX / 42) break; } return 0; }
package main import ( "fmt" "math/big" ) const ( mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota mask1, bit1 mask2, bit2 mask3, bit3 mask4, bit4 mask5, bit5 ) func rupb(x uint64) (out int) { if x == 0 { return -1 } if x&^mask5 != 0 { x >>= bit5 out |= bit5 } if x&^mask4 != 0 { x >>= bit4 out |= bit4 } if x&^mask3 != 0 { x >>= bit3 out |= bit3 } if x&^mask2 != 0 { x >>= bit2 out |= bit2 } if x&^mask1 != 0 { x >>= bit1 out |= bit1 } if x&^mask0 != 0 { out |= bit0 } return } func rlwb(x uint64) (out int) { if x == 0 { return 0 } if x&mask5 == 0 { x >>= bit5 out |= bit5 } if x&mask4 == 0 { x >>= bit4 out |= bit4 } if x&mask3 == 0 { x >>= bit3 out |= bit3 } if x&mask2 == 0 { x >>= bit2 out |= bit2 } if x&mask1 == 0 { x >>= bit1 out |= bit1 } if x&mask0 == 0 { out |= bit0 } return } func rupbBig(x *big.Int) int { return x.BitLen() - 1 } func rlwbBig(x *big.Int) int { if x.BitLen() < 2 { return 0 } bit := uint(1) mask := big.NewInt(1) var ms []*big.Int var y, z big.Int for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 { ms = append(ms, mask) mask = new(big.Int).Or(mask, &z) bit <<= 1 } out := bit for i := len(ms) - 1; i >= 0; i-- { bit >>= 1 if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 { out |= bit } } return int(out) } func main() { show() showBig() } func show() { fmt.Println("uint64:") fmt.Println("power number rupb rlwb") const base = 42 n := uint64(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n)) n *= base } } func showBig() { fmt.Println("\nbig numbers:") fmt.Println(" power number rupb rlwb") base := big.NewInt(1302) n := big.NewInt(1) for i := 0; i < 12; i++ { fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n)) n.Mul(n, base) } }
Write the same code in Go as shown below in C.
#include <stdio.h> int riseEqFall(int num) { int rdigit = num % 10; int netHeight = 0; while (num /= 10) { netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit); rdigit = num % 10; } return netHeight == 0; } int nextNum() { static int num = 0; do {num++;} while (!riseEqFall(num)); return num; } int main(void) { int total, num; printf("The first 200 numbers are: \n"); for (total = 0; total < 200; total++) printf("%d ", nextNum()); printf("\n\nThe 10,000,000th number is: "); for (; total < 10000000; total++) num = nextNum(); printf("%d\n", num); return 0; }
package main import "fmt" func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { falls = falls + 1 } } prev = d n /= 10 } return rises == falls } func main() { fmt.Println("The first 200 numbers in the sequence are:") count := 0 n := 1 for { if risesEqualsFalls(n) { count++ if count <= 200 { fmt.Printf("%3d ", n) if count%20 == 0 { fmt.Println() } } if count == 1e7 { fmt.Println("\nThe 10 millionth number in the sequence is ", n) break } } n++ } }
Maintain the same structure and functionality when rewriting this code in Go.
#include<conio.h> #include<dos.h> char *strings[] = {"The cursor will move one position to the left", "The cursor will move one position to the right", "The cursor will move vetically up one line", "The cursor will move vertically down one line", "The cursor will move to the beginning of the line", "The cursor will move to the end of the line", "The cursor will move to the top left corner of the screen", "The cursor will move to the bottom right corner of the screen"}; int main() { int i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; clrscr(); cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue."); getch(); for(i=0;i<8;i++) { clrscr(); gotoxy(5,MAXROW/2); cprintf("%s",strings[i]); getch(); switch(i){ case 0:gotoxy(wherex()-1,wherey()); break; case 1:gotoxy(wherex()+1,wherey()); break; case 2:gotoxy(wherex(),wherey()-1); break; case 3:gotoxy(wherex(),wherey()+1); break; case 4:for(j=0;j<strlen(strings[i]);j++){ gotoxy(wherex()-1,wherey()); delay(100); } break; case 5:gotoxy(wherex()-strlen(strings[i]),wherey()); for(j=0;j<strlen(strings[i]);j++){ gotoxy(wherex()+1,wherey()); delay(100); } break; case 6:while(wherex()!=1) { gotoxy(wherex()-1,wherey()); delay(100); } while(wherey()!=1) { gotoxy(wherex(),wherey()-1); delay(100); } break; case 7:while(wherex()!=MAXCOL) { gotoxy(wherex()+1,wherey()); delay(100); } while(wherey()!=MAXROW) { gotoxy(wherex(),wherey()+1); delay(100); } break; }; getch(); } clrscr(); cprintf("End of demonstration."); getch(); return 0; }
package main import ( "fmt" "time" "os" "os/exec" "strconv" ) func main() { tput("clear") tput("cup", "6", "3") time.Sleep(1 * time.Second) tput("cub1") time.Sleep(1 * time.Second) tput("cuf1") time.Sleep(1 * time.Second) tput("cuu1") time.Sleep(1 * time.Second) tput("cud", "1") time.Sleep(1 * time.Second) tput("cr") time.Sleep(1 * time.Second) var h, w int cmd := exec.Command("stty", "size") cmd.Stdin = os.Stdin d, _ := cmd.Output() fmt.Sscan(string(d), &h, &w) tput("hpa", strconv.Itoa(w-1)) time.Sleep(2 * time.Second) tput("home") time.Sleep(2 * time.Second) tput("cup", strconv.Itoa(h-1), strconv.Itoa(w-1)) time.Sleep(3 * time.Second) } func tput(args ...string) error { cmd := exec.Command("tput", args...) cmd.Stdout = os.Stdout return cmd.Run() }
Generate a Go translation of this C snippet without changing its computational steps.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #define VECSZ 100 #define STATESZ 64 typedef float floating_pt; #define EXP expf #define SQRT sqrtf static floating_pt randnum (void) { return (floating_pt) ((double) (random () & 2147483647) / 2147483648.0); } static void shuffle (uint8_t vec[], size_t i, size_t n) { for (size_t j = 0; j != n; j += 1) { size_t k = i + j + (random () % (n - j)); uint8_t xi = vec[i]; uint8_t xk = vec[k]; vec[i] = xk; vec[k] = xi; } } static void init_s (uint8_t vec[VECSZ]) { for (uint8_t j = 0; j != VECSZ; j += 1) vec[j] = j; shuffle (vec, 1, VECSZ - 1); } static inline void add_neighbor (uint8_t neigh[8], unsigned int *neigh_size, uint8_t neighbor) { if (neighbor != 0) { neigh[*neigh_size] = neighbor; *neigh_size += 1; } } static void neighborhood (uint8_t neigh[8], unsigned int *neigh_size, uint8_t city) { const uint8_t i = city / 10; const uint8_t j = city % 10; uint8_t c0 = 0; uint8_t c1 = 0; uint8_t c2 = 0; uint8_t c3 = 0; uint8_t c4 = 0; uint8_t c5 = 0; uint8_t c6 = 0; uint8_t c7 = 0; if (i < 9) { c0 = (10 * (i + 1)) + j; if (j < 9) c1 = (10 * (i + 1)) + (j + 1); if (0 < j) c2 = (10 * (i + 1)) + (j - 1); } if (0 < i) { c3 = (10 * (i - 1)) + j; if (j < 9) c4 = (10 * (i - 1)) + (j + 1); if (0 < j) c5 = (10 * (i - 1)) + (j - 1); } if (j < 9) c6 = (10 * i) + (j + 1); if (0 < j) c7 = (10 * i) + (j - 1); *neigh_size = 0; add_neighbor (neigh, neigh_size, c0); add_neighbor (neigh, neigh_size, c1); add_neighbor (neigh, neigh_size, c2); add_neighbor (neigh, neigh_size, c3); add_neighbor (neigh, neigh_size, c4); add_neighbor (neigh, neigh_size, c5); add_neighbor (neigh, neigh_size, c6); add_neighbor (neigh, neigh_size, c7); } static floating_pt distance (uint8_t m, uint8_t n) { const uint8_t im = m / 10; const uint8_t jm = m % 10; const uint8_t in = n / 10; const uint8_t jn = n % 10; const int di = (int) im - (int) in; const int dj = (int) jm - (int) jn; return SQRT ((di * di) + (dj * dj)); } static floating_pt path_length (uint8_t vec[VECSZ]) { floating_pt len = distance (vec[0], vec[VECSZ - 1]); for (size_t j = 0; j != VECSZ - 1; j += 1) len += distance (vec[j], vec[j + 1]); return len; } static void swap_s_elements (uint8_t vec[], uint8_t u, uint8_t v) { size_t j = 1; size_t iu = 0; size_t iv = 0; while (iu == 0 || iv == 0) { if (vec[j] == u) iu = j; else if (vec[j] == v) iv = j; j += 1; } vec[iu] = v; vec[iv] = u; } static void update_s (uint8_t vec[]) { const uint8_t u = 1 + (random () % (VECSZ - 1)); uint8_t neighbors[8]; unsigned int num_neighbors; neighborhood (neighbors, &num_neighbors, u); const uint8_t v = neighbors[random () % num_neighbors]; swap_s_elements (vec, u, v); } static inline void copy_s (uint8_t dst[VECSZ], uint8_t src[VECSZ]) { memcpy (dst, src, VECSZ * (sizeof src[0])); } static void trial_s (uint8_t trial[VECSZ], uint8_t vec[VECSZ]) { copy_s (trial, vec); update_s (trial); } static floating_pt temperature (floating_pt kT, unsigned int kmax, unsigned int k) { return kT * (1 - ((floating_pt) k / (floating_pt) kmax)); } static floating_pt probability (floating_pt delta_E, floating_pt T) { floating_pt prob; if (delta_E < 0) prob = 1; else if (T == 0) prob = 0; else prob = EXP (-(delta_E / T)); return prob; } static void show (unsigned int k, floating_pt T, floating_pt E) { printf (" %7u %7.1f %13.5f\n", k, (double) T, (double) E); } static void simulate_annealing (floating_pt kT, unsigned int kmax, uint8_t s[VECSZ]) { uint8_t trial[VECSZ]; unsigned int kshow = kmax / 10; floating_pt E = path_length (s); for (unsigned int k = 0; k != kmax + 1; k += 1) { const floating_pt T = temperature (kT, kmax, k); if (k % kshow == 0) show (k, T, E); trial_s (trial, s); const floating_pt E_trial = path_length (trial); const floating_pt delta_E = E_trial - E; const floating_pt P = probability (delta_E, T); if (P == 1 || randnum () <= P) { copy_s (s, trial); E = E_trial; } } } static void display_path (uint8_t vec[VECSZ]) { for (size_t i = 0; i != VECSZ; i += 1) { const uint8_t x = vec[i]; printf ("%2u ->", (unsigned int) x); if ((i % 8) == 7) printf ("\n"); else printf (" "); } printf ("%2u\n", vec[0]); } int main (void) { char state[STATESZ]; uint32_t seed[1]; int status = getentropy (&seed[0], sizeof seed[0]); if (status < 0) seed[0] = 1; initstate (seed[0], state, STATESZ); floating_pt kT = 1.0; unsigned int kmax = 1000000; uint8_t s[VECSZ]; init_s (s); printf ("\n"); printf (" kT: %f\n", (double) kT); printf (" kmax: %u\n", kmax); printf ("\n"); printf (" k T E(s)\n"); printf (" -----------------------------\n"); simulate_annealing (kT, kmax, s); printf ("\n"); display_path (s); printf ("\n"); printf ("Final E(s): %.5f\n", (double) path_length (s)); printf ("\n"); return 0; }
package main import ( "fmt" "math" "math/rand" "time" ) var ( dists = calcDists() dirs = [8]int{1, -1, 10, -10, 9, 11, -11, -9} ) func calcDists() []float64 { dists := make([]float64, 10000) for i := 0; i < 10000; i++ { ab, cd := math.Floor(float64(i)/100), float64(i%100) a, b := math.Floor(ab/10), float64(int(ab)%10) c, d := math.Floor(cd/10), float64(int(cd)%10) dists[i] = math.Hypot(a-c, b-d) } return dists } func dist(ci, cj int) float64 { return dists[cj*100+ci] } func Es(path []int) float64 { d := 0.0 for i := 0; i < len(path)-1; i++ { d += dist(path[i], path[i+1]) } return d } func T(k, kmax, kT int) float64 { return (1 - float64(k)/float64(kmax)) * float64(kT) } func dE(s []int, u, v int) float64 { su, sv := s[u], s[v] a, b, c, d := dist(s[u-1], su), dist(s[u+1], su), dist(s[v-1], sv), dist(s[v+1], sv) na, nb, nc, nd := dist(s[u-1], sv), dist(s[u+1], sv), dist(s[v-1], su), dist(s[v+1], su) if v == u+1 { return (na + nd) - (a + d) } else if u == v+1 { return (nc + nb) - (c + b) } else { return (na + nb + nc + nd) - (a + b + c + d) } } func P(deltaE float64, k, kmax, kT int) float64 { return math.Exp(-deltaE / T(k, kmax, kT)) } func sa(kmax, kT int) { rand.Seed(time.Now().UnixNano()) temp := make([]int, 99) for i := 0; i < 99; i++ { temp[i] = i + 1 } rand.Shuffle(len(temp), func(i, j int) { temp[i], temp[j] = temp[j], temp[i] }) s := make([]int, 101) copy(s[1:], temp) fmt.Println("kT =", kT) fmt.Printf("E(s0) %f\n\n", Es(s)) Emin := Es(s) for k := 0; k <= kmax; k++ { if k%(kmax/10) == 0 { fmt.Printf("k:%10d T: %8.4f Es: %8.4f\n", k, T(k, kmax, kT), Es(s)) } u := 1 + rand.Intn(99) cv := s[u] + dirs[rand.Intn(8)] if cv <= 0 || cv >= 100 { continue } if dist(s[u], cv) > 5 { continue } v := s[cv] deltae := dE(s, u, v) if deltae < 0 || P(deltae, k, kmax, kT) >= rand.Float64() { s[u], s[v] = s[v], s[u] Emin += deltae } } fmt.Printf("\nE(s_final) %f\n", Emin) fmt.Println("Path:") for i := 0; i < len(s); i++ { if i > 0 && i%10 == 0 { fmt.Println() } fmt.Printf("%4d", s[i]) } fmt.Println() } func main() { sa(1e6, 1) }
Ensure the translated Go code behaves exactly like the original C snippet.
#include<stdio.h> #define start main() int start { printf("Hello World !"); return 0; }
package main import "fmt" var count = 0 func foo() { fmt.Println("foo called") } func init() { fmt.Println("first init called") foo() } func init() { fmt.Println("second init called") main() } func main() { count++ fmt.Println("main called when count is", count) }
Write a version of this C function in Go with identical behavior.
#include<stdio.h> #define start main() int start { printf("Hello World !"); return 0; }
package main import "fmt" var count = 0 func foo() { fmt.Println("foo called") } func init() { fmt.Println("first init called") foo() } func init() { fmt.Println("second init called") main() } func main() { count++ fmt.Println("main called when count is", count) }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
#include<stdio.h> #include<stdlib.h> int isprime( int p ) { int i; if(p==2) return 1; if(!(p%2)) return 0; for(i=3; i*i<=p; i+=2) { if(!(p%i)) return 0; } return 1; } int main( void ) { int p; long int s = 2; for(p=3;p<2000000;p+=2) { if(isprime(p)) s+=p; } printf( "%ld\n", s ); return 0; }
package main import ( "fmt" "rcu" ) func main() { sum := 0 for _, p := range rcu.Primes(2e6 - 1) { sum += p } fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum)) }
Transform the following C implementation into Go, maintaining the same output and logic.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #define pi M_PI typedef struct{ double x,y; }point; void kochCurve(point p1,point p2,int times){ point p3,p4,p5; double theta = pi/3; if(times>0){ p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3}; p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3}; p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)}; kochCurve(p1,p3,times-1); kochCurve(p3,p4,times-1); kochCurve(p4,p5,times-1); kochCurve(p5,p2,times-1); } else{ line(p1.x,p1.y,p2.x,p2.y); } } int main(int argC, char** argV) { int w,h,r; point p1,p2; if(argC!=4){ printf("Usage : %s <window width> <window height> <recursion level>",argV[0]); } else{ w = atoi(argV[1]); h = atoi(argV[2]); r = atoi(argV[3]); initwindow(w,h,"Koch Curve"); p1 = (point){10,h-10}; p2 = (point){w-10,h-10}; kochCurve(p1,p2,r); getch(); closegraph(); } return 0; }
package main import ( "github.com/fogleman/gg" "math" ) var dc = gg.NewContext(512, 512) func koch(x1, y1, x2, y2 float64, iter int) { angle := math.Pi / 3 x3 := (x1*2 + x2) / 3 y3 := (y1*2 + y2) / 3 x4 := (x1 + x2*2) / 3 y4 := (y1 + y2*2) / 3 x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle) y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle) if iter > 0 { iter-- koch(x1, y1, x3, y3, iter) koch(x3, y3, x5, y5, iter) koch(x5, y5, x4, y4, iter) koch(x4, y4, x2, y2, iter) } else { dc.LineTo(x1, y1) dc.LineTo(x3, y3) dc.LineTo(x5, y5) dc.LineTo(x4, y4) dc.LineTo(x2, y2) } } func main() { dc.SetRGB(1, 1, 1) dc.Clear() koch(100, 100, 400, 400, 4) dc.SetRGB(0, 0, 1) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("koch.png") }
Port the provided C code into Go while preserving the original functionality.
#include<graphics.h> #include<stdlib.h> #include<time.h> int main() { srand(time(NULL)); initwindow(640,480,"Yellow Random Pixel"); putpixel(rand()%640,rand()%480,YELLOW); getch(); return 0; }
package main import ( "fmt" "image" "image/color" "image/draw" "math/rand" "time" ) func main() { rect := image.Rect(0, 0, 640, 480) img := image.NewRGBA(rect) blue := color.RGBA{0, 0, 255, 255} draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src) yellow := color.RGBA{255, 255, 0, 255} width := img.Bounds().Dx() height := img.Bounds().Dy() rand.Seed(time.Now().UnixNano()) x := rand.Intn(width) y := rand.Intn(height) img.Set(x, y, yellow) cmap := map[color.Color]string{blue: "blue", yellow: "yellow"} for i := 0; i < width; i++ { for j := 0; j < height; j++ { c := img.At(i, j) if cmap[c] == "yellow" { fmt.Printf("The color of the pixel at (%d, %d) is yellow\n", i, j) } } } }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> char vowels[] = {'a','e','i','o','u','\n'}; int len(char * str) { int i = 0; while (str[i] != '\n') i++; return i; } int isvowel(char c){ int b = 0; int v = len(vowels); for(int i = 0; i < v;i++) { if(c == vowels[i]) { b = 1; break; } } return b; } int isletter(char c){ return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')); } int isconsonant(char c){ return isletter(c) && !isvowel(c); } int cVowels(char * str) { int i = 0; int count = 0; while (str[i] != '\n') { if (isvowel(str[i])) { count++;; } i++; } return count; } int cConsonants(char * str ) { int i = 0; int count = 0; while (str[i] != '\n') { if (isconsonant(str[i])) { count++; } i++; } return count; } int main() { char buff[] = "This is 1 string\n"; printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff); char buff2[] = "This is a second string\n"; printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2); printf("a: %d\n", isvowel('a')); printf("b: %d\n", isvowel('b')); printf("Z: %d\n", isconsonant('Z')); printf("1: %d\n", isletter('1')); }
package main import ( "fmt" "strings" ) func main() { const ( vowels = "aeiou" consonants = "bcdfghjklmnpqrstvwxyz" ) strs := []string{ "Forever Go programming language", "Now is the time for all good men to come to the aid of their country.", } for _, str := range strs { fmt.Println(str) str = strings.ToLower(str) vc, cc := 0, 0 vmap := make(map[rune]bool) cmap := make(map[rune]bool) for _, c := range str { if strings.ContainsRune(vowels, c) { vc++ vmap[c] = true } else if strings.ContainsRune(consonants, c) { cc++ cmap[c] = true } } fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc) fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap)) } }
Port the following code from C to Go with equivalent syntax and logic.
#include <stdio.h> char vowels[] = {'a','e','i','o','u','\n'}; int len(char * str) { int i = 0; while (str[i] != '\n') i++; return i; } int isvowel(char c){ int b = 0; int v = len(vowels); for(int i = 0; i < v;i++) { if(c == vowels[i]) { b = 1; break; } } return b; } int isletter(char c){ return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')); } int isconsonant(char c){ return isletter(c) && !isvowel(c); } int cVowels(char * str) { int i = 0; int count = 0; while (str[i] != '\n') { if (isvowel(str[i])) { count++;; } i++; } return count; } int cConsonants(char * str ) { int i = 0; int count = 0; while (str[i] != '\n') { if (isconsonant(str[i])) { count++; } i++; } return count; } int main() { char buff[] = "This is 1 string\n"; printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff); char buff2[] = "This is a second string\n"; printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2); printf("a: %d\n", isvowel('a')); printf("b: %d\n", isvowel('b')); printf("Z: %d\n", isconsonant('Z')); printf("1: %d\n", isletter('1')); }
package main import ( "fmt" "strings" ) func main() { const ( vowels = "aeiou" consonants = "bcdfghjklmnpqrstvwxyz" ) strs := []string{ "Forever Go programming language", "Now is the time for all good men to come to the aid of their country.", } for _, str := range strs { fmt.Println(str) str = strings.ToLower(str) vc, cc := 0, 0 vmap := make(map[rune]bool) cmap := make(map[rune]bool) for _, c := range str { if strings.ContainsRune(vowels, c) { vc++ vmap[c] = true } else if strings.ContainsRune(consonants, c) { cc++ cmap[c] = true } } fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc) fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap)) } }
Transform the following C implementation into Go, maintaining the same output and logic.
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type TokenType int const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEql tkNeq tkAssign tkAnd tkOr tkIf tkElse tkWhile tkPrint tkPutc tkLparen tkRparen tkLbrace tkRbrace tkSemi tkComma tkIdent tkInteger tkString ) 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 tokS struct { tok TokenType errLn int errCol int text string } type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { text string enumText string tok TokenType rightAssociative bool isBinary bool isUnary bool precedence int nodeType NodeType } var atrs = []atr{ {"EOI", "End_of_input", tkEOI, false, false, false, -1, -1}, {"*", "Op_multiply", tkMul, false, true, false, 13, ndMul}, {"/", "Op_divide", tkDiv, false, true, false, 13, ndDiv}, {"%", "Op_mod", tkMod, false, true, false, 13, ndMod}, {"+", "Op_add", tkAdd, false, true, false, 12, ndAdd}, {"-", "Op_subtract", tkSub, false, true, false, 12, ndSub}, {"-", "Op_negate", tkNegate, false, false, true, 14, ndNegate}, {"!", "Op_not", tkNot, false, false, true, 14, ndNot}, {"<", "Op_less", tkLss, false, true, false, 10, ndLss}, {"<=", "Op_lessequal", tkLeq, false, true, false, 10, ndLeq}, {">", "Op_greater", tkGtr, false, true, false, 10, ndGtr}, {">=", "Op_greaterequal", tkGeq, false, true, false, 10, ndGeq}, {"==", "Op_equal", tkEql, false, true, false, 9, ndEql}, {"!=", "Op_notequal", tkNeq, false, true, false, 9, ndNeq}, {"=", "Op_assign", tkAssign, false, false, false, -1, ndAssign}, {"&&", "Op_and", tkAnd, false, true, false, 5, ndAnd}, {"||", "Op_or", tkOr, false, true, false, 4, ndOr}, {"if", "Keyword_if", tkIf, false, false, false, -1, ndIf}, {"else", "Keyword_else", tkElse, false, false, false, -1, -1}, {"while", "Keyword_while", tkWhile, false, false, false, -1, ndWhile}, {"print", "Keyword_print", tkPrint, false, false, false, -1, -1}, {"putc", "Keyword_putc", tkPutc, false, false, false, -1, -1}, {"(", "LeftParen", tkLparen, false, false, false, -1, -1}, {")", "RightParen", tkRparen, false, false, false, -1, -1}, {"{", "LeftBrace", tkLbrace, false, false, false, -1, -1}, {"}", "RightBrace", tkRbrace, false, false, false, -1, -1}, {";", "Semicolon", tkSemi, false, false, false, -1, -1}, {",", "Comma", tkComma, false, false, false, -1, -1}, {"Ident", "Identifier", tkIdent, false, false, false, -1, ndIdent}, {"Integer literal", "Integer", tkInteger, false, false, false, -1, ndInteger}, {"String literal", "String", tkString, false, false, false, -1, ndString}, } var displayNodes = []string{ "Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or", } var ( err error token tokS scanner *bufio.Scanner ) func reportError(errLine, errCol int, msg string) { log.Fatalf("(%d, %d) error : %s\n", errLine, errCol, msg) } func check(err error) { if err != nil { log.Fatal(err) } } func getEum(name string) TokenType { for _, atr := range atrs { if atr.enumText == name { return atr.tok } } reportError(0, 0, fmt.Sprintf("Unknown token %s\n", name)) return tkEOI } func getTok() tokS { tok := tokS{} if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") fields := strings.Fields(line) tok.errLn, err = strconv.Atoi(fields[0]) check(err) tok.errCol, err = strconv.Atoi(fields[1]) check(err) tok.tok = getEum(fields[2]) le := len(fields) if le == 4 { tok.text = fields[3] } else if le > 4 { idx := strings.Index(line, `"`) tok.text = line[idx:] } } check(scanner.Err()) return tok } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func expect(msg string, s TokenType) { if token.tok == s { token = getTok() return } reportError(token.errLn, token.errCol, fmt.Sprintf("%s: Expecting '%s', found '%s'\n", msg, atrs[s].text, atrs[token.tok].text)) } func expr(p int) *Tree { var x, node *Tree switch token.tok { case tkLparen: x = parenExpr() case tkSub, tkAdd: op := token.tok token = getTok() node = expr(atrs[tkNegate].precedence) if op == tkSub { x = makeNode(ndNegate, node, nil) } else { x = node } case tkNot: token = getTok() x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil) case tkIdent: x = makeLeaf(ndIdent, token.text) token = getTok() case tkInteger: x = makeLeaf(ndInteger, token.text) token = getTok() default: reportError(token.errLn, token.errCol, fmt.Sprintf("Expecting a primary, found: %s\n", atrs[token.tok].text)) } for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p { op := token.tok token = getTok() q := atrs[op].precedence if !atrs[op].rightAssociative { q++ } node = expr(q) x = makeNode(atrs[op].nodeType, x, node) } return x } func parenExpr() *Tree { expect("parenExpr", tkLparen) t := expr(0) expect("parenExpr", tkRparen) return t } func stmt() *Tree { var t, v, e, s, s2 *Tree switch token.tok { case tkIf: token = getTok() e = parenExpr() s = stmt() s2 = nil if token.tok == tkElse { token = getTok() s2 = stmt() } t = makeNode(ndIf, e, makeNode(ndIf, s, s2)) case tkPutc: token = getTok() e = parenExpr() t = makeNode(ndPrtc, e, nil) expect("Putc", tkSemi) case tkPrint: token = getTok() for expect("Print", tkLparen); ; expect("Print", tkComma) { if token.tok == tkString { e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil) token = getTok() } else { e = makeNode(ndPrti, expr(0), nil) } t = makeNode(ndSequence, t, e) if token.tok != tkComma { break } } expect("Print", tkRparen) expect("Print", tkSemi) case tkSemi: token = getTok() case tkIdent: v = makeLeaf(ndIdent, token.text) token = getTok() expect("assign", tkAssign) e = expr(0) t = makeNode(ndAssign, v, e) expect("assign", tkSemi) case tkWhile: token = getTok() e = parenExpr() s = stmt() t = makeNode(ndWhile, e, s) case tkLbrace: for expect("Lbrace", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; { t = makeNode(ndSequence, t, stmt()) } expect("Lbrace", tkRbrace) case tkEOI: default: reportError(token.errLn, token.errCol, fmt.Sprintf("expecting start of statement, found '%s'\n", atrs[token.tok].text)) } return t } func parse() *Tree { var t *Tree token = getTok() for { t = makeNode(ndSequence, t, stmt()) if t == nil || token.tok == tkEOI { break } } return t } func prtAst(t *Tree) { if t == nil { fmt.Print(";\n") } else { fmt.Printf("%-14s ", displayNodes[t.nodeType]) if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString { fmt.Printf("%s\n", t.value) } else { fmt.Println() prtAst(t.left) prtAst(t.right) } } } func main() { source, err := os.Open("source.txt") check(err) defer source.Close() scanner = bufio.NewScanner(source) prtAst(parse()) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type TokenType int const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEql tkNeq tkAssign tkAnd tkOr tkIf tkElse tkWhile tkPrint tkPutc tkLparen tkRparen tkLbrace tkRbrace tkSemi tkComma tkIdent tkInteger tkString ) 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 tokS struct { tok TokenType errLn int errCol int text string } type Tree struct { nodeType NodeType left *Tree right *Tree value string } type atr struct { text string enumText string tok TokenType rightAssociative bool isBinary bool isUnary bool precedence int nodeType NodeType } var atrs = []atr{ {"EOI", "End_of_input", tkEOI, false, false, false, -1, -1}, {"*", "Op_multiply", tkMul, false, true, false, 13, ndMul}, {"/", "Op_divide", tkDiv, false, true, false, 13, ndDiv}, {"%", "Op_mod", tkMod, false, true, false, 13, ndMod}, {"+", "Op_add", tkAdd, false, true, false, 12, ndAdd}, {"-", "Op_subtract", tkSub, false, true, false, 12, ndSub}, {"-", "Op_negate", tkNegate, false, false, true, 14, ndNegate}, {"!", "Op_not", tkNot, false, false, true, 14, ndNot}, {"<", "Op_less", tkLss, false, true, false, 10, ndLss}, {"<=", "Op_lessequal", tkLeq, false, true, false, 10, ndLeq}, {">", "Op_greater", tkGtr, false, true, false, 10, ndGtr}, {">=", "Op_greaterequal", tkGeq, false, true, false, 10, ndGeq}, {"==", "Op_equal", tkEql, false, true, false, 9, ndEql}, {"!=", "Op_notequal", tkNeq, false, true, false, 9, ndNeq}, {"=", "Op_assign", tkAssign, false, false, false, -1, ndAssign}, {"&&", "Op_and", tkAnd, false, true, false, 5, ndAnd}, {"||", "Op_or", tkOr, false, true, false, 4, ndOr}, {"if", "Keyword_if", tkIf, false, false, false, -1, ndIf}, {"else", "Keyword_else", tkElse, false, false, false, -1, -1}, {"while", "Keyword_while", tkWhile, false, false, false, -1, ndWhile}, {"print", "Keyword_print", tkPrint, false, false, false, -1, -1}, {"putc", "Keyword_putc", tkPutc, false, false, false, -1, -1}, {"(", "LeftParen", tkLparen, false, false, false, -1, -1}, {")", "RightParen", tkRparen, false, false, false, -1, -1}, {"{", "LeftBrace", tkLbrace, false, false, false, -1, -1}, {"}", "RightBrace", tkRbrace, false, false, false, -1, -1}, {";", "Semicolon", tkSemi, false, false, false, -1, -1}, {",", "Comma", tkComma, false, false, false, -1, -1}, {"Ident", "Identifier", tkIdent, false, false, false, -1, ndIdent}, {"Integer literal", "Integer", tkInteger, false, false, false, -1, ndInteger}, {"String literal", "String", tkString, false, false, false, -1, ndString}, } var displayNodes = []string{ "Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or", } var ( err error token tokS scanner *bufio.Scanner ) func reportError(errLine, errCol int, msg string) { log.Fatalf("(%d, %d) error : %s\n", errLine, errCol, msg) } func check(err error) { if err != nil { log.Fatal(err) } } func getEum(name string) TokenType { for _, atr := range atrs { if atr.enumText == name { return atr.tok } } reportError(0, 0, fmt.Sprintf("Unknown token %s\n", name)) return tkEOI } func getTok() tokS { tok := tokS{} if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") fields := strings.Fields(line) tok.errLn, err = strconv.Atoi(fields[0]) check(err) tok.errCol, err = strconv.Atoi(fields[1]) check(err) tok.tok = getEum(fields[2]) le := len(fields) if le == 4 { tok.text = fields[3] } else if le > 4 { idx := strings.Index(line, `"`) tok.text = line[idx:] } } check(scanner.Err()) return tok } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func expect(msg string, s TokenType) { if token.tok == s { token = getTok() return } reportError(token.errLn, token.errCol, fmt.Sprintf("%s: Expecting '%s', found '%s'\n", msg, atrs[s].text, atrs[token.tok].text)) } func expr(p int) *Tree { var x, node *Tree switch token.tok { case tkLparen: x = parenExpr() case tkSub, tkAdd: op := token.tok token = getTok() node = expr(atrs[tkNegate].precedence) if op == tkSub { x = makeNode(ndNegate, node, nil) } else { x = node } case tkNot: token = getTok() x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil) case tkIdent: x = makeLeaf(ndIdent, token.text) token = getTok() case tkInteger: x = makeLeaf(ndInteger, token.text) token = getTok() default: reportError(token.errLn, token.errCol, fmt.Sprintf("Expecting a primary, found: %s\n", atrs[token.tok].text)) } for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p { op := token.tok token = getTok() q := atrs[op].precedence if !atrs[op].rightAssociative { q++ } node = expr(q) x = makeNode(atrs[op].nodeType, x, node) } return x } func parenExpr() *Tree { expect("parenExpr", tkLparen) t := expr(0) expect("parenExpr", tkRparen) return t } func stmt() *Tree { var t, v, e, s, s2 *Tree switch token.tok { case tkIf: token = getTok() e = parenExpr() s = stmt() s2 = nil if token.tok == tkElse { token = getTok() s2 = stmt() } t = makeNode(ndIf, e, makeNode(ndIf, s, s2)) case tkPutc: token = getTok() e = parenExpr() t = makeNode(ndPrtc, e, nil) expect("Putc", tkSemi) case tkPrint: token = getTok() for expect("Print", tkLparen); ; expect("Print", tkComma) { if token.tok == tkString { e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil) token = getTok() } else { e = makeNode(ndPrti, expr(0), nil) } t = makeNode(ndSequence, t, e) if token.tok != tkComma { break } } expect("Print", tkRparen) expect("Print", tkSemi) case tkSemi: token = getTok() case tkIdent: v = makeLeaf(ndIdent, token.text) token = getTok() expect("assign", tkAssign) e = expr(0) t = makeNode(ndAssign, v, e) expect("assign", tkSemi) case tkWhile: token = getTok() e = parenExpr() s = stmt() t = makeNode(ndWhile, e, s) case tkLbrace: for expect("Lbrace", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; { t = makeNode(ndSequence, t, stmt()) } expect("Lbrace", tkRbrace) case tkEOI: default: reportError(token.errLn, token.errCol, fmt.Sprintf("expecting start of statement, found '%s'\n", atrs[token.tok].text)) } return t } func parse() *Tree { var t *Tree token = getTok() for { t = makeNode(ndSequence, t, stmt()) if t == nil || token.tok == tkEOI { break } } return t } func prtAst(t *Tree) { if t == nil { fmt.Print(";\n") } else { fmt.Printf("%-14s ", displayNodes[t.nodeType]) if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString { fmt.Printf("%s\n", t.value) } else { fmt.Println() prtAst(t.left) prtAst(t.right) } } } func main() { source, err := os.Open("source.txt") check(err) defer source.Close() scanner = bufio.NewScanner(source) prtAst(parse()) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include<graphics.h> int main() { initwindow(320,240,"Red Pixel"); putpixel(100,100,RED); getch(); return 0; }
package main import ( "fmt" "image" "image/color" "image/draw" ) func main() { rect := image.Rect(0, 0, 320, 240) img := image.NewRGBA(rect) green := color.RGBA{0, 255, 0, 255} draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src) red := color.RGBA{255, 0, 0, 255} img.Set(100, 100, red) cmap := map[color.Color]string{green: "green", red: "red"} c1 := img.At(0, 0) c2 := img.At(100, 100) fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.") fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.") }
Rewrite the snippet below in Go so it works the same as the original C code.
#include <stdio.h> #include <stdint.h> uint8_t prime(uint8_t n) { uint8_t f; if (n < 2) return 0; for (f = 2; f < n; f++) { if (n % f == 0) return 0; } return 1; } uint8_t digit_sum(uint8_t n, uint8_t base) { uint8_t s = 0; do {s += n % base;} while (n /= base); return s; } int main() { uint8_t n, s = 0; for (n = 0; n < 200; n++) { if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) { printf("%4d",n); if (++s>=10) { printf("\n"); s=0; } } } printf("\n"); return 0; }
package main import ( "fmt" "rcu" ) func main() { var numbers []int for i := 2; i < 200; i++ { bds := rcu.DigitSum(i, 2) if rcu.IsPrime(bds) { tds := rcu.DigitSum(i, 3) if rcu.IsPrime(tds) { numbers = append(numbers, i) } } } fmt.Println("Numbers < 200 whose binary and ternary digit sums are prime:") for i, n := range numbers { fmt.Printf("%4d", n) if (i+1)%14 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found\n", len(numbers)) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdint.h> uint8_t prime(uint8_t n) { uint8_t f; if (n < 2) return 0; for (f = 2; f < n; f++) { if (n % f == 0) return 0; } return 1; } uint8_t digit_sum(uint8_t n, uint8_t base) { uint8_t s = 0; do {s += n % base;} while (n /= base); return s; } int main() { uint8_t n, s = 0; for (n = 0; n < 200; n++) { if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) { printf("%4d",n); if (++s>=10) { printf("\n"); s=0; } } } printf("\n"); return 0; }
package main import ( "fmt" "rcu" ) func main() { var numbers []int for i := 2; i < 200; i++ { bds := rcu.DigitSum(i, 2) if rcu.IsPrime(bds) { tds := rcu.DigitSum(i, 3) if rcu.IsPrime(tds) { numbers = append(numbers, i) } } } fmt.Println("Numbers < 200 whose binary and ternary digit sums are prime:") for i, n := range numbers { fmt.Printf("%4d", n) if (i+1)%14 == 0 { fmt.Println() } } fmt.Printf("\n\n%d such numbers found\n", len(numbers)) }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 80 #define MIN_LENGTH 9 #define WORD_SIZE (MIN_LENGTH + 1) void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int word_compare(const void* p1, const void* p2) { return memcmp(p1, p2, WORD_SIZE); } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; FILE* in = fopen(filename, "r"); if (!in) { perror(filename); return EXIT_FAILURE; } char line[MAX_WORD_SIZE]; size_t size = 0, capacity = 1024; char* words = xmalloc(WORD_SIZE * capacity); while (fgets(line, sizeof(line), in)) { size_t len = strlen(line) - 1; if (len < MIN_LENGTH) continue; line[len] = '\0'; if (size == capacity) { capacity *= 2; words = xrealloc(words, WORD_SIZE * capacity); } memcpy(&words[size * WORD_SIZE], line, WORD_SIZE); ++size; } fclose(in); qsort(words, size, WORD_SIZE, word_compare); int count = 0; char prev_word[WORD_SIZE] = { 0 }; for (size_t i = 0; i + MIN_LENGTH <= size; ++i) { char word[WORD_SIZE] = { 0 }; for (size_t j = 0; j < MIN_LENGTH; ++j) word[j] = words[(i + j) * WORD_SIZE + j]; if (word_compare(word, prev_word) == 0) continue; if (bsearch(word, words, size, WORD_SIZE, word_compare)) printf("%2d. %s\n", ++count, word); memcpy(prev_word, word, WORD_SIZE); } free(words); return EXIT_SUCCESS; }
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" "unicode/utf8" ) func main() { wordList := "unixdict.txt" b, err := ioutil.ReadFile(wordList) if err != nil { log.Fatal("Error reading file") } bwords := bytes.Fields(b) var words []string for _, bword := range bwords { s := string(bword) if utf8.RuneCountInString(s) >= 9 { words = append(words, s) } } count := 0 var alreadyFound []string le := len(words) var sb strings.Builder for i := 0; i < le-9; i++ { sb.Reset() for j := i; j < i+9; j++ { sb.WriteByte(words[j][j-i]) } word := sb.String() ix := sort.SearchStrings(words, word) if ix < le && word == words[ix] { ix2 := sort.SearchStrings(alreadyFound, word) if ix2 == len(alreadyFound) { count++ fmt.Printf("%2d: %s\n", count, word) alreadyFound = append(alreadyFound, word) } } } }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> int divisible(int n) { int p = 1; int c, d; for (c=n; c; c /= 10) { d = c % 10; if (!d || n % d) return 0; p *= d; } return n % p; } int main() { int n, c=0; for (n=1; n<1000; n++) { if (divisible(n)) { printf("%5d", n); if (!(++c % 10)) printf("\n"); } } printf("\n"); return 0; }
package main import ( "fmt" "rcu" ) func main() { var res []int for n := 1; n < 1000; n++ { digits := rcu.Digits(n, 10) var all = true for _, d := range digits { if d == 0 || n%d != 0 { all = false break } } if all { prod := 1 for _, d := range digits { prod *= d } if prod > 0 && n%prod != 0 { res = append(res, n) } } } fmt.Println("Numbers < 1000 divisible by their digits, but not by the product thereof:") for i, n := range res { fmt.Printf("%4d", n) if (i+1)%9 == 0 { fmt.Println() } } fmt.Printf("\n%d such numbers found\n", len(res)) }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
Ensure the translated Go code behaves exactly like the original C snippet.
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
package main import "fmt" func xor(a, b byte) byte { return a&(^b) | b&(^a) } func ha(a, b byte) (s, c byte) { return xor(a, b), a & b } func fa(a, b, c0 byte) (s, c1 byte) { sa, ca := ha(a, c0) s, cb := ha(sa, b) c1 = ca | cb return } func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) { s0, c0 := fa(a0, b0, 0) s1, c1 := fa(a1, b1, c0) s2, c2 := fa(a2, b2, c1) s3, v = fa(a3, b3, c2) return } func main() { fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1)) }
Change the following C code into Go without altering its purpose.
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** oddMagicSquare(int n) { if (n < 3 || n % 2 == 0) return NULL; int value = 0; int squareSize = n * n; int c = n / 2, r = 0,i; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); while (++value <= squareSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } int** singlyEvenMagicSquare(int n) { if (n < 6 || (n - 2) % 4 != 0) return NULL; int size = n * n; int halfN = n / 2; int subGridSize = size / 4, i; int** subGrid = oddMagicSquare(halfN); int gridFactors[] = {0, 2, 3, 1}; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int grid = (r / halfN) * 2 + (c / halfN); result[r][c] = subGrid[r % halfN][c % halfN]; result[r][c] += gridFactors[grid] * subGridSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } 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; for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2); } 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(singlyEvenMagicSquare(n),n); } return 0; }
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for value <= gridSize { result[r][c] = value if r == 0 { if c == n-1 { r++ } else { r = n - 1 c++ } } else if c == n-1 { r-- c = 0 } else if result[r-1][c+1] == 0 { r-- c++ } else { r++ } value++ } return result, nil } func magicSquareSinglyEven(n int) ([][]int, error) { if n < 6 || (n-2)%4 != 0 { return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2") } size := n * n halfN := n / 2 subSquareSize := size / 4 subSquare, err := magicSquareOdd(halfN) if err != nil { return nil, err } quadrantFactors := [4]int{0, 2, 3, 1} result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for r := 0; r < n; r++ { for c := 0; c < n; c++ { quadrant := r/halfN*2 + c/halfN result[r][c] = subSquare[r%halfN][c%halfN] result[r][c] += quadrantFactors[quadrant] * subSquareSize } } nColsLeft := halfN / 2 nColsRight := nColsLeft - 1 for r := 0; r < halfN; r++ { for c := 0; c < n; c++ { if c < nColsLeft || c >= n-nColsRight || (c == nColsLeft && r == nColsLeft) { if c == 0 && r == nColsLeft { continue } tmp := result[r][c] result[r][c] = result[r+halfN][c] result[r+halfN][c] = tmp } } } return result, nil } func main() { const n = 6 msse, err := magicSquareSinglyEven(n) if err != nil { log.Fatal(err) } for _, row := range msse { for _, x := range row { fmt.Printf("%2d ", x) } fmt.Println() } fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2) }
Generate a Go translation of this C snippet without changing its computational steps.
#include <stdio.h> #define sqr(x) ((x) * (x)) #define greet printf("Hello There!\n") int twice(int x) { return 2 * x; } int main(void) { int x; printf("This will demonstrate function and label scopes.\n"); printf("All output is happening through printf(), a function declared in the header stdio.h, which is external to this program.\n"); printf("Enter a number: "); if (scanf("%d", &x) != 1) return 0; switch (x % 2) { default: printf("Case labels in switch statements have scope local to the switch block.\n"); case 0: printf("You entered an even number.\n"); printf("Its square is %d, which was computed by a macro. It has global scope within the translation unit.\n", sqr(x)); break; case 1: printf("You entered an odd number.\n"); goto sayhello; jumpin: printf("2 times %d is %d, which was computed by a function defined in this file. It has global scope within the translation unit.\n", x, twice(x)); printf("Since you jumped in, you will now be greeted, again!\n"); sayhello: greet; if (x == -1) goto scram; break; } printf("We now come to goto, it's extremely powerful but it's also prone to misuse. Its use is discouraged and it wasn't even adopted by Java and later languages.\n"); if (x != -1) { x = -1; goto jumpin; } scram: printf("If you are trying to figure out what happened, you now understand goto.\n"); return 0; }
package main import ( "fmt" "runtime" "ex" ) func main() { f := func() { pc, _, _, _ := runtime.Caller(0) fmt.Println(runtime.FuncForPC(pc).Name(), "here!") } ex.X(f) }
Keep all operations the same but rewrite the snippet in Go.
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h> char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e'; pos[i] = i; } do{ kPos = rand()%8; rPos1 = rand()%8; rPos2 = rand()%8; }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); rank[pos[rPos1]] = 'R'; rank[pos[kPos]] = 'K'; rank[pos[rPos2]] = 'R'; swap(rPos1,7); swap(rPos2,6); swap(kPos,5); do{ bPos1 = rand()%5; bPos2 = rand()%5; }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); rank[pos[bPos1]] = 'B'; rank[pos[bPos2]] = 'B'; swap(bPos1,4); swap(bPos2,3); do{ qPos = rand()%3; nPos1 = rand()%3; }while(qPos==nPos1); rank[pos[qPos]] = 'Q'; rank[pos[nPos1]] = 'N'; for(i=0;i<8;i++) if(rank[i]=='e'){ rank[i] = 'N'; break; } } void printRank(){ int i; #ifdef _WIN32 printf("%s\n",rank); #else { setlocale(LC_ALL,""); printf("\n"); for(i=0;i<8;i++){ if(rank[i]=='K') printf("%lc",(wint_t)9812); else if(rank[i]=='Q') printf("%lc",(wint_t)9813); else if(rank[i]=='R') printf("%lc",(wint_t)9814); else if(rank[i]=='B') printf("%lc",(wint_t)9815); if(rank[i]=='N') printf("%lc",(wint_t)9816); } } #endif } int main() { int i; srand((unsigned)time(NULL)); for(i=0;i<9;i++){ generateFirstRank(); printRank(); } return 0; }
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn"} func (sym symbols) chess960(id int) string { var pos [8]rune q, r := id/4, id%4 pos[r*2+1] = sym.b q, r = q/4, q%4 pos[r*2] = sym.b q, r = q/6, q%6 for i := 0; ; i++ { if pos[i] != 0 { continue } if r == 0 { pos[i] = sym.q break } r-- } i := 0 for _, f := range krn[q] { for pos[i] != 0 { i++ } switch f { case 'k': pos[i] = sym.k case 'r': pos[i] = sym.r case 'n': pos[i] = sym.n } } return string(pos[:]) } func main() { fmt.Println(" ID Start position") for _, id := range []int{0, 518, 959} { fmt.Printf("%3d %s\n", id, A.chess960(id)) } fmt.Println("\nRandom") for i := 0; i < 5; i++ { fmt.Println(W.chess960(rand.Intn(960))) } }
Produce a functionally identical Go code for the snippet given in C.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
package main import "fmt" func main() { bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.`) } func bf(dLen int, is string) { ds := make([]byte, dLen) var dp int for ip := 0; ip < len(is); ip++ { switch is[ip] { case '>': dp++ case '<': dp-- case '+': ds[dp]++ case '-': ds[dp]-- case '.': fmt.Printf("%c", ds[dp]) case ',': fmt.Scanf("%c", &ds[dp]) case '[': if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if is[ip] == '[' { nc++ } else if is[ip] == ']' { nc-- } } } case ']': if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if is[ip] == ']' { nc++ } else if is[ip] == '[' { nc-- } } } } } }
Write the same algorithm in Go as shown in this C implementation.
int meaning_of_life();
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
int meaning_of_life();
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
Port the following code from C to Go with equivalent syntax and logic.
#include<stdlib.h> #include<stdio.h> #include<math.h> int p[512]; double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double lerp(double t, double a, double b) { return a + t * (b - a); } double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } double noise(double x, double y, double z) { int X = (int)floor(x) & 255, Y = (int)floor(y) & 255, Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } void loadPermutation(char* fileName){ FILE* fp = fopen(fileName,"r"); int permutation[256],i; for(i=0;i<256;i++) fscanf(fp,"%d",&permutation[i]); fclose(fp); for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } int main(int argC,char* argV[]) { if(argC!=5) printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>"); else{ loadPermutation(argV[1]); printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL))); } return 0; }
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fade(x) v := fade(y) w := fade(z) A := p[X] + Y AA := p[A] + Z AB := p[A+1] + Z B := p[X+1] + Y BA := p[B] + Z BB := p[B+1] + Z return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x-1, y, z)), lerp(u, grad(p[AB], x, y-1, z), grad(p[BB], x-1, y-1, z))), lerp(v, lerp(u, grad(p[AA+1], x, y, z-1), grad(p[BA+1], x-1, y, z-1)), lerp(u, grad(p[AB+1], x, y-1, z-1), grad(p[BB+1], x-1, y-1, z-1)))) } func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) } func lerp(t, a, b float64) float64 { return a + t*(b-a) } func grad(hash int, x, y, z float64) float64 { switch hash & 15 { case 0, 12: return x + y case 1, 14: return y - x case 2: return x - y case 3: return -x - y case 4: return x + z case 5: return z - x case 6: return x - z case 7: return -x - z case 8: return y + z case 9, 13: return z - y case 10: return y - z } return -y - z } var permutation = []int{ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, } var p = append(permutation, permutation...)