Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the provided C code into Go while preserving the original functionality.
#include <windows.h> #include <wchar.h> int main() { CONSOLE_SCREEN_BUFFER_INFO info; COORD pos; HANDLE conout; long len; wchar_t c; conout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (conout == INVALID_HANDLE_VALUE) return 1; if (GetConsoleScreenBufferInfo(conout, &info) == 0) return 1; pos.X = info.srWindow.Left + 3; pos.Y = info.srWindow.Top + 6; if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 || len <= 0) return 1; wprintf(L"Character at (3, 6) had been '%lc'\n", c); return 0; }
package main import "C" import "fmt" func main() { for i := 0; i < 80*25; i++ { fmt.Print("A") } fmt.Println() conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE) info := C.CONSOLE_SCREEN_BUFFER_INFO{} pos := C.COORD{} C.GetConsoleScreenBufferInfo(conOut, &info) pos.X = info.srWindow.Left + 3 pos.Y = info.srWindow.Top + 6 var c C.wchar_t var le C.ulong ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le) if ret == 0 || le <= 0 { fmt.Println("Something went wrong!") return } fmt.Printf("The character at column 3, row 6 is '%c'\n", c) }
Port the provided C code into Go while preserving the original functionality.
#include<stdio.h> long long seed; long long random(){ seed = seed * seed / 1000 % 1000000; return seed; } int main(){ seed = 675248; for(int i=1;i<=5;i++) printf("%lld\n",random()); return 0; }
package main import "fmt" func random(seed int) int { return seed * seed / 1e3 % 1e6 } func main() { seed := 675248 for i := 1; i <= 5; i++ { seed = random(seed) fmt.Println(seed) } }
Translate the given C code snippet into Go without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { case ignore, parseError, comment, blank: return l.value case value: s := l.option if l.disabled { s = "; " + s } if l.value != "" { s += " " + l.value } return s } panic("unexpected line kind") } func removeDross(s string) string { return strings.Map(func(r rune) rune { if r < 32 || r > 0x7f || unicode.IsControl(r) { return -1 } return r }, s) } func parseLine(s string) line { if s == "" { return line{kind: blank} } if s[0] == '#' { return line{kind: comment, value: s} } s = removeDross(s) fields := strings.Fields(s) if len(fields) == 0 { return line{kind: blank} } semi := false for len(fields[0]) > 0 && fields[0][0] == ';' { semi = true fields[0] = fields[0][1:] } if fields[0] == "" { fields = fields[1:] } switch len(fields) { case 0: return line{kind: ignore} case 1: return line{ kind: value, option: strings.ToUpper(fields[0]), disabled: semi, } case 2: return line{ kind: value, option: strings.ToUpper(fields[0]), value: fields[1], disabled: semi, } } return line{kind: parseError, value: s} } type Config struct { options map[string]int lines []line } func (c *Config) index(option string) int { if i, ok := c.options[option]; ok { return i } return -1 } func (c *Config) addLine(l line) { switch l.kind { case ignore: return case value: if c.index(l.option) >= 0 { return } c.options[l.option] = len(c.lines) c.lines = append(c.lines, l) default: c.lines = append(c.lines, l) } } func ReadConfig(path string) (*Config, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() r := bufio.NewReader(f) c := &Config{options: make(map[string]int)} for { s, err := r.ReadString('\n') if s != "" { if err == nil { s = s[:len(s)-1] } c.addLine(parseLine(s)) } if err == io.EOF { break } if err != nil { return nil, err } } return c, nil } func (c *Config) Set(option string, val string) { if i := c.index(option); i >= 0 { line := &c.lines[i] line.disabled = false line.value = val return } c.addLine(line{ kind: value, option: option, value: val, }) } func (c *Config) Enable(option string, enabled bool) { if i := c.index(option); i >= 0 { c.lines[i].disabled = !enabled } } func (c *Config) Write(w io.Writer) { for _, line := range c.lines { fmt.Println(line) } } func main() { c, err := ReadConfig("/tmp/cfg") if err != nil { log.Fatalln(err) } c.Enable("NEEDSPEELING", false) c.Set("SEEDSREMOVED", "") c.Set("NUMBEROFBANANAS", "1024") c.Set("NUMBEROFSTRAWBERRIES", "62000") c.Write(os.Stdout) }
Keep all operations the same but rewrite the snippet in Go.
image filter(image img, double *K, int Ks, double, double);
package main import ( "fmt" "image" "image/color" "image/jpeg" "math" "os" ) func kf3(k *[9]float64, src, dst *image.Gray) { for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ { for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ { var sum float64 var i int for yo := y - 1; yo <= y+1; yo++ { for xo := x - 1; xo <= x+1; xo++ { if (image.Point{xo, yo}).In(src.Rect) { sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y) } else { sum += k[i] * float64(src.At(x, y).(color.Gray).Y) } i++ } } dst.SetGray(x, y, color.Gray{uint8(math.Min(255, math.Max(0, sum)))}) } } } var blur = [9]float64{ 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9, 1. / 9} func blurY(src *image.YCbCr) *image.YCbCr { dst := *src if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y { return &dst } srcGray := image.Gray{src.Y, src.YStride, src.Rect} dstGray := srcGray dstGray.Pix = make([]uint8, len(src.Y)) kf3(&blur, &srcGray, &dstGray) dst.Y = dstGray.Pix dst.Cb = append([]uint8{}, src.Cb...) dst.Cr = append([]uint8{}, src.Cr...) return &dst } func main() { f, err := os.Open("Lenna100.jpg") if err != nil { fmt.Println(err) return } img, err := jpeg.Decode(f) if err != nil { fmt.Println(err) return } f.Close() y, ok := img.(*image.YCbCr) if !ok { fmt.Println("expected color jpeg") return } f, err = os.Create("blur.jpg") if err != nil { fmt.Println(err) return } err = jpeg.Encode(f, blurY(y), &jpeg.Options{90}) if err != nil { fmt.Println(err) } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdint.h> typedef uint32_t uint; typedef uint64_t ulong; ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; } uint min(const uint x, const uint y) { return (x < y) ? x : y; } void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; } for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); } double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1); const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2); const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2)); double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; } int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
package main import( "math" "fmt" ) func minOf(x, y uint) uint { if x < y { return x } return y } func throwDie(nSides, nDice, s uint, counts []uint) { if nDice == 0 { counts[s]++ return } for i := uint(1); i <= nSides; i++ { throwDie(nSides, nDice - 1, s + i, counts) } } func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 { len1 := (nSides1 + 1) * nDice1 c1 := make([]uint, len1) throwDie(nSides1, nDice1, 0, c1) len2 := (nSides2 + 1) * nDice2 c2 := make([]uint, len2) throwDie(nSides2, nDice2, 0, c2) p12 := math.Pow(float64(nSides1), float64(nDice1)) * math.Pow(float64(nSides2), float64(nDice2)) tot := 0.0 for i := uint(0); i < len1; i++ { for j := uint(0); j < minOf(i, len2); j++ { tot += float64(c1[i] * c2[j]) / p12 } } return tot } func main() { fmt.Println(beatingProbability(4, 9, 6, 6)) fmt.Println(beatingProbability(10, 5, 7, 6)) }
Write the same code in Go as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } 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; } 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.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_find_unimplemented_tasks.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 ( "encoding/xml" "fmt" "io" "net/http" "net/url" ) const language = "Go" var baseQuery = "http: "&format=xml&list=categorymembers&cmlimit=100" func req(u string, foundCm func(string)) string { resp, err := http.Get(u) if err != nil { fmt.Println(err) return "" } defer resp.Body.Close() for p := xml.NewDecoder(resp.Body); ; { t, err := p.RawToken() switch s, ok := t.(xml.StartElement); { case err == io.EOF: return "" case err != nil: fmt.Println(err) return "" case !ok: continue case s.Name.Local == "cm": for _, a := range s.Attr { if a.Name.Local == "title" { foundCm(a.Value) } } case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && s.Attr[0].Name.Local == "cmcontinue": return url.QueryEscape(s.Attr[0].Value) } } return "" } func main() { langMap := make(map[string]bool) storeLang := func(cm string) { langMap[cm] = true } languageQuery := baseQuery + "&cmtitle=Category:" + language continueAt := req(languageQuery, storeLang) for continueAt > "" { continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang) } if len(langMap) == 0 { fmt.Println("no tasks implemented for", language) return } printUnImp := func(cm string) { if !langMap[cm] { fmt.Println(cm) } } taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks" continueAt = req(taskQuery, printUnImp) for continueAt > "" { continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp) } }
Rewrite the snippet below in Go so it works the same as the original C code.
int main(){int a=0, b=0, c=a/b;}
package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
Please provide an equivalent version of this C code in Go.
#include<windows.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<math.h> #define pi M_PI int main() { CONSOLE_SCREEN_BUFFER_INFO info; int cols, rows; time_t t; int i,j; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); cols = info.srWindow.Right - info.srWindow.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system("@clear||cls"); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf("%c",219); } getchar(); return 0; }
package main import ( "image" "image/color" "image/gif" "log" "math" "os" ) func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func main() { const degToRad = math.Pi / 180 const nframes = 100 const delay = 4 w, h := 640, 640 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, w, h) palette := make([]color.Color, nframes+1) palette[0] = color.White for i := 1; i <= nframes; i++ { r, g, b := hsb2rgb(float64(i)/nframes, 1, 1) palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255} } for f := 1; f <= nframes; f++ { img := image.NewPaletted(rect, palette) setBackgroundColor(img, w, h, 0) for y := 0; y < h; y++ { for x := 0; x < w; x++ { fx, fy := float64(x), float64(y) value := math.Sin(fx / 16) value += math.Sin(fy / 8) value += math.Sin((fx + fy) / 16) value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8) value += 4 value /= 8 _, rem := math.Modf(value + float64(f)/float64(nframes)) ci := uint8(nframes*rem) + 1 img.SetColorIndex(x, y, ci) } } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } file, err := os.Create("plasma.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
Translate this program into Go but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> void wordle(const char *answer, const char *guess, int *result) { int i, ix, n = strlen(guess); char *ptr; if (n != strlen(answer)) { printf("The words must be of the same length.\n"); exit(1); } char answer2[n+1]; strcpy(answer2, answer); for (i = 0; i < n; ++i) { if (guess[i] == answer2[i]) { answer2[i] = '\v'; result[i] = 2; } } for (i = 0; i < n; ++i) { if ((ptr = strchr(answer2, guess[i])) != NULL) { ix = ptr - answer2; answer2[ix] = '\v'; result[i] = 1; } } } int main() { int i, j; const char *answer, *guess; int res[5]; const char *res2[5]; const char *colors[3] = {"grey", "yellow", "green"}; const char *pairs[5][2] = { {"ALLOW", "LOLLY"}, {"BULLY", "LOLLY"}, {"ROBIN", "ALERT"}, {"ROBIN", "SONIC"}, {"ROBIN", "ROBIN"} }; for (i = 0; i < 5; ++i) { answer = pairs[i][0]; guess = pairs[i][1]; for (j = 0; j < 5; ++j) res[j] = 0; wordle(answer, guess, res); for (j = 0; j < 5; ++j) res2[j] = colors[res[j]]; printf("%s v %s => { ", answer, guess); for (j = 0; j < 5; ++j) printf("%d ", res[j]); printf("} => { "); for (j = 0; j < 5; ++j) printf("%s ", res2[j]); printf("}\n"); } return 0; }
package main import ( "bytes" "fmt" "log" ) func wordle(answer, guess string) []int { n := len(guess) if n != len(answer) { log.Fatal("The words must be of the same length.") } answerBytes := []byte(answer) result := make([]int, n) for i := 0; i < n; i++ { if guess[i] == answerBytes[i] { answerBytes[i] = '\000' result[i] = 2 } } for i := 0; i < n; i++ { ix := bytes.IndexByte(answerBytes, guess[i]) if ix >= 0 { answerBytes[ix] = '\000' result[i] = 1 } } return result } func main() { colors := []string{"grey", "yellow", "green"} pairs := [][]string{ {"ALLOW", "LOLLY"}, {"BULLY", "LOLLY"}, {"ROBIN", "ALERT"}, {"ROBIN", "SONIC"}, {"ROBIN", "ROBIN"}, } for _, pair := range pairs { res := wordle(pair[0], pair[1]) res2 := make([]string, len(res)) for i := 0; i < len(res); i++ { res2[i] = colors[res[i]] } fmt.Printf("%s v %s => %v => %v\n", pair[0], pair[1], res, res2) } }
Maintain the same structure and functionality when rewriting this code in Go.
typedef struct oct_node_t oct_node_t, *oct_node; struct oct_node_t{ uint64_t r, g, b; int count, heap_idx; oct_node kids[8], parent; unsigned char n_kids, kid_idx, flags, depth; }; inline int cmp_node(oct_node a, oct_node b) { if (a->n_kids < b->n_kids) return -1; if (a->n_kids > b->n_kids) return 1; int ac = a->count * (1 + a->kid_idx) >> a->depth; int bc = b->count * (1 + b->kid_idx) >> b->depth; return ac < bc ? -1 : ac > bc; } oct_node node_insert(oct_node root, unsigned char *pix) { # define OCT_DEPTH 8 unsigned char i, bit, depth = 0; for (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) { i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit); if (!root->kids[i]) root->kids[i] = node_new(i, depth, root); root = root->kids[i]; } root->r += pix[0]; root->g += pix[1]; root->b += pix[2]; root->count++; return root; } oct_node node_fold(oct_node p) { if (p->n_kids) abort(); oct_node q = p->parent; q->count += p->count; q->r += p->r; q->g += p->g; q->b += p->b; q->n_kids --; q->kids[p->kid_idx] = 0; return q; } void color_replace(oct_node root, unsigned char *pix) { unsigned char i, bit; for (bit = 1 << 7; bit; bit >>= 1) { i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit); if (!root->kids[i]) break; root = root->kids[i]; } pix[0] = root->r; pix[1] = root->g; pix[2] = root->b; } void color_quant(image im, int n_colors) { int i; unsigned char *pix = im->pix; node_heap heap = { 0, 0, 0 }; oct_node root = node_new(0, 0, 0), got; for (i = 0; i < im->w * im->h; i++, pix += 3) heap_add(&heap, node_insert(root, pix)); while (heap.n > n_colors + 1) heap_add(&heap, node_fold(pop_heap(&heap))); double c; for (i = 1; i < heap.n; i++) { got = heap.buf[i]; c = got->count; got->r = got->r / c + .5; got->g = got->g / c + .5; got->b = got->b / c + .5; printf("%2d | %3llu %3llu %3llu (%d pixels)\n", i, got->r, got->g, got->b, got->count); } for (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3) color_replace(root, pix); node_free(); free(heap.buf); }
package main import ( "container/heap" "image" "image/color" "image/png" "log" "math" "os" "sort" ) func main() { f, err := os.Open("Quantum_frog.png") if err != nil { log.Fatal(err) } img, err := png.Decode(f) if ec := f.Close(); err != nil { log.Fatal(err) } else if ec != nil { log.Fatal(ec) } fq, err := os.Create("frog16.png") if err != nil { log.Fatal(err) } if err = png.Encode(fq, quant(img, 16)); err != nil { log.Fatal(err) } } func quant(img image.Image, nq int) image.Image { qz := newQuantizer(img, nq) qz.cluster() return qz.Paletted() } type quantizer struct { img image.Image cs []cluster px []point ch chValues eq []point } type cluster struct { px []point widestCh int chRange uint32 } type point struct{ x, y int } type chValues []uint32 type queue []*cluster const ( rx = iota gx bx ) func newQuantizer(img image.Image, nq int) *quantizer { b := img.Bounds() npx := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) qz := &quantizer{ img: img, ch: make(chValues, npx), cs: make([]cluster, nq), } c := &qz.cs[0] px := make([]point, npx) c.px = px i := 0 for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { px[i].x = x px[i].y = y i++ } } return qz } func (qz *quantizer) cluster() { pq := new(queue) c := &qz.cs[0] for i := 1; ; { qz.setColorRange(c) if c.chRange > 0 { heap.Push(pq, c) } if len(*pq) == 0 { qz.cs = qz.cs[:i] break } s := heap.Pop(pq).(*cluster) c = &qz.cs[i] i++ m := qz.Median(s) qz.Split(s, c, m) if i == len(qz.cs) { break } qz.setColorRange(s) if s.chRange > 0 { heap.Push(pq, s) } } } func (q *quantizer) setColorRange(c *cluster) { var maxR, maxG, maxB uint32 minR := uint32(math.MaxUint32) minG := uint32(math.MaxUint32) minB := uint32(math.MaxUint32) for _, p := range c.px { r, g, b, _ := q.img.At(p.x, p.y).RGBA() if r < minR { minR = r } if r > maxR { maxR = r } if g < minG { minG = g } if g > maxG { maxG = g } if b < minB { minB = b } if b > maxB { maxB = b } } s := gx min := minG max := maxG if maxR-minR > max-min { s = rx min = minR max = maxR } if maxB-minB > max-min { s = bx min = minB max = maxB } c.widestCh = s c.chRange = max - min } func (q *quantizer) Median(c *cluster) uint32 { px := c.px ch := q.ch[:len(px)] switch c.widestCh { case rx: for i, p := range c.px { ch[i], _, _, _ = q.img.At(p.x, p.y).RGBA() } case gx: for i, p := range c.px { _, ch[i], _, _ = q.img.At(p.x, p.y).RGBA() } case bx: for i, p := range c.px { _, _, ch[i], _ = q.img.At(p.x, p.y).RGBA() } } sort.Sort(ch) half := len(ch) / 2 m := ch[half] if len(ch)%2 == 0 { m = (m + ch[half-1]) / 2 } return m } func (q *quantizer) Split(s, c *cluster, m uint32) { px := s.px var v uint32 i := 0 lt := 0 gt := len(px) - 1 eq := q.eq[:0] for i <= gt { r, g, b, _ := q.img.At(px[i].x, px[i].y).RGBA() switch s.widestCh { case rx: v = r case gx: v = g case bx: v = b } switch { case v < m: px[lt] = px[i] lt++ i++ case v > m: px[gt], px[i] = px[i], px[gt] gt-- default: eq = append(eq, px[i]) i++ } } if len(eq) > 0 { copy(px[lt:], eq) if len(px)-i < lt { i = lt } q.eq = eq } s.px = px[:i] c.px = px[i:] } func (qz *quantizer) Paletted() *image.Paletted { cp := make(color.Palette, len(qz.cs)) pi := image.NewPaletted(qz.img.Bounds(), cp) for i := range qz.cs { px := qz.cs[i].px var rsum, gsum, bsum int64 for _, p := range px { r, g, b, _ := qz.img.At(p.x, p.y).RGBA() rsum += int64(r) gsum += int64(g) bsum += int64(b) } n64 := int64(len(px)) cp[i] = color.NRGBA64{ uint16(rsum / n64), uint16(gsum / n64), uint16(bsum / n64), 0xffff, } for _, p := range px { pi.SetColorIndex(p.x, p.y, uint8(i)) } } return pi } func (c chValues) Len() int { return len(c) } func (c chValues) Less(i, j int) bool { return c[i] < c[j] } func (c chValues) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (q queue) Len() int { return len(q) } func (q queue) Less(i, j int) bool { return len(q[j].px) < len(q[i].px) } func (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] } func (pq *queue) Push(x interface{}) { c := x.(*cluster) *pq = append(*pq, c) } func (pq *queue) Pop() interface{} { q := *pq n := len(q) - 1 c := q[n] *pq = q[:n] return c }
Convert this C block to Go, preserving its control flow and logic.
#define _POSIX_SOURCE #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <stddef.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> struct functionInfo { char* name; int timesCalled; char marked; }; void addToList(struct functionInfo** list, struct functionInfo toAdd, \ size_t* numElements, size_t* allocatedSize) { static const char* keywords[32] = {"auto", "break", "case", "char", "const", \ "continue", "default", "do", "double", \ "else", "enum", "extern", "float", "for", \ "goto", "if", "int", "long", "register", \ "return", "short", "signed", "sizeof", \ "static", "struct", "switch", "typedef", \ "union", "unsigned", "void", "volatile", \ "while" }; int i; for (i = 0; i < 32; i++) { if (!strcmp(toAdd.name, keywords[i])) { return; } } if (!*list) { *allocatedSize = 10; *list = calloc(*allocatedSize, sizeof(struct functionInfo)); if (!*list) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ *allocatedSize, sizeof(struct functionInfo)); abort(); } (*list)[0].name = malloc(strlen(toAdd.name)+1); if (!(*list)[0].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[0].name, toAdd.name); (*list)[0].timesCalled = 1; (*list)[0].marked = 0; *numElements = 1; } else { char found = 0; unsigned int i; for (i = 0; i < *numElements; i++) { if (!strcmp((*list)[i].name, toAdd.name)) { found = 1; (*list)[i].timesCalled++; break; } } if (!found) { struct functionInfo* newList = calloc((*allocatedSize)+10, \ sizeof(struct functionInfo)); if (!newList) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ (*allocatedSize)+10, sizeof(struct functionInfo)); abort(); } memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo)); free(*list); *allocatedSize += 10; *list = newList; (*list)[*numElements].name = malloc(strlen(toAdd.name)+1); if (!(*list)[*numElements].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[*numElements].name, toAdd.name); (*list)[*numElements].timesCalled = 1; (*list)[*numElements].marked = 0; (*numElements)++; } } } void printList(struct functionInfo** list, size_t numElements) { char maxSet = 0; unsigned int i; size_t maxIndex = 0; for (i = 0; i<10; i++) { maxSet = 0; size_t j; for (j = 0; j<numElements; j++) { if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) { if (!(*list)[j].marked) { maxSet = 1; maxIndex = j; } } } (*list)[maxIndex].marked = 1; printf("%s() called %d times.\n", (*list)[maxIndex].name, \ (*list)[maxIndex].timesCalled); } } void freeList(struct functionInfo** list, size_t numElements) { size_t i; for (i = 0; i<numElements; i++) { free((*list)[i].name); } free(*list); } char* extractFunctionName(char* readHead) { char* identifier = readHead; if (isalpha(*identifier) || *identifier == '_') { while (isalnum(*identifier) || *identifier == '_') { identifier++; } } char* toParen = identifier; if (toParen == readHead) return NULL; while (isspace(*toParen)) { toParen++; } if (*toParen != '(') return NULL; ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \ - ((ptrdiff_t)readHead)+1; char* const name = malloc(size); if (!name) { printf("Failed to allocate %lu bytes.\n", size); abort(); } name[size-1] = '\0'; memcpy(name, readHead, size-1); if (strcmp(name, "")) { return name; } free(name); return NULL; } int main(int argc, char** argv) { int i; for (i = 1; i<argc; i++) { errno = 0; FILE* file = fopen(argv[i], "r"); if (errno || !file) { printf("fopen() failed with error code \"%s\"\n", \ strerror(errno)); abort(); } char comment = 0; #define DOUBLEQUOTE 1 #define SINGLEQUOTE 2 int string = 0; struct functionInfo* functions = NULL; struct functionInfo toAdd; size_t numElements = 0; size_t allocatedSize = 0; struct stat metaData; errno = 0; if (fstat(fileno(file), &metaData) < 0) { printf("fstat() returned error \"%s\"\n", strerror(errno)); abort(); } char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \ MAP_PRIVATE, fileno(file), 0); if (errno) { printf("mmap() failed with error \"%s\"\n", strerror(errno)); abort(); } if (!mmappedSource) { printf("mmap() returned NULL.\n"); abort(); } char* readHead = mmappedSource; while (readHead < mmappedSource + metaData.st_size) { while (*readHead) { if (!string) { if (*readHead == '/' && !strncmp(readHead, "", 2)) { comment = 0; } } if (!comment) { if (*readHead == '"') { if (!string) { string = DOUBLEQUOTE; } else if (string == DOUBLEQUOTE) { if (strncmp((readHead-1), "\\\"", 2)) { string = 0; } } } if (*readHead == '\'') { if (!string) { string = SINGLEQUOTE; } else if (string == SINGLEQUOTE) { if (strncmp((readHead-1), "\\\'", 2)) { string = 0; } } } } if (!comment && !string) { char* name = extractFunctionName(readHead); if (name) { toAdd.name = name; addToList(&functions, toAdd, &numElements, &allocatedSize); readHead += strlen(name); } free(name); } readHead++; } } errno = 0; munmap(mmappedSource, metaData.st_size); if (errno) { printf("munmap() returned error \"%s\"\n", strerror(errno)); abort(); } errno = 0; fclose(file); if (errno) { printf("fclose() returned error \"%s\"\n", strerror(errno)); abort(); } printList(&functions, numElements); freeList(&functions, numElements); } return 0; }
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) return } fs := token.NewFileSet() a, err := parser.ParseFile(fs, os.Args[1], src, 0) if err != nil { fmt.Println(err) return } f := fs.File(a.Pos()) m := make(map[string]int) ast.Inspect(a, func(n ast.Node) bool { if ce, ok := n.(*ast.CallExpr); ok { start := f.Offset(ce.Pos()) end := f.Offset(ce.Lparen) m[string(src[start:end])]++ } return true }) cs := make(calls, 0, len(m)) for k, v := range m { cs = append(cs, &call{k, v}) } sort.Sort(cs) for i, c := range cs { fmt.Printf("%-20s %4d\n", c.expr, c.count) if i == 9 { break } } } type call struct { expr string count int } type calls []*call func (c calls) Len() int { return len(c) } func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }
Generate a Go translation of this C snippet without changing its computational steps.
#define _POSIX_SOURCE #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <stddef.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> struct functionInfo { char* name; int timesCalled; char marked; }; void addToList(struct functionInfo** list, struct functionInfo toAdd, \ size_t* numElements, size_t* allocatedSize) { static const char* keywords[32] = {"auto", "break", "case", "char", "const", \ "continue", "default", "do", "double", \ "else", "enum", "extern", "float", "for", \ "goto", "if", "int", "long", "register", \ "return", "short", "signed", "sizeof", \ "static", "struct", "switch", "typedef", \ "union", "unsigned", "void", "volatile", \ "while" }; int i; for (i = 0; i < 32; i++) { if (!strcmp(toAdd.name, keywords[i])) { return; } } if (!*list) { *allocatedSize = 10; *list = calloc(*allocatedSize, sizeof(struct functionInfo)); if (!*list) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ *allocatedSize, sizeof(struct functionInfo)); abort(); } (*list)[0].name = malloc(strlen(toAdd.name)+1); if (!(*list)[0].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[0].name, toAdd.name); (*list)[0].timesCalled = 1; (*list)[0].marked = 0; *numElements = 1; } else { char found = 0; unsigned int i; for (i = 0; i < *numElements; i++) { if (!strcmp((*list)[i].name, toAdd.name)) { found = 1; (*list)[i].timesCalled++; break; } } if (!found) { struct functionInfo* newList = calloc((*allocatedSize)+10, \ sizeof(struct functionInfo)); if (!newList) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ (*allocatedSize)+10, sizeof(struct functionInfo)); abort(); } memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo)); free(*list); *allocatedSize += 10; *list = newList; (*list)[*numElements].name = malloc(strlen(toAdd.name)+1); if (!(*list)[*numElements].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[*numElements].name, toAdd.name); (*list)[*numElements].timesCalled = 1; (*list)[*numElements].marked = 0; (*numElements)++; } } } void printList(struct functionInfo** list, size_t numElements) { char maxSet = 0; unsigned int i; size_t maxIndex = 0; for (i = 0; i<10; i++) { maxSet = 0; size_t j; for (j = 0; j<numElements; j++) { if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) { if (!(*list)[j].marked) { maxSet = 1; maxIndex = j; } } } (*list)[maxIndex].marked = 1; printf("%s() called %d times.\n", (*list)[maxIndex].name, \ (*list)[maxIndex].timesCalled); } } void freeList(struct functionInfo** list, size_t numElements) { size_t i; for (i = 0; i<numElements; i++) { free((*list)[i].name); } free(*list); } char* extractFunctionName(char* readHead) { char* identifier = readHead; if (isalpha(*identifier) || *identifier == '_') { while (isalnum(*identifier) || *identifier == '_') { identifier++; } } char* toParen = identifier; if (toParen == readHead) return NULL; while (isspace(*toParen)) { toParen++; } if (*toParen != '(') return NULL; ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \ - ((ptrdiff_t)readHead)+1; char* const name = malloc(size); if (!name) { printf("Failed to allocate %lu bytes.\n", size); abort(); } name[size-1] = '\0'; memcpy(name, readHead, size-1); if (strcmp(name, "")) { return name; } free(name); return NULL; } int main(int argc, char** argv) { int i; for (i = 1; i<argc; i++) { errno = 0; FILE* file = fopen(argv[i], "r"); if (errno || !file) { printf("fopen() failed with error code \"%s\"\n", \ strerror(errno)); abort(); } char comment = 0; #define DOUBLEQUOTE 1 #define SINGLEQUOTE 2 int string = 0; struct functionInfo* functions = NULL; struct functionInfo toAdd; size_t numElements = 0; size_t allocatedSize = 0; struct stat metaData; errno = 0; if (fstat(fileno(file), &metaData) < 0) { printf("fstat() returned error \"%s\"\n", strerror(errno)); abort(); } char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \ MAP_PRIVATE, fileno(file), 0); if (errno) { printf("mmap() failed with error \"%s\"\n", strerror(errno)); abort(); } if (!mmappedSource) { printf("mmap() returned NULL.\n"); abort(); } char* readHead = mmappedSource; while (readHead < mmappedSource + metaData.st_size) { while (*readHead) { if (!string) { if (*readHead == '/' && !strncmp(readHead, "", 2)) { comment = 0; } } if (!comment) { if (*readHead == '"') { if (!string) { string = DOUBLEQUOTE; } else if (string == DOUBLEQUOTE) { if (strncmp((readHead-1), "\\\"", 2)) { string = 0; } } } if (*readHead == '\'') { if (!string) { string = SINGLEQUOTE; } else if (string == SINGLEQUOTE) { if (strncmp((readHead-1), "\\\'", 2)) { string = 0; } } } } if (!comment && !string) { char* name = extractFunctionName(readHead); if (name) { toAdd.name = name; addToList(&functions, toAdd, &numElements, &allocatedSize); readHead += strlen(name); } free(name); } readHead++; } } errno = 0; munmap(mmappedSource, metaData.st_size); if (errno) { printf("munmap() returned error \"%s\"\n", strerror(errno)); abort(); } errno = 0; fclose(file); if (errno) { printf("fclose() returned error \"%s\"\n", strerror(errno)); abort(); } printList(&functions, numElements); freeList(&functions, numElements); } return 0; }
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) return } fs := token.NewFileSet() a, err := parser.ParseFile(fs, os.Args[1], src, 0) if err != nil { fmt.Println(err) return } f := fs.File(a.Pos()) m := make(map[string]int) ast.Inspect(a, func(n ast.Node) bool { if ce, ok := n.(*ast.CallExpr); ok { start := f.Offset(ce.Pos()) end := f.Offset(ce.Lparen) m[string(src[start:end])]++ } return true }) cs := make(calls, 0, len(m)) for k, v := range m { cs = append(cs, &call{k, v}) } sort.Sort(cs) for i, c := range cs { fmt.Printf("%-20s %4d\n", c.expr, c.count) if i == 9 { break } } } type call struct { expr string count int } type calls []*call func (c calls) Len() int { return len(c) } func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }
Port the provided C code into Go while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t poker[] = L"♥♦♣♠"; wchar_t four_two[] = L"\x56db\x5341\x4e8c"; int main() { if (!setlocale(LC_CTYPE, "")) { fprintf(stderr, "Locale failure, check your env vars\n"); return 1; } #ifdef __STDC_ISO_10646__ printf("%lc\n", 0x2708); printf("%ls\n", poker); printf("%ls\n", four_two); #else printf("airplane\n"); printf("club diamond club spade\n"); printf("for ty two\n"); #endif return 0; }
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
Keep all operations the same but rewrite the snippet in Go.
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t poker[] = L"♥♦♣♠"; wchar_t four_two[] = L"\x56db\x5341\x4e8c"; int main() { if (!setlocale(LC_CTYPE, "")) { fprintf(stderr, "Locale failure, check your env vars\n"); return 1; } #ifdef __STDC_ISO_10646__ printf("%lc\n", 0x2708); printf("%ls\n", poker); printf("%ls\n", four_two); #else printf("airplane\n"); printf("club diamond club spade\n"); printf("for ty two\n"); #endif return 0; }
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
Can you help me rewrite this code in Go instead of C, keeping it the same logically?
image read_image(const char *name);
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := raster.ReadPpmFrom(pipe) if err != nil { log.Fatal(err) } if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil { log.Fatal(err) } }
Change the following C code into Go without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "wren.h" void C_fileAllocate(WrenVM* vm) { FILE** pfp = (FILE**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(FILE*)); const char *filename = wrenGetSlotString(vm, 1); const char *mode = wrenGetSlotString(vm, 2); *pfp = fopen(filename, mode); } void C_write(WrenVM* vm) { FILE* fp = *(FILE**)wrenGetSlotForeign(vm, 0); const char *s = wrenGetSlotString(vm, 1); fputs(s, fp); } void C_close(WrenVM* vm) { FILE* fp = *(FILE**)wrenGetSlotForeign(vm, 0); fclose(fp); } void C_remove(WrenVM* vm) { const char *filename = wrenGetSlotString(vm, 1); remove(filename); } void C_flushAll(WrenVM* vm) { fflush(NULL); } void C_system(WrenVM* vm) { const char *s = wrenGetSlotString(vm, 1); system(s); } void C_sleep(WrenVM* vm) { int seconds = (int)wrenGetSlotDouble(vm, 1); sleep(seconds); } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "File") == 0) { methods.allocate = C_fileAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "File") == 0) { if (!isStatic && strcmp(signature, "write(_)") == 0) return C_write; if (!isStatic && strcmp(signature, "close()") == 0) return C_close; if ( isStatic && strcmp(signature, "remove(_)") == 0) return C_remove; if ( isStatic && strcmp(signature, "flushAll()") == 0) return C_flushAll; } else if (strcmp(className, "C") == 0) { if ( isStatic && strcmp(signature, "system(_)") == 0) return C_system; if ( isStatic && strcmp(signature, "sleep(_)") == 0) return C_sleep; } } 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; } 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.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "starting_web_browser.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 ( "fmt" "html/template" "log" "os" "os/exec" "strings" "time" ) type row struct { Address, Street, House, Color string } func isDigit(b byte) bool { return '0' <= b && b <= '9' } func separateHouseNumber(address string) (street string, house string) { length := len(address) fields := strings.Fields(address) size := len(fields) last := fields[size-1] penult := fields[size-2] if isDigit(last[0]) { isdig := isDigit(penult[0]) if size > 2 && isdig && !strings.HasPrefix(penult, "194") { house = fmt.Sprintf("%s %s", penult, last) } else { house = last } } else if size > 2 { house = fmt.Sprintf("%s %s", penult, last) } street = strings.TrimRight(address[:length-len(house)], " ") return } func check(err error) { if err != nil { log.Fatal(err) } } var tmpl = ` <head> <title>Rosetta Code - Start a Web Browser</title> <meta charset="UTF-8"> </head> <body bgcolor="#d8dcd6"> <table border="2"> <p align="center"> <font face="Arial, sans-serif" size="5">Split the house number from the street name</font> <tr bgcolor="#02ccfe"><th>Address</th><th>Street</th><th>House Number</th></tr> {{range $row := .}} <tr bgcolor={{$row.Color}}> <td>{{$row.Address}}</td> <td>{{$row.Street}}</td> <td>{{$row.House}}</td> </tr> {{end}} </p> </table> </body> ` func main() { addresses := []string{ "Plataanstraat 5", "Straat 12", "Straat 12 II", "Dr. J. Straat 12", "Dr. J. Straat 12 a", "Dr. J. Straat 12-14", "Laan 1940 - 1945 37", "Plein 1940 2", "1213-laan 11", "16 april 1944 Pad 1", "1e Kruisweg 36", "Laan 1940-'45 66", "Laan '40-'45", "Langeloërduinen 3 46", "Marienwaerdt 2e Dreef 2", "Provincialeweg N205 1", "Rivium 2e Straat 59.", "Nieuwe gracht 20rd", "Nieuwe gracht 20rd 2", "Nieuwe gracht 20zw /2", "Nieuwe gracht 20zw/3", "Nieuwe gracht 20 zw/4", "Bahnhofstr. 4", "Wertstr. 10", "Lindenhof 1", "Nordesch 20", "Weilstr. 6", "Harthauer Weg 2", "Mainaustr. 49", "August-Horch-Str. 3", "Marktplatz 31", "Schmidener Weg 3", "Karl-Weysser-Str. 6", } browser := "firefox" colors := [2]string{"#d7fffe", "#9dbcd4"} fileName := "addresses_table.html" ct := template.Must(template.New("").Parse(tmpl)) file, err := os.Create(fileName) check(err) rows := make([]row, len(addresses)) for i, address := range addresses { street, house := separateHouseNumber(address) if house == "" { house = "(none)" } color := colors[i%2] rows[i] = row{address, street, house, color} } err = ct.Execute(file, rows) check(err) cmd := exec.Command(browser, fileName) err = cmd.Run() check(err) file.Close() time.Sleep(5 * time.Second) err = os.Remove(fileName) check(err) }
Write the same algorithm in Go as shown in this C implementation.
struct RS232_data { unsigned carrier_detect : 1; unsigned received_data : 1; unsigned transmitted_data : 1; unsigned data_terminal_ready : 1; unsigned signal_ground : 1; unsigned data_set_ready : 1; unsigned request_to_send : 1; unsigned clear_to_send : 1; unsigned ring_indicator : 1; };
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { p := RI9 | TD9 | CD9 fmt.Printf("Type=%T value=%#04x\n", p, p) }
Port the following code from C to Go with equivalent syntax 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 main( void ) { int s=0, p, i=1; for(p=2;p<=999;p++) { if(isprime(p)) { if(i%2) { s+=p; if(isprime(s)) printf( "%d %d %d\n", i, p, s ); } i+=1; } } return 0; }
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum := 0 fmt.Println(" i p[i] Σp[i]") fmt.Println("----------------") for i := 0; i < len(primes); i += 2 { sum += primes[i] if rcu.IsPrime(sum) { fmt.Printf("%3d %3d %6s\n", i+1, primes[i], rcu.Commatize(sum)) } } }
Convert this C snippet to Go and keep its semantics consistent.
#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 s=0, p, i=1; for(p=2;p<=999;p++) { if(isprime(p)) { if(i%2) { s+=p; if(isprime(s)) printf( "%d %d %d\n", i, p, s ); } i+=1; } } return 0; }
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum := 0 fmt.Println(" i p[i] Σp[i]") fmt.Println("----------------") for i := 0; i < len(primes); i += 2 { sum += primes[i] if rcu.IsPrime(sum) { fmt.Printf("%3d %3d %6s\n", i+1, primes[i], rcu.Commatize(sum)) } } }
Produce a language-to-language conversion: from C to Go, same semantics.
#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 s=0, p, i=1; for(p=2;p<=999;p++) { if(isprime(p)) { if(i%2) { s+=p; if(isprime(s)) printf( "%d %d %d\n", i, p, s ); } i+=1; } } return 0; }
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum := 0 fmt.Println(" i p[i] Σp[i]") fmt.Println("----------------") for i := 0; i < len(primes); i += 2 { sum += primes[i] if rcu.IsPrime(sum) { fmt.Printf("%3d %3d %6s\n", i+1, primes[i], rcu.Commatize(sum)) } } }
Generate an equivalent Go version of this C code.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define TRUE 1 #define FALSE 0 typedef int bool; void primeSieve(int *c, int limit, bool processEven, bool primesOnly) { int i, ix, p, p2; limit++; c[0] = TRUE; c[1] = TRUE; if (processEven) { for (i = 4; i < limit; i +=2) c[i] = TRUE; } p = 3; while (TRUE) { p2 = p * p; if (p2 >= limit) break; for (i = p2; i < limit; i += 2*p) c[i] = TRUE; while (TRUE) { p += 2; if (!c[p]) break; } } if (primesOnly) { c[0] = 2; for (i = 3, ix = 1; i < limit; i += 2) { if (!c[i]) c[ix++] = i; } } } int main() { int i, p, hp, n = 10000000; int limit = (int)(log(n) * (double)n * 1.2); int *primes = (int *)calloc(limit, sizeof(int)); primeSieve(primes, limit-1, FALSE, TRUE); printf("The first 20 pairs of natural numbers whose sum is prime are:\n"); for (i = 1; i <= 20; ++i) { p = primes[i]; hp = p / 2; printf("%2d + %2d = %2d\n", hp, hp+1, p); } printf("\nThe 10 millionth such pair is:\n"); p = primes[n]; hp = p / 2; printf("%2d + %2d = %2d\n", hp, hp+1, p); free(primes); return 0; }
package main import ( "fmt" "math" "rcu" ) func main() { limit := int(math.Log(1e7) * 1e7 * 1.2) primes := rcu.Primes(limit) fmt.Println("The first 20 pairs of natural numbers whose sum is prime are:") for i := 1; i <= 20; i++ { p := primes[i] hp := p / 2 fmt.Printf("%2d + %2d = %2d\n", hp, hp+1, p) } fmt.Println("\nThe 10 millionth such pair is:") p := primes[1e7] hp := p / 2 fmt.Printf("%2d + %2d = %2d\n", hp, hp+1, p) }
Convert this C snippet to Go and keep its semantics consistent.
#include <math.h> #include <stdio.h> #define nelems(x) (sizeof(x) / sizeof((x)[0])) const unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11}; unsigned long long gcd(unsigned long long a, unsigned long long b) { while (b != 0) { a %= b; a ^= b; b ^= a; a ^= b; } return a; } unsigned long long SQUFOF( unsigned long long N ) { unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s; unsigned long L, B, i; s = (unsigned long long)(sqrtl(N)+0.5); if (s*s == N) return s; for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) { D = multiplier[k]*N; Po = Pprev = P = sqrtl(D); Qprev = 1; Q = D - Po*Po; L = 2 * sqrtl( 2*s ); B = 3 * L; for (i = 2 ; i < B ; i++) { b = (unsigned long long)((Po + P)/Q); P = b*Q - P; q = Q; Q = Qprev + b*(Pprev - P); r = (unsigned long long)(sqrtl(Q)+0.5); if (!(i & 1) && r*r == Q) break; Qprev = q; Pprev = P; }; if (i >= B) continue; b = (unsigned long long)((Po - P)/r); Pprev = P = b*r + P; Qprev = r; Q = (D - Pprev*Pprev)/Qprev; i = 0; do { b = (unsigned long long)((Po + P)/Q); Pprev = P; P = b*Q - P; q = Q; Q = Qprev + b*(Pprev - P); Qprev = q; i++; } while (P != Pprev); r = gcd(N, Qprev); if (r != 1 && r != N) return r; } return 0; } int main(int argc, char *argv[]) { int i; const unsigned long long data[] = { 2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791, 9007199254740931, 11111111111111111, 314159265358979323, 384307168202281507, 419244183493398773, 658812288346769681, 922337203685477563, 1000000000000000127, 1152921505680588799, 1537228672809128917, 4611686018427387877}; for(int i = 0; i < nelems(data); i++) { unsigned long long example, factor, quotient; example = data[i]; factor = SQUFOF(example); if(factor == 0) { printf("%llu was not factored.\n", example); } else { quotient = example / factor; printf("Integer %llu has factors %llu and %llu\n", example, factor, quotient); } } }
package main import ( "fmt" "math" ) func isqrt(x uint64) uint64 { x0 := x >> 1 x1 := (x0 + x/x0) >> 1 for x1 < x0 { x0 = x1 x1 = (x0 + x/x0) >> 1 } return x0 } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } var multiplier = []uint64{ 1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11, } func squfof(N uint64) uint64 { s := uint64(math.Sqrt(float64(N)) + 0.5) if s*s == N { return s } for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ { D := multiplier[k] * N P := isqrt(D) Pprev := P Po := Pprev Qprev := uint64(1) Q := D - Po*Po L := uint32(isqrt(8 * s)) B := 3 * L i := uint32(2) var b, q, r uint64 for ; i < B; i++ { b = uint64((Po + P) / Q) P = b*Q - P q = Q Q = Qprev + b*(Pprev-P) r = uint64(math.Sqrt(float64(Q)) + 0.5) if (i&1) == 0 && r*r == Q { break } Qprev = q Pprev = P } if i >= B { continue } b = uint64((Po - P) / r) P = b*r + P Pprev = P Qprev = r Q = (D - Pprev*Pprev) / Qprev i = 0 for { b = uint64((Po + P) / Q) Pprev = P P = b*Q - P q = Q Q = Qprev + b*(Pprev-P) Qprev = q i++ if P == Pprev { break } } r = gcd(N, Qprev) if r != 1 && r != N { return r } } return 0 } func main() { examples := []uint64{ 2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791, 9007199254740931, 11111111111111111, 314159265358979323, 384307168202281507, 419244183493398773, 658812288346769681, 922337203685477563, 1000000000000000127, 1152921505680588799, 1537228672809128917, 4611686018427387877, } fmt.Println("Integer Factor Quotient") fmt.Println("------------------------------------------") for _, N := range examples { fact := squfof(N) quot := "fail" if fact > 0 { quot = fmt.Sprintf("%d", N/fact) } fmt.Printf("%-20d %-10d %s\n", N, fact, quot) } }
Produce a functionally identical Go code for the snippet given in C.
#include <math.h> #include <stdio.h> #define nelems(x) (sizeof(x) / sizeof((x)[0])) const unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11}; unsigned long long gcd(unsigned long long a, unsigned long long b) { while (b != 0) { a %= b; a ^= b; b ^= a; a ^= b; } return a; } unsigned long long SQUFOF( unsigned long long N ) { unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s; unsigned long L, B, i; s = (unsigned long long)(sqrtl(N)+0.5); if (s*s == N) return s; for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) { D = multiplier[k]*N; Po = Pprev = P = sqrtl(D); Qprev = 1; Q = D - Po*Po; L = 2 * sqrtl( 2*s ); B = 3 * L; for (i = 2 ; i < B ; i++) { b = (unsigned long long)((Po + P)/Q); P = b*Q - P; q = Q; Q = Qprev + b*(Pprev - P); r = (unsigned long long)(sqrtl(Q)+0.5); if (!(i & 1) && r*r == Q) break; Qprev = q; Pprev = P; }; if (i >= B) continue; b = (unsigned long long)((Po - P)/r); Pprev = P = b*r + P; Qprev = r; Q = (D - Pprev*Pprev)/Qprev; i = 0; do { b = (unsigned long long)((Po + P)/Q); Pprev = P; P = b*Q - P; q = Q; Q = Qprev + b*(Pprev - P); Qprev = q; i++; } while (P != Pprev); r = gcd(N, Qprev); if (r != 1 && r != N) return r; } return 0; } int main(int argc, char *argv[]) { int i; const unsigned long long data[] = { 2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791, 9007199254740931, 11111111111111111, 314159265358979323, 384307168202281507, 419244183493398773, 658812288346769681, 922337203685477563, 1000000000000000127, 1152921505680588799, 1537228672809128917, 4611686018427387877}; for(int i = 0; i < nelems(data); i++) { unsigned long long example, factor, quotient; example = data[i]; factor = SQUFOF(example); if(factor == 0) { printf("%llu was not factored.\n", example); } else { quotient = example / factor; printf("Integer %llu has factors %llu and %llu\n", example, factor, quotient); } } }
package main import ( "fmt" "math" ) func isqrt(x uint64) uint64 { x0 := x >> 1 x1 := (x0 + x/x0) >> 1 for x1 < x0 { x0 = x1 x1 = (x0 + x/x0) >> 1 } return x0 } func gcd(x, y uint64) uint64 { for y != 0 { x, y = y, x%y } return x } var multiplier = []uint64{ 1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11, } func squfof(N uint64) uint64 { s := uint64(math.Sqrt(float64(N)) + 0.5) if s*s == N { return s } for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ { D := multiplier[k] * N P := isqrt(D) Pprev := P Po := Pprev Qprev := uint64(1) Q := D - Po*Po L := uint32(isqrt(8 * s)) B := 3 * L i := uint32(2) var b, q, r uint64 for ; i < B; i++ { b = uint64((Po + P) / Q) P = b*Q - P q = Q Q = Qprev + b*(Pprev-P) r = uint64(math.Sqrt(float64(Q)) + 0.5) if (i&1) == 0 && r*r == Q { break } Qprev = q Pprev = P } if i >= B { continue } b = uint64((Po - P) / r) P = b*r + P Pprev = P Qprev = r Q = (D - Pprev*Pprev) / Qprev i = 0 for { b = uint64((Po + P) / Q) Pprev = P P = b*Q - P q = Q Q = Qprev + b*(Pprev-P) Qprev = q i++ if P == Pprev { break } } r = gcd(N, Qprev) if r != 1 && r != N { return r } } return 0 } func main() { examples := []uint64{ 2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791, 9007199254740931, 11111111111111111, 314159265358979323, 384307168202281507, 419244183493398773, 658812288346769681, 922337203685477563, 1000000000000000127, 1152921505680588799, 1537228672809128917, 4611686018427387877, } fmt.Println("Integer Factor Quotient") fmt.Println("------------------------------------------") for _, N := range examples { fact := squfof(N) quot := "fail" if fact > 0 { quot = fmt.Sprintf("%d", N/fact) } fmt.Printf("%-20d %-10d %s\n", N, fact, quot) } }
Rewrite this program in Go while keeping its functionality equivalent to the C version.
#include <stdlib.h> #include <string.h> #include "dome.h" static DOME_API_v0* core; static WREN_API_v0* wren; static const char* source = "" "class Printer {\n" "foreign static printFile(name) \n" "} \n"; void C_printFile(WrenVM* vm) { const char *arg = wren->getSlotString(vm, 1); char command[strlen(arg) + 4]; strcpy(command, "lp "); strcat(command, arg); int res = system(command); } DOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) { core = DOME_getAPI(API_DOME, DOME_API_VERSION); wren = DOME_getAPI(API_WREN, WREN_API_VERSION); core->registerModule(ctx, "printer", source); core->registerClass(ctx, "printer", "Printer", NULL, NULL); core->registerFn(ctx, "printer", "static Printer.printFile(_)", C_printFile); return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) { return DOME_RESULT_SUCCESS; }
package main import ( "github.com/fogleman/gg" "log" "os/exec" "runtime" ) var palette = [2]string{ "FFFFFF", "000000", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 7 for b := 1; b <= 11; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { dc.SetHexColor(palette[ci%2]) y := h * (b - 1) dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h)) dc.Fill() } } } func main() { dc := gg.NewContext(842, 595) pinstripe(dc) fileName := "w_pinstripe.png" dc.SavePNG(fileName) var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("mspaint", "/pt", fileName) } else { cmd = exec.Command("lp", fileName) } if err := cmd.Run(); err != nil { log.Fatal(err) } }
Write the same algorithm in Go as shown in this C implementation.
#include <stdlib.h> #include <string.h> #include "dome.h" static DOME_API_v0* core; static WREN_API_v0* wren; static const char* source = "" "class Printer {\n" "foreign static printFile(name) \n" "} \n"; void C_printFile(WrenVM* vm) { const char *arg = wren->getSlotString(vm, 1); char command[strlen(arg) + 4]; strcpy(command, "lp "); strcat(command, arg); int res = system(command); } DOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) { core = DOME_getAPI(API_DOME, DOME_API_VERSION); wren = DOME_getAPI(API_WREN, WREN_API_VERSION); core->registerModule(ctx, "printer", source); core->registerClass(ctx, "printer", "Printer", NULL, NULL); core->registerFn(ctx, "printer", "static Printer.printFile(_)", C_printFile); return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) { return DOME_RESULT_SUCCESS; }
package main import ( "github.com/fogleman/gg" "log" "os/exec" "runtime" ) var palette = [2]string{ "FFFFFF", "000000", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 7 for b := 1; b <= 11; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { dc.SetHexColor(palette[ci%2]) y := h * (b - 1) dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h)) dc.Fill() } } } func main() { dc := gg.NewContext(842, 595) pinstripe(dc) fileName := "w_pinstripe.png" dc.SavePNG(fileName) var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("mspaint", "/pt", fileName) } else { cmd = exec.Command("lp", fileName) } if err := cmd.Run(); err != nil { log.Fatal(err) } }
Port the provided C code into Go while preserving the original functionality.
vertex face_point(face f) { int i; vertex v; if (!f->avg) { f->avg = vertex_new(); foreach(i, v, f->v) if (!i) f->avg->pos = v->pos; else vadd(f->avg->pos, v->pos); vdiv(f->avg->pos, len(f->v)); } return f->avg; } #define hole_edge(e) (len(e->f)==1) vertex edge_point(edge e) { int i; face f; if (!e->e_pt) { e->e_pt = vertex_new(); e->avg = e->v[0]->pos; vadd(e->avg, e->v[1]->pos); e->e_pt->pos = e->avg; if (!hole_edge(e)) { foreach (i, f, e->f) vadd(e->e_pt->pos, face_point(f)->pos); vdiv(e->e_pt->pos, 4); } else vdiv(e->e_pt->pos, 2); vdiv(e->avg, 2); } return e->e_pt; } #define hole_vertex(v) (len((v)->f) != len((v)->e)) vertex updated_point(vertex v) { int i, n = 0; edge e; face f; coord_t sum = {0, 0, 0}; if (v->v_new) return v->v_new; v->v_new = vertex_new(); if (hole_vertex(v)) { v->v_new->pos = v->pos; foreach(i, e, v->e) { if (!hole_edge(e)) continue; vadd(v->v_new->pos, edge_point(e)->pos); n++; } vdiv(v->v_new->pos, n + 1); } else { n = len(v->f); foreach(i, f, v->f) vadd(sum, face_point(f)->pos); foreach(i, e, v->e) vmadd(sum, edge_point(e)->pos, 2, sum); vdiv(sum, n); vmadd(sum, v->pos, n - 3, sum); vdiv(sum, n); v->v_new->pos = sum; } return v->v_new; } model catmull(model m) { int i, j, a, b, c, d; face f; vertex v, x; model nm = model_new(); foreach (i, f, m->f) { foreach(j, v, f->v) { _get_idx(a, updated_point(v)); _get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e)))); _get_idx(c, face_point(f)); _get_idx(d, edge_point(elem(f->e, j))); model_add_face(nm, 4, a, b, c, d); } } return nm; }
package main import ( "fmt" "sort" ) type ( Point [3]float64 Face []int Edge struct { pn1 int pn2 int fn1 int fn2 int cp Point } PointEx struct { p Point n int } ) func sumPoint(p1, p2 Point) Point { sp := Point{} for i := 0; i < 3; i++ { sp[i] = p1[i] + p2[i] } return sp } func mulPoint(p Point, m float64) Point { mp := Point{} for i := 0; i < 3; i++ { mp[i] = p[i] * m } return mp } func divPoint(p Point, d float64) Point { return mulPoint(p, 1.0/d) } func centerPoint(p1, p2 Point) Point { return divPoint(sumPoint(p1, p2), 2) } func getFacePoints(inputPoints []Point, inputFaces []Face) []Point { facePoints := make([]Point, len(inputFaces)) for i, currFace := range inputFaces { facePoint := Point{} for _, cpi := range currFace { currPoint := inputPoints[cpi] facePoint = sumPoint(facePoint, currPoint) } facePoint = divPoint(facePoint, float64(len(currFace))) facePoints[i] = facePoint } return facePoints } func getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge { var edges [][3]int for faceNum, face := range inputFaces { numPoints := len(face) for pointIndex := 0; pointIndex < numPoints; pointIndex++ { pointNum1 := face[pointIndex] var pointNum2 int if pointIndex < numPoints-1 { pointNum2 = face[pointIndex+1] } else { pointNum2 = face[0] } if pointNum1 > pointNum2 { pointNum1, pointNum2 = pointNum2, pointNum1 } edges = append(edges, [3]int{pointNum1, pointNum2, faceNum}) } } sort.Slice(edges, func(i, j int) bool { if edges[i][0] == edges[j][0] { if edges[i][1] == edges[j][1] { return edges[i][2] < edges[j][2] } return edges[i][1] < edges[j][1] } return edges[i][0] < edges[j][0] }) numEdges := len(edges) eIndex := 0 var mergedEdges [][4]int for eIndex < numEdges { e1 := edges[eIndex] if eIndex < numEdges-1 { e2 := edges[eIndex+1] if e1[0] == e2[0] && e1[1] == e2[1] { mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]}) eIndex += 2 } else { mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1}) eIndex++ } } else { mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1}) eIndex++ } } var edgesCenters []Edge for _, me := range mergedEdges { p1 := inputPoints[me[0]] p2 := inputPoints[me[1]] cp := centerPoint(p1, p2) edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp}) } return edgesCenters } func getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point { edgePoints := make([]Point, len(edgesFaces)) for i, edge := range edgesFaces { cp := edge.cp fp1 := facePoints[edge.fn1] var fp2 Point if edge.fn2 == -1 { fp2 = fp1 } else { fp2 = facePoints[edge.fn2] } cfp := centerPoint(fp1, fp2) edgePoints[i] = centerPoint(cp, cfp) } return edgePoints } func getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point { numPoints := len(inputPoints) tempPoints := make([]PointEx, numPoints) for faceNum := range inputFaces { fp := facePoints[faceNum] for _, pointNum := range inputFaces[faceNum] { tp := tempPoints[pointNum].p tempPoints[pointNum].p = sumPoint(tp, fp) tempPoints[pointNum].n++ } } avgFacePoints := make([]Point, numPoints) for i, tp := range tempPoints { avgFacePoints[i] = divPoint(tp.p, float64(tp.n)) } return avgFacePoints } func getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point { numPoints := len(inputPoints) tempPoints := make([]PointEx, numPoints) for _, edge := range edgesFaces { cp := edge.cp for _, pointNum := range []int{edge.pn1, edge.pn2} { tp := tempPoints[pointNum].p tempPoints[pointNum].p = sumPoint(tp, cp) tempPoints[pointNum].n++ } } avgMidEdges := make([]Point, len(tempPoints)) for i, tp := range tempPoints { avgMidEdges[i] = divPoint(tp.p, float64(tp.n)) } return avgMidEdges } func getPointsFaces(inputPoints []Point, inputFaces []Face) []int { numPoints := len(inputPoints) pointsFaces := make([]int, numPoints) for faceNum := range inputFaces { for _, pointNum := range inputFaces[faceNum] { pointsFaces[pointNum]++ } } return pointsFaces } func getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point { newPoints := make([]Point, len(inputPoints)) for pointNum := range inputPoints { n := float64(pointsFaces[pointNum]) m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n oldCoords := inputPoints[pointNum] p1 := mulPoint(oldCoords, m1) afp := avgFacePoints[pointNum] p2 := mulPoint(afp, m2) ame := avgMidEdges[pointNum] p3 := mulPoint(ame, m3) p4 := sumPoint(p1, p2) newPoints[pointNum] = sumPoint(p4, p3) } return newPoints } func switchNums(pointNums [2]int) [2]int { if pointNums[0] < pointNums[1] { return pointNums } return [2]int{pointNums[1], pointNums[0]} } func cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) { facePoints := getFacePoints(inputPoints, inputFaces) edgesFaces := getEdgesFaces(inputPoints, inputFaces) edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints) avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints) avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces) pointsFaces := getPointsFaces(inputPoints, inputFaces) newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges) var facePointNums []int nextPointNum := len(newPoints) for _, facePoint := range facePoints { newPoints = append(newPoints, facePoint) facePointNums = append(facePointNums, nextPointNum) nextPointNum++ } edgePointNums := make(map[[2]int]int) for edgeNum := range edgesFaces { pointNum1 := edgesFaces[edgeNum].pn1 pointNum2 := edgesFaces[edgeNum].pn2 edgePoint := edgePoints[edgeNum] newPoints = append(newPoints, edgePoint) edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum nextPointNum++ } var newFaces []Face for oldFaceNum, oldFace := range inputFaces { if len(oldFace) == 4 { a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3] facePointAbcd := facePointNums[oldFaceNum] edgePointAb := edgePointNums[switchNums([2]int{a, b})] edgePointDa := edgePointNums[switchNums([2]int{d, a})] edgePointBc := edgePointNums[switchNums([2]int{b, c})] edgePointCd := edgePointNums[switchNums([2]int{c, d})] newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa}) newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb}) newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc}) newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd}) } } return newPoints, newFaces } func main() { inputPoints := []Point{ {-1.0, 1.0, 1.0}, {-1.0, -1.0, 1.0}, {1.0, -1.0, 1.0}, {1.0, 1.0, 1.0}, {1.0, -1.0, -1.0}, {1.0, 1.0, -1.0}, {-1.0, -1.0, -1.0}, {-1.0, 1.0, -1.0}, } inputFaces := []Face{ {0, 1, 2, 3}, {3, 2, 4, 5}, {5, 4, 6, 7}, {7, 0, 3, 5}, {7, 6, 1, 0}, {6, 1, 2, 4}, } outputPoints := make([]Point, len(inputPoints)) outputFaces := make([]Face, len(inputFaces)) copy(outputPoints, inputPoints) copy(outputFaces, inputFaces) iterations := 1 for i := 0; i < iterations; i++ { outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces) } for _, p := range outputPoints { fmt.Printf("% .4f\n", p) } fmt.Println() for _, f := range outputFaces { fmt.Printf("%2d\n", f) } }
Maintain the same structure and functionality when rewriting this code in Go.
vertex face_point(face f) { int i; vertex v; if (!f->avg) { f->avg = vertex_new(); foreach(i, v, f->v) if (!i) f->avg->pos = v->pos; else vadd(f->avg->pos, v->pos); vdiv(f->avg->pos, len(f->v)); } return f->avg; } #define hole_edge(e) (len(e->f)==1) vertex edge_point(edge e) { int i; face f; if (!e->e_pt) { e->e_pt = vertex_new(); e->avg = e->v[0]->pos; vadd(e->avg, e->v[1]->pos); e->e_pt->pos = e->avg; if (!hole_edge(e)) { foreach (i, f, e->f) vadd(e->e_pt->pos, face_point(f)->pos); vdiv(e->e_pt->pos, 4); } else vdiv(e->e_pt->pos, 2); vdiv(e->avg, 2); } return e->e_pt; } #define hole_vertex(v) (len((v)->f) != len((v)->e)) vertex updated_point(vertex v) { int i, n = 0; edge e; face f; coord_t sum = {0, 0, 0}; if (v->v_new) return v->v_new; v->v_new = vertex_new(); if (hole_vertex(v)) { v->v_new->pos = v->pos; foreach(i, e, v->e) { if (!hole_edge(e)) continue; vadd(v->v_new->pos, edge_point(e)->pos); n++; } vdiv(v->v_new->pos, n + 1); } else { n = len(v->f); foreach(i, f, v->f) vadd(sum, face_point(f)->pos); foreach(i, e, v->e) vmadd(sum, edge_point(e)->pos, 2, sum); vdiv(sum, n); vmadd(sum, v->pos, n - 3, sum); vdiv(sum, n); v->v_new->pos = sum; } return v->v_new; } model catmull(model m) { int i, j, a, b, c, d; face f; vertex v, x; model nm = model_new(); foreach (i, f, m->f) { foreach(j, v, f->v) { _get_idx(a, updated_point(v)); _get_idx(b, edge_point(elem(f->e, (j + 1) % len(f->e)))); _get_idx(c, face_point(f)); _get_idx(d, edge_point(elem(f->e, j))); model_add_face(nm, 4, a, b, c, d); } } return nm; }
package main import ( "fmt" "sort" ) type ( Point [3]float64 Face []int Edge struct { pn1 int pn2 int fn1 int fn2 int cp Point } PointEx struct { p Point n int } ) func sumPoint(p1, p2 Point) Point { sp := Point{} for i := 0; i < 3; i++ { sp[i] = p1[i] + p2[i] } return sp } func mulPoint(p Point, m float64) Point { mp := Point{} for i := 0; i < 3; i++ { mp[i] = p[i] * m } return mp } func divPoint(p Point, d float64) Point { return mulPoint(p, 1.0/d) } func centerPoint(p1, p2 Point) Point { return divPoint(sumPoint(p1, p2), 2) } func getFacePoints(inputPoints []Point, inputFaces []Face) []Point { facePoints := make([]Point, len(inputFaces)) for i, currFace := range inputFaces { facePoint := Point{} for _, cpi := range currFace { currPoint := inputPoints[cpi] facePoint = sumPoint(facePoint, currPoint) } facePoint = divPoint(facePoint, float64(len(currFace))) facePoints[i] = facePoint } return facePoints } func getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge { var edges [][3]int for faceNum, face := range inputFaces { numPoints := len(face) for pointIndex := 0; pointIndex < numPoints; pointIndex++ { pointNum1 := face[pointIndex] var pointNum2 int if pointIndex < numPoints-1 { pointNum2 = face[pointIndex+1] } else { pointNum2 = face[0] } if pointNum1 > pointNum2 { pointNum1, pointNum2 = pointNum2, pointNum1 } edges = append(edges, [3]int{pointNum1, pointNum2, faceNum}) } } sort.Slice(edges, func(i, j int) bool { if edges[i][0] == edges[j][0] { if edges[i][1] == edges[j][1] { return edges[i][2] < edges[j][2] } return edges[i][1] < edges[j][1] } return edges[i][0] < edges[j][0] }) numEdges := len(edges) eIndex := 0 var mergedEdges [][4]int for eIndex < numEdges { e1 := edges[eIndex] if eIndex < numEdges-1 { e2 := edges[eIndex+1] if e1[0] == e2[0] && e1[1] == e2[1] { mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]}) eIndex += 2 } else { mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1}) eIndex++ } } else { mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1}) eIndex++ } } var edgesCenters []Edge for _, me := range mergedEdges { p1 := inputPoints[me[0]] p2 := inputPoints[me[1]] cp := centerPoint(p1, p2) edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp}) } return edgesCenters } func getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point { edgePoints := make([]Point, len(edgesFaces)) for i, edge := range edgesFaces { cp := edge.cp fp1 := facePoints[edge.fn1] var fp2 Point if edge.fn2 == -1 { fp2 = fp1 } else { fp2 = facePoints[edge.fn2] } cfp := centerPoint(fp1, fp2) edgePoints[i] = centerPoint(cp, cfp) } return edgePoints } func getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point { numPoints := len(inputPoints) tempPoints := make([]PointEx, numPoints) for faceNum := range inputFaces { fp := facePoints[faceNum] for _, pointNum := range inputFaces[faceNum] { tp := tempPoints[pointNum].p tempPoints[pointNum].p = sumPoint(tp, fp) tempPoints[pointNum].n++ } } avgFacePoints := make([]Point, numPoints) for i, tp := range tempPoints { avgFacePoints[i] = divPoint(tp.p, float64(tp.n)) } return avgFacePoints } func getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point { numPoints := len(inputPoints) tempPoints := make([]PointEx, numPoints) for _, edge := range edgesFaces { cp := edge.cp for _, pointNum := range []int{edge.pn1, edge.pn2} { tp := tempPoints[pointNum].p tempPoints[pointNum].p = sumPoint(tp, cp) tempPoints[pointNum].n++ } } avgMidEdges := make([]Point, len(tempPoints)) for i, tp := range tempPoints { avgMidEdges[i] = divPoint(tp.p, float64(tp.n)) } return avgMidEdges } func getPointsFaces(inputPoints []Point, inputFaces []Face) []int { numPoints := len(inputPoints) pointsFaces := make([]int, numPoints) for faceNum := range inputFaces { for _, pointNum := range inputFaces[faceNum] { pointsFaces[pointNum]++ } } return pointsFaces } func getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point { newPoints := make([]Point, len(inputPoints)) for pointNum := range inputPoints { n := float64(pointsFaces[pointNum]) m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n oldCoords := inputPoints[pointNum] p1 := mulPoint(oldCoords, m1) afp := avgFacePoints[pointNum] p2 := mulPoint(afp, m2) ame := avgMidEdges[pointNum] p3 := mulPoint(ame, m3) p4 := sumPoint(p1, p2) newPoints[pointNum] = sumPoint(p4, p3) } return newPoints } func switchNums(pointNums [2]int) [2]int { if pointNums[0] < pointNums[1] { return pointNums } return [2]int{pointNums[1], pointNums[0]} } func cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) { facePoints := getFacePoints(inputPoints, inputFaces) edgesFaces := getEdgesFaces(inputPoints, inputFaces) edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints) avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints) avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces) pointsFaces := getPointsFaces(inputPoints, inputFaces) newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges) var facePointNums []int nextPointNum := len(newPoints) for _, facePoint := range facePoints { newPoints = append(newPoints, facePoint) facePointNums = append(facePointNums, nextPointNum) nextPointNum++ } edgePointNums := make(map[[2]int]int) for edgeNum := range edgesFaces { pointNum1 := edgesFaces[edgeNum].pn1 pointNum2 := edgesFaces[edgeNum].pn2 edgePoint := edgePoints[edgeNum] newPoints = append(newPoints, edgePoint) edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum nextPointNum++ } var newFaces []Face for oldFaceNum, oldFace := range inputFaces { if len(oldFace) == 4 { a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3] facePointAbcd := facePointNums[oldFaceNum] edgePointAb := edgePointNums[switchNums([2]int{a, b})] edgePointDa := edgePointNums[switchNums([2]int{d, a})] edgePointBc := edgePointNums[switchNums([2]int{b, c})] edgePointCd := edgePointNums[switchNums([2]int{c, d})] newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa}) newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb}) newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc}) newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd}) } } return newPoints, newFaces } func main() { inputPoints := []Point{ {-1.0, 1.0, 1.0}, {-1.0, -1.0, 1.0}, {1.0, -1.0, 1.0}, {1.0, 1.0, 1.0}, {1.0, -1.0, -1.0}, {1.0, 1.0, -1.0}, {-1.0, -1.0, -1.0}, {-1.0, 1.0, -1.0}, } inputFaces := []Face{ {0, 1, 2, 3}, {3, 2, 4, 5}, {5, 4, 6, 7}, {7, 0, 3, 5}, {7, 6, 1, 0}, {6, 1, 2, 4}, } outputPoints := make([]Point, len(inputPoints)) outputFaces := make([]Face, len(inputFaces)) copy(outputPoints, inputPoints) copy(outputFaces, inputFaces) iterations := 1 for i := 0; i < iterations; i++ { outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces) } for _, p := range outputPoints { fmt.Printf("% .4f\n", p) } fmt.Println() for _, f := range outputFaces { fmt.Printf("%2d\n", f) } }
Convert this C snippet to Go and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } 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; } 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.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_list_authors_of_task_descriptions.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 ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strings" ) type authorNumber struct { author string number int } func main() { ex1 := `<li><a href="/wiki/(.*?)"` ex2 := `a href="/(wiki/User:|mw/index\.php\?title=User:|wiki/Special:Contributions/)([^"&]+)` re1 := regexp.MustCompile(ex1) re2 := regexp.MustCompile(ex2) url1 := "http: url2 := "http: urls := []string{url1, url2} var tasks []string for _, url := range urls { resp, _ := http.Get(url) body, _ := ioutil.ReadAll(resp.Body) matches := re1.FindAllStringSubmatch(string(body), -1) resp.Body.Close() for _, match := range matches { if !strings.HasPrefix(match[1], "Category:") { tasks = append(tasks, match[1]) } } } authors := make(map[string]int) for _, task := range tasks { page := fmt.Sprintf("http: resp, _ := http.Get(page) body, _ := ioutil.ReadAll(resp.Body) matches := re2.FindAllStringSubmatch(string(body), -1) resp.Body.Close() author := matches[len(matches)-1][2] author = strings.ReplaceAll(author, "_", " ") authors[author]++ } authorNumbers := make([]authorNumber, 0, len(authors)) for k, v := range authors { authorNumbers = append(authorNumbers, authorNumber{k, v}) } sort.Slice(authorNumbers, func(i, j int) bool { return authorNumbers[i].number > authorNumbers[j].number }) fmt.Println("Total tasks  :", len(tasks)) fmt.Println("Total authors :", len(authors)) fmt.Println("\nThe top 20 authors by number of tasks created are:\n") fmt.Println("Pos Tasks Author") fmt.Println("=== ===== ======") lastNumber, lastIndex := 0, -1 for i, authorNumber := range authorNumbers[0:20] { j := i if authorNumber.number == lastNumber { j = lastIndex } else { lastIndex = i lastNumber = authorNumber.number } fmt.Printf("%2d: %3d %s\n", j+1, authorNumber.number, authorNumber.author) } }
Convert this C block to Go, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } 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; } 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.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_list_authors_of_task_descriptions.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 ( "fmt" "io/ioutil" "net/http" "regexp" "sort" "strings" ) type authorNumber struct { author string number int } func main() { ex1 := `<li><a href="/wiki/(.*?)"` ex2 := `a href="/(wiki/User:|mw/index\.php\?title=User:|wiki/Special:Contributions/)([^"&]+)` re1 := regexp.MustCompile(ex1) re2 := regexp.MustCompile(ex2) url1 := "http: url2 := "http: urls := []string{url1, url2} var tasks []string for _, url := range urls { resp, _ := http.Get(url) body, _ := ioutil.ReadAll(resp.Body) matches := re1.FindAllStringSubmatch(string(body), -1) resp.Body.Close() for _, match := range matches { if !strings.HasPrefix(match[1], "Category:") { tasks = append(tasks, match[1]) } } } authors := make(map[string]int) for _, task := range tasks { page := fmt.Sprintf("http: resp, _ := http.Get(page) body, _ := ioutil.ReadAll(resp.Body) matches := re2.FindAllStringSubmatch(string(body), -1) resp.Body.Close() author := matches[len(matches)-1][2] author = strings.ReplaceAll(author, "_", " ") authors[author]++ } authorNumbers := make([]authorNumber, 0, len(authors)) for k, v := range authors { authorNumbers = append(authorNumbers, authorNumber{k, v}) } sort.Slice(authorNumbers, func(i, j int) bool { return authorNumbers[i].number > authorNumbers[j].number }) fmt.Println("Total tasks  :", len(tasks)) fmt.Println("Total authors :", len(authors)) fmt.Println("\nThe top 20 authors by number of tasks created are:\n") fmt.Println("Pos Tasks Author") fmt.Println("=== ===== ======") lastNumber, lastIndex := 0, -1 for i, authorNumber := range authorNumbers[0:20] { j := i if authorNumber.number == lastNumber { j = lastIndex } else { lastIndex = i lastNumber = authorNumber.number } fmt.Printf("%2d: %3d %s\n", j+1, authorNumber.number, authorNumber.author) } }
Write the same code in C as shown below in C++.
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_size = 5; const int diff = 6; const int array_size = max + diff; const int max_groups = 5; const int max_unsexy = 10; prime_sieve sieve(array_size); std::array<int, max_group_size> group_count{0}; vector<group_buffer> groups(max_group_size, group_buffer(max_groups)); int unsexy_count = 0; circular_buffer<int> unsexy_primes(max_unsexy); vector<int> group; for (int p = 2; p < max; ++p) { if (!sieve.is_prime(p)) continue; if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) { ++unsexy_count; unsexy_primes.push_back(p); } else { group.clear(); group.push_back(p); for (int group_size = 1; group_size < max_group_size; group_size++) { int next_p = p + group_size * diff; if (next_p >= max || !sieve.is_prime(next_p)) break; group.push_back(next_p); ++group_count[group_size]; groups[group_size].push_back(group); } } } for (int size = 1; size < max_group_size; ++size) { cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n'; cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":"; for (const vector<int>& group : groups[size]) { cout << " ("; for (size_t i = 0; i < group.size(); ++i) { if (i > 0) cout << ' '; cout << group[i]; } cout << ")"; } cout << "\n\n"; } cout << "number of unsexy primes is " << unsexy_count << '\n'; cout << "last " << unsexy_primes.size() << " unsexy primes:"; for (int prime : unsexy_primes) cout << ' ' << prime; cout << '\n'; return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #define TRUE 1 #define FALSE 0 typedef unsigned char bool; void sieve(bool *c, int limit) { int i, p = 3, p2; c[0] = TRUE; c[1] = TRUE; for (;;) { p2 = p * p; if (p2 >= limit) { break; } for (i = p2; i < limit; i += 2*p) { c[i] = TRUE; } for (;;) { p += 2; if (!c[p]) { break; } } } } void printHelper(const char *cat, int len, int lim, int n) { const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : ""; const char *verb = (len == 1) ? "is" : "are"; printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len); printf("The last %d %s:\n", n, verb); } void printArray(int *a, int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]"); } int main() { int i, ix, n, lim = 1000035; int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2; int pr = 0, tr = 0, qd = 0, qn = 0, un = 2; int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10; int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5]; int last_un[10]; bool *sv = calloc(lim - 1, sizeof(bool)); setlocale(LC_NUMERIC, ""); sieve(sv, lim); for (i = 3; i < lim; i += 2) { if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) { unsexy++; continue; } if (i < lim-6 && !sv[i] && !sv[i+6]) { pairs++; } else continue; if (i < lim-12 && !sv[i+12]) { trips++; } else continue; if (i < lim-18 && !sv[i+18]) { quads++; } else continue; if (i < lim-24 && !sv[i+24]) { quins++; } } if (pairs < lpr) lpr = pairs; if (trips < ltr) ltr = trips; if (quads < lqd) lqd = quads; if (quins < lqn) lqn = quins; if (unsexy < lun) lun = unsexy; for (i = 3; i < lim; i += 2) { if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) { un++; if (un > unsexy - lun) { last_un[un + lun - 1 - unsexy] = i; } continue; } if (i < lim-6 && !sv[i] && !sv[i+6]) { pr++; if (pr > pairs - lpr) { ix = pr + lpr - 1 - pairs; last_pr[ix][0] = i; last_pr[ix][1] = i + 6; } } else continue; if (i < lim-12 && !sv[i+12]) { tr++; if (tr > trips - ltr) { ix = tr + ltr - 1 - trips; last_tr[ix][0] = i; last_tr[ix][1] = i + 6; last_tr[ix][2] = i + 12; } } else continue; if (i < lim-18 && !sv[i+18]) { qd++; if (qd > quads - lqd) { ix = qd + lqd - 1 - quads; last_qd[ix][0] = i; last_qd[ix][1] = i + 6; last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18; } } else continue; if (i < lim-24 && !sv[i+24]) { qn++; if (qn > quins - lqn) { ix = qn + lqn - 1 - quins; last_qn[ix][0] = i; last_qn[ix][1] = i + 6; last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18; last_qn[ix][4] = i + 24; } } } printHelper("pairs", pairs, lim, lpr); printf(" ["); for (i = 0; i < lpr; ++i) { printArray(last_pr[i], 2); printf("\b] "); } printf("\b]\n\n"); printHelper("triplets", trips, lim, ltr); printf(" ["); for (i = 0; i < ltr; ++i) { printArray(last_tr[i], 3); printf("\b] "); } printf("\b]\n\n"); printHelper("quadruplets", quads, lim, lqd); printf(" ["); for (i = 0; i < lqd; ++i) { printArray(last_qd[i], 4); printf("\b] "); } printf("\b]\n\n"); printHelper("quintuplets", quins, lim, lqn); printf(" ["); for (i = 0; i < lqn; ++i) { printArray(last_qn[i], 5); printf("\b] "); } printf("\b]\n\n"); printHelper("unsexy primes", unsexy, lim, lun); printf(" ["); printArray(last_un, lun); printf("\b]\n"); free(sv); return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
#include <stdlib.h> #include <string.h> #include <stdio.h> double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf("%g ", y[i]); putchar('\n'); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
Ensure the translated C code behaves exactly like the original C++ snippet.
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
Please provide an equivalent version of this C++ code in C.
int a[5]; a[0] = 1; int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; #include <string> std::string strings[4];
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) int ar[10]; ar[0] = 1; ar[1] = 2; int* p; for (p=ar; p<(ar+cSize(ar)); p++) { printf("%d\n",*p); }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
Port the following code from C++ to C with equivalent syntax and logic.
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Generate an equivalent C version of this C++ code.
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
#include <stdio.h> int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
Change the following C++ code into C without altering its purpose.
#include <array> #include <cmath> #include <iomanip> #include <iostream> double ByVaccaSeries(int numTerms) { double gamma = 0; size_t next = 4; for(double numerator = 1; numerator < numTerms; ++numerator) { double delta = 0; for(size_t denominator = next/2; denominator < next; denominator+=2) { delta += 1.0/denominator - 1.0/(denominator + 1); } gamma += numerator * delta; next *= 2; } return gamma; } double ByEulersMethod() { const std::array<double, 8> B2 {1.0, 1.0/6, -1.0/30, 1.0/42, -1.0/30, 5.0/66, -691.0/2730, 7.0/6}; const int n = 10; const double h = [] { double sum = 1; for (int k = 2; k <= n; k++) { sum += 1.0 / k; } return sum - log(n); }(); double a = -1.0 / (2*n); double r = 1; for (int k = 1; k < ssize(B2); k++) { r *= n * n; a += B2[k] / (2*k * r); } return h + a; } int main() { std::cout << std::setprecision(16) << "Vacca series: " << ByVaccaSeries(32); std::cout << std::setprecision(16) << "\nEulers method: " << ByEulersMethod(); }
#include <math.h> #include <stdio.h> #define eps 1e-6 int main(void) { double a, b, h, n2, r, u, v; int k, k2, m, n; printf("From the definition, err. 3e-10\n"); n = 400; h = 1; for (k = 2; k <= n; k++) { h += 1.0 / k; } a = log(n +.5 + 1.0 / (24*n)); printf("Hn  %.16f\n", h); printf("gamma %.16f\nk = %d\n\n", h - a, n); printf("Sweeney, 1963, err. idem\n"); n = 21; double s[] = {0, n}; r = n; k = 1; do { k += 1; r *= (double) n / k; s[k & 1] += r / k; } while (r > eps); printf("gamma %.16f\nk = %d\n\n", s[1] - s[0] - log(n), k); printf("Bailey, 1988\n"); n = 5; a = 1; h = 1; n2 = pow(2,n); r = 1; k = 1; do { k += 1; r *= n2 / k; h += 1.0 / k; b = a; a += r * h; } while (fabs(b - a) > eps); a *= n2 / exp(n2); printf("gamma %.16f\nk = %d\n\n", a - n * log(2), k); printf("Brent-McMillan, 1980\n"); n = 13; a = -log(n); b = 1; u = a; v = b; n2 = n * n; k2 = 0; k = 0; do { k2 += 2*k + 1; k += 1; a *= n2 / k; b *= n2 / k2; a = (a + b) / k; u += a; v += b; } while (fabs(a) > eps); printf("gamma %.16f\nk = %d\n\n", u / v, k); printf("How Euler did it in 1735\n"); double B2[] = {1.0,1.0/6,-1.0/30,1.0/42,-1.0/30,\ 5.0/66,-691.0/2730,7.0/6,-3617.0/510,43867.0/798}; m = 7; if (m > 9) return(0); n = 10; h = 1; for (k = 2; k <= n; k++) { h += 1.0 / k; } printf("Hn  %.16f\n", h); h -= log(n); printf(" -ln %.16f\n", h); a = -1.0 / (2*n); n2 = n * n; r = 1; for (k = 1; k <= m; k++) { r *= n2; a += B2[k] / (2*k * r); } printf("err  %.16f\ngamma %.16f\nk = %d", a, h + a, n + m); printf("\n\nC = 0.57721566490153286...\n"); }
Change the following C++ code into C without altering its purpose.
#include <iostream> #include <algorithm> #include <vector> #include <sstream> #include <iterator> using namespace std; class myTuple { public: void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; } bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; } string second() { return t.second; } private: pair<pair<int, int>, string> t; }; class discordian { public: discordian() { myTuple t; t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t ); t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t ); t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t ); t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t ); t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t ); t.set( 8, 12, "Afflux" ); holyday.push_back( t ); seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" ); seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" ); wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" ); wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" ); } void convert( int d, int m, int y ) { if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { cout << "\nThis is not a date!"; return; } vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); int dd = d, day, wday, sea, yr = y + 1166; for( int x = 1; x < m; x++ ) dd += getMaxDay( x, 1 ); day = dd % 73; if( !day ) day = 73; wday = dd % 5; sea = ( dd - 1 ) / 73; if( d == 29 && m == 2 && isLeap( y ) ) { cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr; return; } cout << wdays[wday] << " " << seasons[sea] << " " << day; if( day > 10 && day < 14 ) cout << "th"; else switch( day % 10) { case 1: cout << "st"; break; case 2: cout << "nd"; break; case 3: cout << "rd"; break; default: cout << "th"; } cout << ", Year of Our Lady of Discord " << yr; if( f != holyday.end() ) cout << " - " << ( *f ).second(); } private: int getMaxDay( int m, int y ) { int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; } bool isLeap( int y ) { bool l = false; if( !( y % 4 ) ) { if( y % 100 ) l = true; else if( !( y % 400 ) ) l = true; } return l; } vector<myTuple> holyday; vector<string> seasons, wdays; }; int main( int argc, char* argv[] ) { string date; discordian disc; while( true ) { cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break; if( date.length() == 10 ) { istringstream iss( date ); vector<string> vc; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) ); disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); cout << "\n\n\n"; } else cout << "\nIs this a date?!\n\n"; } return 0; }
#include <stdlib.h> #include <stdio.h> #include <time.h> #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange") #define season( x ) ((x) == 0 ? "Chaos" :\ (x) == 1 ? "Discord" :\ (x) == 2 ? "Confusion" :\ (x) == 3 ? "Bureaucracy" :\ "The Aftermath") #define date( x ) ((x)%73 == 0 ? 73 : (x)%73) #define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100)) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = malloc( 100 * sizeof( char ) ); if( leap_year( y ) ){ if( d == 60 ){ sprintf( result, "St. Tib's Day, YOLD %d", dyear ); return result; } else if( d >= 60 ){ -- d; } } sprintf( result, "%s, %s %d, YOLD %d", day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear ); return result; } int day_of_year( int y, int m, int d ){ int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; for( ; m > 1; m -- ){ d += month_lengths[ m - 2 ]; if( m == 3 && leap_year( y ) ){ ++ d; } } return d; } int main( int argc, char * argv[] ){ time_t now; struct tm * now_time; int year, doy; if( argc == 1 ){ now = time( NULL ); now_time = localtime( &now ); year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1; } else if( argc == 4 ){ year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) ); } char * result = ddate( year, doy ); puts( result ); free( result ); return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
Write the same algorithm in C as shown in this C++ implementation.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
Convert this C++ block to C, preserving its control flow and logic.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
Generate a C translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
Change the following C++ code into C without altering its purpose.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
Produce a functionally identical C code for the snippet given in C++.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
Rewrite this program in C while keeping its functionality equivalent to the C++ version.
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
Produce a language-to-language conversion: from C++ to C, same semantics.
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
#include <stdio.h> int main() { const char *extra = "little"; printf("Mary had a %s lamb.\n", extra); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <iostream> #include <vector> #include <stack> #include <iterator> #include <algorithm> #include <cassert> template <class E> struct pile_less { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() < pile2.top(); } }; template <class E> struct pile_greater { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() > pile2.top(); } }; template <class Iterator> void patience_sort(Iterator first, Iterator last) { typedef typename std::iterator_traits<Iterator>::value_type E; typedef std::stack<E> Pile; std::vector<Pile> piles; for (Iterator it = first; it != last; it++) { E& x = *it; Pile newPile; newPile.push(x); typename std::vector<Pile>::iterator i = std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>()); if (i != piles.end()) i->push(x); else piles.push_back(newPile); } std::make_heap(piles.begin(), piles.end(), pile_greater<E>()); for (Iterator it = first; it != last; it++) { std::pop_heap(piles.begin(), piles.end(), pile_greater<E>()); Pile &smallPile = piles.back(); *it = smallPile.top(); smallPile.pop(); if (smallPile.empty()) piles.pop_back(); else std::push_heap(piles.begin(), piles.end(), pile_greater<E>()); } assert(piles.empty()); } int main() { int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1}; patience_sort(a, a+sizeof(a)/sizeof(*a)); std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; return 0; }
#include<stdlib.h> #include<stdio.h> int* patienceSort(int* arr,int size){ int decks[size][size],i,j,min,pickedRow; int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int)); for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){ decks[j][count[j]] = arr[i]; count[j]++; break; } } } min = decks[0][count[0]-1]; pickedRow = 0; for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]>0 && decks[j][count[j]-1]<min){ min = decks[j][count[j]-1]; pickedRow = j; } } sortedArr[i] = min; count[pickedRow]--; for(j=0;j<size;j++) if(count[j]>0){ min = decks[j][count[j]-1]; pickedRow = j; break; } } free(count); free(decks); return sortedArr; } int main(int argC,char* argV[]) { int *arr, *sortedArr, i; if(argC==0) printf("Usage : %s <integers to be sorted separated by space>"); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<=argC;i++) arr[i-1] = atoi(argV[i]); sortedArr = patienceSort(arr,argC-1); for(i=0;i<argC-1;i++) printf("%d ",sortedArr[i]); } return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
Please provide an equivalent version of this C++ code in C.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } int main() { const unsigned int limit = 100; std::cout << "The first " << limit << " tau numbers are:\n"; unsigned int count = 0; for (unsigned int n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { std::cout << std::setw(6) << n; ++count; if (count % 10 == 0) std::cout << '\n'; } } }
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int count = 0; unsigned int n; printf("The first %d tau numbers are:\n", limit); for (n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { printf("%6d", n); ++count; if (count % 10 == 0) { printf("\n"); } } } return 0; }
Change the following C++ code into C without altering its purpose.
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } return sum; } double det(double *in, int n, int perm) { double *m[n]; for (int i = 0; i < n; i++) m[i] = in + (n * i); return det_in(m, n, perm); } int main(void) { double x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; printf("det: %14.12g\n", det(x, 5, 0)); printf("perm: %14.12g\n", det(x, 5, 1)); return 0; }
Convert this C++ snippet to C and keep its semantics consistent.
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } return sum; } double det(double *in, int n, int perm) { double *m[n]; for (int i = 0; i < n; i++) m[i] = in + (n * i); return det_in(m, n, perm); } int main(void) { double x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; printf("det: %14.12g\n", det(x, 5, 0)); printf("perm: %14.12g\n", det(x, 5, 1)); return 0; }
Write the same code in C as shown below in C++.
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } return sum; } double det(double *in, int n, int perm) { double *m[n]; for (int i = 0; i < n; i++) m[i] = in + (n * i); return det_in(m, n, perm); } int main(void) { double x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; printf("det: %14.12g\n", det(x, 5, 0)); printf("perm: %14.12g\n", det(x, 5, 1)); return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; } int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\n"; }
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <gmp.h> mpz_t* partition(uint64_t n) { mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t)); mpz_init_set_ui(pn[0], 1); mpz_init_set_ui(pn[1], 1); for (uint64_t i = 2; i < n + 2; i ++) { mpz_init(pn[i]); for (uint64_t k = 1, penta; ; k++) { penta = k * (3 * k - 1) >> 1; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); penta += k; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); } } mpz_t *tmp = &pn[n + 1]; for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]); free(pn); return tmp; } int main(int argc, char const *argv[]) { clock_t start = clock(); mpz_t *p = partition(6666); gmp_printf("%Zd\n", p); printf("Elapsed time: %.04f seconds\n", (double)(clock() - start) / (double)CLOCKS_PER_SEC); return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string> #include <unistd.h> enum cell_type { none, wire, head, tail }; class display { public: display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors); ~display() { ggiClose(visual); ggiExit(); } void flush(); bool keypressed() { return ggiKbhit(visual); } void clear(); void putpixel(int x, int y, cell_type c); private: ggi_visual_t visual; int size_x, size_y; int pixel_size_x, pixel_size_y; ggi_pixel pixels[4]; }; display::display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors): pixel_size_x(pixsizex), pixel_size_y(pixsizey) { if (ggiInit() < 0) { std::cerr << "couldn't open ggi\n"; exit(1); } visual = ggiOpen(NULL); if (!visual) { ggiPanic("couldn't open visual\n"); } ggi_mode mode; if (ggiCheckGraphMode(visual, sizex, sizey, GGI_AUTO, GGI_AUTO, GT_4BIT, &mode) != 0) { if (GT_DEPTH(mode.graphtype) < 2) ggiPanic("low-color displays are not supported!\n"); } if (ggiSetMode(visual, &mode) != 0) { ggiPanic("couldn't set graph mode\n"); } ggiAddFlags(visual, GGIFLAG_ASYNC); size_x = mode.virt.x; size_y = mode.virt.y; for (int i = 0; i < 4; ++i) pixels[i] = ggiMapColor(visual, colors+i); } void display::flush() { ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual)); ggiFlush(visual); ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); } void display::clear() { ggiSetGCForeground(visual, pixels[0]); ggiDrawBox(visual, 0, 0, size_x, size_y); } void display::putpixel(int x, int y, cell_type cell) { ggiSetGCForeground(visual, pixels[cell]); ggiDrawBox(visual, x*pixel_size_x, y*pixel_size_y, pixel_size_x, pixel_size_y); } class wireworld { public: void set(int posx, int posy, cell_type type); void draw(display& destination); void step(); private: typedef std::pair<int, int> position; typedef std::set<position> position_set; typedef position_set::iterator positer; position_set wires, heads, tails; }; void wireworld::set(int posx, int posy, cell_type type) { position p(posx, posy); wires.erase(p); heads.erase(p); tails.erase(p); switch(type) { case head: heads.insert(p); break; case tail: tails.insert(p); break; case wire: wires.insert(p); break; } } void wireworld::draw(display& destination) { destination.clear(); for (positer i = heads.begin(); i != heads.end(); ++i) destination.putpixel(i->first, i->second, head); for (positer i = tails.begin(); i != tails.end(); ++i) destination.putpixel(i->first, i->second, tail); for (positer i = wires.begin(); i != wires.end(); ++i) destination.putpixel(i->first, i->second, wire); destination.flush(); } void wireworld::step() { std::map<position, int> new_heads; for (positer i = heads.begin(); i != heads.end(); ++i) for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) { position pos(i->first + dx, i->second + dy); if (wires.count(pos)) new_heads[pos]++; } wires.insert(tails.begin(), tails.end()); tails.swap(heads); heads.clear(); for (std::map<position, int>::iterator i = new_heads.begin(); i != new_heads.end(); ++i) { if (i->second < 3) { wires.erase(i->first); heads.insert(i->first); } } } ggi_color colors[4] = {{ 0x0000, 0x0000, 0x0000 }, { 0x8000, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0x0000 }, { 0xffff, 0x0000, 0x0000 }}; int main(int argc, char* argv[]) { int display_x = 800; int display_y = 600; int pixel_x = 5; int pixel_y = 5; if (argc < 2) { std::cerr << "No file name given!\n"; return 1; } std::ifstream f(argv[1]); wireworld w; std::string line; int line_number = 0; while (std::getline(f, line)) { for (int col = 0; col < line.size(); ++col) { switch (line[col]) { case 'h': case 'H': w.set(col, line_number, head); break; case 't': case 'T': w.set(col, line_number, tail); break; case 'w': case 'W': case '.': w.set(col, line_number, wire); break; default: std::cerr << "unrecognized character: " << line[col] << "\n"; return 1; case ' ': ; } } ++line_number; } display d(display_x, display_y, pixel_x, pixel_y, colors); w.draw(d); while (!d.keypressed()) { usleep(100000); w.step(); w.draw(d); } std::cout << std::endl; }
#define ANIMATE_VT100_POSIX #include <stdio.h> #include <string.h> #ifdef ANIMATE_VT100_POSIX #include <time.h> #endif char world_7x14[2][512] = { { "+-----------+\n" "|tH.........|\n" "|. . |\n" "| ... |\n" "|. . |\n" "|Ht.. ......|\n" "+-----------+\n" } }; void next_world(const char *in, char *out, int w, int h) { int i; for (i = 0; i < w*h; i++) { switch (in[i]) { case ' ': out[i] = ' '; break; case 't': out[i] = '.'; break; case 'H': out[i] = 't'; break; case '.': { int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') + (in[i-1] == 'H') + (in[i+1] == 'H') + (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H'); out[i] = (hc == 1 || hc == 2) ? 'H' : '.'; break; } default: out[i] = in[i]; } } out[i] = in[i]; } int main() { int f; for (f = 0; ; f = 1 - f) { puts(world_7x14[f]); next_world(world_7x14[f], world_7x14[1-f], 14, 7); #ifdef ANIMATE_VT100_POSIX printf("\x1b[%dA", 8); printf("\x1b[%dD", 14); { static const struct timespec ts = { 0, 100000000 }; nanosleep(&ts, 0); } #endif } return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <algorithm> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits> using namespace std; const double epsilon = numeric_limits<float>().epsilon(); const numeric_limits<double> DOUBLE; const double MIN = DOUBLE.min(); const double MAX = DOUBLE.max(); struct Point { const double x, y; }; struct Edge { const Point a, b; bool operator()(const Point& p) const { if (a.y > b.y) return Edge{ b, a }(p); if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon }); if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false; if (p.x < min(a.x, b.x)) return true; auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX; auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX; return blue >= red; } }; struct Figure { const string name; const initializer_list<Edge> edges; bool contains(const Point& p) const { auto c = 0; for (auto e : edges) if (e(p)) c++; return c % 2 != 0; } template<unsigned char W = 3> void check(const initializer_list<Point>& points, ostream& os) const { os << "Is point inside figure " << name << '?' << endl; for (auto p : points) os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl; os << endl; } }; int main() { const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} }; const Figure square = { "Square", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} } }; const Figure square_hole = { "Square hole", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}}, {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}} } }; const Figure strange = { "Strange", { {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}}, {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}} } }; const Figure exagon = { "Exagon", { {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}}, {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}} } }; for(auto f : {square, square_hole, strange, exagon}) f.check(points, cout); return EXIT_SUCCESS; }
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double x, y; } vec; typedef struct { int n; vec* v; } polygon_t, *polygon; #define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;} #define BIN_S(op, r) double v##op(vec a, vec b){ return r; } BIN_V(sub, a.x - b.x, a.y - b.y); BIN_V(add, a.x + b.x, a.y + b.y); BIN_S(dot, a.x * b.x + a.y * b.y); BIN_S(cross, a.x * b.y - a.y * b.x); vec vmadd(vec a, double s, vec b) { vec c; c.x = a.x + s * b.x; c.y = a.y + s * b.y; return c; } int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect) { vec dx = vsub(x1, x0), dy = vsub(y1, y0); double d = vcross(dy, dx), a; if (!d) return 0; a = (vcross(x0, dx) - vcross(y0, dx)) / d; if (sect) *sect = vmadd(y0, a, dy); if (a < -tol || a > 1 + tol) return -1; if (a < tol || a > 1 - tol) return 0; a = (vcross(x0, dy) - vcross(y0, dy)) / d; if (a < 0 || a > 1) return -1; return 1; } double dist(vec x, vec y0, vec y1, double tol) { vec dy = vsub(y1, y0); vec x1, s; int r; x1.x = x.x + dy.y; x1.y = x.y - dy.x; r = intersect(x, x1, y0, y1, tol, &s); if (r == -1) return HUGE_VAL; s = vsub(s, x); return sqrt(vdot(s, s)); } #define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++) int inside(vec v, polygon p, double tol) { int i, k, crosses, intersectResult; vec *pv; double min_x, max_x, min_y, max_y; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; min_x = dist(v, p->v[i], p->v[k], tol); if (min_x < tol) return 0; } min_x = max_x = p->v[0].x; min_y = max_y = p->v[1].y; for_v(i, pv, p) { if (pv->x > max_x) max_x = pv->x; if (pv->x < min_x) min_x = pv->x; if (pv->y > max_y) max_y = pv->y; if (pv->y < min_y) min_y = pv->y; } if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y) return -1; max_x -= min_x; max_x *= 2; max_y -= min_y; max_y *= 2; max_x += max_y; vec e; while (1) { crosses = 0; e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x; e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0); if (!intersectResult) break; if (intersectResult == 1) crosses++; } if (i == p->n) break; } return (crosses & 1) ? 1 : -1; } int main() { vec vsq[] = { {0,0}, {10,0}, {10,10}, {0,10}, {2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}}; polygon_t sq = { 4, vsq }, sq_hole = { 8, vsq }; vec c = { 10, 5 }; vec d = { 5, 5 }; printf("%d\n", inside(c, &sq, 1e-10)); printf("%d\n", inside(c, &sq_hole, 1e-10)); printf("%d\n", inside(d, &sq, 1e-10)); printf("%d\n", inside(d, &sq_hole, 1e-10)); return 0; }
Write the same code in C as shown below in C++.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
#include <stdio.h> #include <math.h> #define C 7 typedef struct { double x, y; } pt; pt zero(void) { return (pt){ INFINITY, INFINITY }; } int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; } pt neg(pt p) { return (pt){ p.x, -p.y }; } pt dbl(pt p) { if (is_zero(p)) return p; pt r; double L = (3 * p.x * p.x) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
Please provide an equivalent version of this C++ code in C.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
#include <stdio.h> #include <math.h> #define C 7 typedef struct { double x, y; } pt; pt zero(void) { return (pt){ INFINITY, INFINITY }; } int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; } pt neg(pt p) { return (pt){ p.x, -p.y }; } pt dbl(pt p) { if (is_zero(p)) return p; pt r; double L = (3 * p.x * p.x) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
Write the same code in C as shown below in C++.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
#include <stdio.h> #include <math.h> #define C 7 typedef struct { double x, y; } pt; pt zero(void) { return (pt){ INFINITY, INFINITY }; } int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; } pt neg(pt p) { return (pt){ p.x, -p.y }; } pt dbl(pt p) { if (is_zero(p)) return p; pt r; double L = (3 * p.x * p.x) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
Write a version of this C++ function in C with identical behavior.
#include <iostream> #include <string> int countSubstring(const std::string& str, const std::string& sub) { if (sub.length() == 0) return 0; int count = 0; for (size_t offset = str.find(sub); offset != std::string::npos; offset = str.find(sub, offset + sub.length())) { ++count; } return count; } int main() { std::cout << countSubstring("the three truths", "th") << '\n'; std::cout << countSubstring("ababababab", "abab") << '\n'; std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n'; return 0; }
#include <stdio.h> #include <string.h> int match(const char *s, const char *p, int overlap) { int c = 0, l = strlen(p); while (*s != '\0') { if (strncmp(s++, p, l)) continue; if (!overlap) s += l - 1; c++; } return c; } int main() { printf("%d\n", match("the three truths", "th", 0)); printf("overlap:%d\n", match("abababababa", "aba", 1)); printf("not: %d\n", match("abababababa", "aba", 0)); return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
Produce a language-to-language conversion: from C++ to C, same semantics.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
Write the same algorithm in C as shown in this C++ implementation.
#include <algorithm> #include <iostream> #include <sstream> #include <string> template <typename T> void demo_compare(const T &a, const T &b, const std::string &semantically) { std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") << "exactly " << semantically << " equal." << std::endl; std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ") << semantically << "inequal." << std::endl; std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically << " ordered before " << b << '.' << std::endl; std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically << " ordered after " << b << '.' << std::endl; } int main(int argc, char *argv[]) { std::string a((argc > 1) ? argv[1] : "1.2.Foo"); std::string b((argc > 2) ? argv[2] : "1.3.Bar"); demo_compare<std::string>(a, b, "lexically"); std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); demo_compare<std::string>(a, b, "lexically"); double numA, numB; std::istringstream(a) >> numA; std::istringstream(b) >> numB; demo_compare<double>(numA, numB, "numerically"); return (a == b); }
if (strcmp(a,b)) action_on_equality();
Port the provided C++ code into C while preserving the original functionality.
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
#include <stdio.h> #include <string.h> #include <math.h> #define N 32 #define N2 (N * (N - 1) / 2) #define STEP .05 double xval[N], t_sin[N], t_cos[N], t_tan[N]; double r_sin[N2], r_cos[N2], r_tan[N2]; double rho(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } #define i_sin(x) thiele(t_sin, xval, r_sin, x, 0) #define i_cos(x) thiele(t_cos, xval, r_cos, x, 0) #define i_tan(x) thiele(t_tan, xval, r_tan, x, 0) int main() { int i; for (i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = 0/0.; printf("%16.14f\n", 6 * i_sin(.5)); printf("%16.14f\n", 3 * i_cos(.5)); printf("%16.14f\n", 4 * i_tan(1.)); return 0; }
Port the provided C++ code into C while preserving the original functionality.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void print_headings() { printf("%2s", "N"); printf(" %10s", "Length"); printf(" %-20s", "Entropy"); printf(" %-40s", "Word"); printf("\n"); } double calculate_entropy(int ones, int zeros) { double result = 0; int total = ones + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void print_headings() { printf("%2s", "N"); printf(" %10s", "Length"); printf(" %-20s", "Entropy"); printf(" %-40s", "Word"); printf("\n"); } double calculate_entropy(int ones, int zeros) { double result = 0; int total = ones + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
Transform the following C++ implementation into C, maintaining the same output and logic.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void print_headings() { printf("%2s", "N"); printf(" %10s", "Length"); printf(" %-20s", "Entropy"); printf(" %-40s", "Word"); printf("\n"); } double calculate_entropy(int ones, int zeros) { double result = 0; int total = ones + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
Write a version of this C++ function in C with identical behavior.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(double a) { return normalize<double>(a, 400); } inline double m2m(double a) { return normalize<double>(a, 6400); } inline double r2r(double a) { return normalize<double>(a, 2*M_PI); } double d2g(double a) { return g2g(a * 10 / 9); } double d2m(double a) { return m2m(a * 160 / 9); } double d2r(double a) { return r2r(a * M_PI / 180); } double g2d(double a) { return d2d(a * 9 / 10); } double g2m(double a) { return m2m(a * 16); } double g2r(double a) { return r2r(a * M_PI / 200); } double m2d(double a) { return d2d(a * 9 / 160); } double m2g(double a) { return g2g(a / 16); } double m2r(double a) { return r2r(a * M_PI / 3200); } double r2d(double a) { return d2d(a * 180 / M_PI); } double r2g(double a) { return g2g(a * 200 / M_PI); } double r2m(double a) { return m2m(a * 3200 / M_PI); } void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) { using namespace std; ostringstream out; out << " ┌───────────────────┐\n"; out << " │ " << setw(17) << s << " │\n"; out << "┌─────────────────┼───────────────────┤\n"; for (double i : values) out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n"; out << "└─────────────────┴───────────────────┘\n"; auto str = out.str(); boost::algorithm::replace_all(str, ".000000", " "); cout << str; } int main() { std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }; print(values, "normalized (deg)", d2d); print(values, "normalized (grad)", g2g); print(values, "normalized (mil)", m2m); print(values, "normalized (rad)", r2r); print(values, "deg -> grad ", d2g); print(values, "deg -> mil ", d2m); print(values, "deg -> rad ", d2r); print(values, "grad -> deg ", g2d); print(values, "grad -> mil ", g2m); print(values, "grad -> rad ", g2r); print(values, "mil -> deg ", m2d); print(values, "mil -> grad ", m2g); print(values, "mil -> rad ", m2r); print(values, "rad -> deg ", r2d); print(values, "rad -> grad ", r2g); print(values, "rad -> mil ", r2m); return 0; }
#define PI 3.141592653589793 #define TWO_PI 6.283185307179586 double normalize2deg(double a) { while (a < 0) a += 360; while (a >= 360) a -= 360; return a; } double normalize2grad(double a) { while (a < 0) a += 400; while (a >= 400) a -= 400; return a; } double normalize2mil(double a) { while (a < 0) a += 6400; while (a >= 6400) a -= 6400; return a; } double normalize2rad(double a) { while (a < 0) a += TWO_PI; while (a >= TWO_PI) a -= TWO_PI; return a; } double deg2grad(double a) {return a * 10 / 9;} double deg2mil(double a) {return a * 160 / 9;} double deg2rad(double a) {return a * PI / 180;} double grad2deg(double a) {return a * 9 / 10;} double grad2mil(double a) {return a * 16;} double grad2rad(double a) {return a * PI / 200;} double mil2deg(double a) {return a * 9 / 160;} double mil2grad(double a) {return a / 16;} double mil2rad(double a) {return a * PI / 3200;} double rad2deg(double a) {return a * 180 / PI;} double rad2grad(double a) {return a * 200 / PI;} double rad2mil(double a) {return a * 3200 / PI;}
Write the same algorithm in C as shown in this C++ implementation.
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
#include <stdio.h> int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue; while (pos > 0 && names[0][--pos] != sep); return pos; } } return 0; } int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } } return good; }
#include <stdlib.h> #include <stdio.h> #include <math.h> inline int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; } inline int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; } int check(int (*gen)(), int n, int cnt, double delta) { int i = cnt, *bins = calloc(sizeof(int), n); double ratio; while (i--) bins[gen() - 1]++; for (i = 0; i < n; i++) { ratio = bins[i] * n / (double)cnt - 1; if (ratio > -delta && ratio < delta) continue; printf("bin %d out of range: %d (%g%% vs %g%%), ", i + 1, bins[i], ratio * 100, delta * 100); break; } free(bins); return i == n; } int main() { int cnt = 1; while ((cnt *= 10) <= 1000000) { printf("Count = %d: ", cnt); printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n"); } return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct stirling_cache_tag { int max; int* values; } stirling_cache; int stirling_number2(stirling_cache* sc, int n, int k) { if (k == n) return 1; if (k == 0 || k > n || n > sc->max) return 0; return sc->values[n*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct stirling_cache_tag { int max; int* values; } stirling_cache; int stirling_number2(stirling_cache* sc, int n, int k) { if (k == n) return 1; if (k == 0 || k > n || n > sc->max) return 0; return sc->values[n*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
Write a version of this C++ function in C with identical behavior.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
Port the following code from C++ to C with equivalent syntax and logic.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
Convert this C++ snippet to C and keep its semantics consistent.
#include <string> int main() { int* p; p = new int; delete p; p = new int(2); delete p; std::string* p2; p2 = new std::string; delete p2; p = new int[10]; delete[] p; p2 = new std::string[10]; delete[] p2; }
#include <stdlib.h> #define SIZEOF_MEMB (sizeof(int)) #define NMEMB 100 int main() { int *ints = malloc(SIZEOF_MEMB*NMEMB); ints = realloc(ints, sizeof(int)*(NMEMB+1)); int *int2 = calloc(NMEMB, SIZEOF_MEMB); free(ints); free(int2); return 0; }
Translate this program into C but keep the logic exactly as in C++.
#include <windows.h> #include <iostream> #include <string> using namespace std; enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; class ttt { public: ttt() { _p = rand() % 2; reset(); } void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove(); drawGrid(); res = checkVictory(); if( res != None ) break; ++_p %= 2; } if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!"; cout << endl << endl; string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return; ++_p %= 2; reset(); } } private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; } void drawGrid() { system( "cls" ); COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl; int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; } c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); } int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } } int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw; return None; } void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 ); if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; } _field[m - 1] = Human; } void getComputerMove() { int move = 0; do{ move = rand() % 9; } while( _field[move] != None ); for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2]; if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; } if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; } if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer; } int _p; int _field[9]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); ttt tic; tic.play(); return 0; }
#include <stdio.h> #include <stdlib.h> int b[3][3]; int check_winner() { int i; for (i = 0; i < 3; i++) { if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]; if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]; } if (!b[1][1]) return 0; if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]; if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]; return 0; } void showboard() { const char *t = "X O"; int i, j; for (i = 0; i < 3; i++, putchar('\n')) for (j = 0; j < 3; j++) printf("%c ", t[ b[i][j] + 1 ]); printf("-----\n"); } #define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) int best_i, best_j; int test_move(int val, int depth) { int i, j, score; int best = -1, changed = 0; if ((score = check_winner())) return (score == val) ? 1 : -1; for_ij { if (b[i][j]) continue; changed = b[i][j] = val; score = -test_move(-val, depth + 1); b[i][j] = 0; if (score <= best) continue; if (!depth) { best_i = i; best_j = j; } best = score; } return changed ? best : 0; } const char* game(int user) { int i, j, k, move, win = 0; for_ij b[i][j] = 0; printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n"); printf("You have O, I have X.\n\n"); for (k = 0; k < 9; k++, user = !user) { while(user) { printf("your move: "); if (!scanf("%d", &move)) { scanf("%*s"); continue; } if (--move < 0 || move >= 9) continue; if (b[i = move / 3][j = move % 3]) continue; b[i][j] = 1; break; } if (!user) { if (!k) { best_i = rand() % 3; best_j = rand() % 3; } else test_move(-1, 0); b[best_i][best_j] = -1; printf("My move: %d\n", best_i * 3 + best_j + 1); } showboard(); if ((win = check_winner())) return win == 1 ? "You win.\n\n": "I win.\n\n"; } return "A draw.\n\n"; } int main() { int first = 0; while (1) printf("%s", game(first = !first)); return 0; }
Write the same code in C as shown below in C++.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
#include <stdio.h> int main() { unsigned int i = 0; while (++i) printf("%u\n", i); return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
#include <stdio.h> int main() { unsigned int i = 0; while (++i) printf("%u\n", i); return 0; }
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
Translate this program into C but keep the logic exactly as in C++.
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Please provide an equivalent version of this C++ code in C.
#include <cmath> #include <fstream> #include <iostream> #include <string> class peano_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void peano_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length; y_ = length; angle_ = 90; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "L"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string peano_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { switch (c) { case 'L': t += "LFRFL-F-RFLFR+F+LFRFL"; break; case 'R': t += "RFLFR+F+LFRFL-F-RFLFR"; break; default: t += c; break; } } return t; } void peano_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void peano_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } } int main() { std::ofstream out("peano_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } peano_curve pc; pc.write(out, 656, 8, 4); return 0; }
#include <graphics.h> #include <math.h> void Peano(int x, int y, int lg, int i1, int i2) { if (lg == 1) { lineto(3*x,3*y); return; } lg = lg/3; Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); Peano(x+lg, y+lg, lg, i1, 1-i2); Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); } int main(void) { initwindow(1000,1000,"Peano, Peano"); Peano(0, 0, 1000, 0, 0); getch(); cleardevice(); return 0; }
Change the following C++ code into C without altering its purpose.
template<typename F> class fivetoseven { public: fivetoseven(F f): d5(f), rem(0), max(1) {} int operator()(); private: F d5; int rem, max; }; template<typename F> int fivetoseven<F>::operator()() { while (rem/7 == max/7) { while (max < 7) { int rand5 = d5()-1; max *= 5; rem = 5*rem + rand5; } int groups = max / 7; if (rem >= 7*groups) { rem -= 7*groups; max -= 7*groups; } } int result = rem % 7; rem /= 7; max /= 7; return result+1; } int d5() { return 5.0*std::rand()/(RAND_MAX + 1.0) + 1; } fivetoseven<int(*)()> d7(d5); int main() { srand(time(0)); test_distribution(d5, 1000000, 0.001); test_distribution(d7, 1000000, 0.001); }
int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; } int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; } int main() { printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n"); printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n"); return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <array> #include <iostream> #include <vector> std::vector<std::pair<int, int>> connections = { {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, }; std::array<int, 8> pegs; int num = 0; void printSolution() { std::cout << "----- " << num++ << " -----\n"; std::cout << " " << pegs[0] << ' ' << pegs[1] << '\n'; std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n'; std::cout << " " << pegs[6] << ' ' << pegs[7] << '\n'; std::cout << '\n'; } bool valid() { for (size_t i = 0; i < connections.size(); i++) { if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) { return false; } } return true; } void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { for (size_t i = le; i <= ri; i++) { std::swap(pegs[le], pegs[i]); solution(le + 1, ri); std::swap(pegs[le], pegs[i]); } } } int main() { pegs = { 1, 2, 3, 4, 5, 6, 7, 8 }; solution(0, pegs.size() - 1); return 0; }
#include <stdbool.h> #include <stdio.h> #include <math.h> int connections[15][2] = { {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, }; int pegs[8]; int num = 0; bool valid() { int i; for (i = 0; i < 15; i++) { if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) { return false; } } return true; } void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } void printSolution() { printf("----- %d -----\n", num++); printf(" %d %d\n", pegs[0], pegs[1]); printf("%d %d %d %d\n", pegs[2], pegs[3], pegs[4], pegs[5]); printf(" %d %d\n", pegs[6], pegs[7]); printf("\n"); } void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { int i; for (i = le; i <= ri; i++) { swap(pegs + le, pegs + i); solution(le + 1, ri); swap(pegs + le, pegs + i); } } } int main() { int i; for (i = 0; i < 8; i++) { pegs[i] = i + 1; } solution(0, 8 - 1); return 0; }
Port the provided C++ code into C while preserving the original functionality.
#include <iomanip> #include <iostream> 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; } bool is_magnanimous(unsigned int n) { for (unsigned int p = 10; n >= p; p *= 10) { if (!is_prime(n % p + n / p)) return false; } return true; } int main() { unsigned int count = 0, n = 0; std::cout << "First 45 magnanimous numbers:\n"; for (; count < 45; ++n) { if (is_magnanimous(n)) { if (count > 0) std::cout << (count % 15 == 0 ? "\n" : ", "); std::cout << std::setw(3) << n; ++count; } } std::cout << "\n\n241st through 250th magnanimous numbers:\n"; for (unsigned int i = 0; count < 250; ++n) { if (is_magnanimous(n)) { if (count++ >= 240) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << "\n\n391st through 400th magnanimous numbers:\n"; for (unsigned int i = 0; count < 400; ++n) { if (is_magnanimous(n)) { if (count++ >= 390) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << '\n'; return 0; }
#include <stdio.h> #include <string.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 bool is_prime(ull n) { ull 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; } void ord(char *res, int n) { char suffix[3]; int m = n % 100; if (m >= 4 && m <= 20) { sprintf(res,"%dth", n); return; } switch(m % 10) { case 1: strcpy(suffix, "st"); break; case 2: strcpy(suffix, "nd"); break; case 3: strcpy(suffix, "rd"); break; default: strcpy(suffix, "th"); break; } sprintf(res, "%d%s", n, suffix); } bool is_magnanimous(ull n) { ull p, q, r; if (n < 10) return TRUE; for (p = 10; ; p *= 10) { q = n / p; r = n % p; if (!is_prime(q + r)) return FALSE; if (q < 10) break; } return TRUE; } void list_mags(int from, int thru, int digs, int per_line) { ull i = 0; int c = 0; char res1[13], res2[13]; if (from < 2) { printf("\nFirst %d magnanimous numbers:\n", thru); } else { ord(res1, from); ord(res2, thru); printf("\n%s through %s magnanimous numbers:\n", res1, res2); } for ( ; c < thru; ++i) { if (is_magnanimous(i)) { if (++c >= from) { printf("%*llu ", digs, i); if (!(c % per_line)) printf("\n"); } } } } int main() { list_mags(1, 45, 3, 15); list_mags(241, 250, 1, 10); list_mags(391, 400, 1, 10); return 0; }
Translate this program into C but keep the logic exactly as in C++.
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits> template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime, integer multiple, unsigned int wheel_index) : prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {} integer prime_; integer multiple_; unsigned int wheel_index_; }; struct cmp { bool operator()(const queue_item& a, const queue_item& b) const { return a.multiple_ > b.multiple_; } }; static integer wheel_next(unsigned int& index) { integer offset = wheel_[index]; ++index; if (index == std::size(wheel_)) index = 0; return offset; } typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue; integer next_ = 11; integer count_ = 0; queue queue_; unsigned int wheel_index_ = 0; static const unsigned int wheel_[]; static const integer primes_[]; }; template<typename integer> const unsigned int prime_generator<integer>::wheel_[] = { 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 }; template<typename integer> const integer prime_generator<integer>::primes_[] = { 2, 3, 5, 7 }; template<typename integer> integer prime_generator<integer>::next_prime() { if (count_ < std::size(primes_)) return primes_[count_++]; integer n = next_; integer prev = 0; while (!queue_.empty()) { queue_item item = queue_.top(); if (prev != 0 && prev != item.multiple_) n += wheel_next(wheel_index_); if (item.multiple_ > n) break; else if (item.multiple_ == n) { queue_.pop(); queue_item new_item(item); new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_); queue_.push(new_item); } else throw std::overflow_error("prime_generator: overflow!"); prev = item.multiple_; } if (std::numeric_limits<integer>::max()/n > n) queue_.emplace(n, n * n, wheel_index_); next_ = n + wheel_next(wheel_index_); ++count_; return n; } int main() { typedef uint32_t integer; prime_generator<integer> pgen; std::cout << "First 20 primes:\n"; for (int i = 0; i < 20; ++i) { integer p = pgen.next_prime(); if (i != 0) std::cout << ", "; std::cout << p; } std::cout << "\nPrimes between 100 and 150:\n"; for (int n = 0; ; ) { integer p = pgen.next_prime(); if (p > 150) break; if (p >= 100) { if (n != 0) std::cout << ", "; std::cout << p; ++n; } } int count = 0; for (;;) { integer p = pgen.next_prime(); if (p > 8000) break; if (p >= 7700) ++count; } std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n'; for (integer n = 10000; n <= 10000000; n *= 10) { integer prime; while (pgen.count() != n) prime = pgen.next_prime(); std::cout << n << "th prime: " << prime << '\n'; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define CHUNK_BYTES (32 << 8) #define CHUNK_SIZE (CHUNK_BYTES << 6) int field[CHUNK_BYTES]; #define GET(x) (field[(x)>>6] & 1<<((x)>>1&31)) #define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31)) typedef unsigned uint; typedef struct { uint *e; uint cap, len; } uarray; uarray primes, offset; void push(uarray *a, uint n) { if (a->len >= a->cap) { if (!(a->cap *= 2)) a->cap = 16; a->e = realloc(a->e, sizeof(uint) * a->cap); } a->e[a->len++] = n; } uint low; void init(void) { uint p, q; unsigned char f[1<<16]; memset(f, 0, sizeof(f)); push(&primes, 2); push(&offset, 0); for (p = 3; p < 1<<16; p += 2) { if (f[p]) continue; for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1; push(&primes, p); push(&offset, q); } low = 1<<16; } void sieve(void) { uint i, p, q, hi, ptop; if (!low) init(); memset(field, 0, sizeof(field)); hi = low + CHUNK_SIZE; ptop = sqrt(hi) * 2 + 1; for (i = 1; (p = primes.e[i]*2) < ptop; i++) { for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p) SET(q); offset.e[i] = q + low; } for (p = 1; p < CHUNK_SIZE; p += 2) if (!GET(p)) push(&primes, low + p); low = hi; } int main(void) { uint i, p, c; while (primes.len < 20) sieve(); printf("First 20:"); for (i = 0; i < 20; i++) printf(" %u", primes.e[i]); putchar('\n'); while (primes.e[primes.len-1] < 150) sieve(); printf("Between 100 and 150:"); for (i = 0; i < primes.len; i++) { if ((p = primes.e[i]) >= 100 && p < 150) printf(" %u", primes.e[i]); } putchar('\n'); while (primes.e[primes.len-1] < 8000) sieve(); for (i = c = 0; i < primes.len; i++) if ((p = primes.e[i]) >= 7700 && p < 8000) c++; printf("%u primes between 7700 and 8000\n", c); for (c = 10; c <= 100000000; c *= 10) { while (primes.len < c) sieve(); printf("%uth prime: %u\n", c, primes.e[c-1]); } return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <windows.h> #include <iostream> #include <string> using namespace std; enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C }; enum indexes { PLAYER, COMPUTER, DRAW }; class stats { public: stats() : _draw( 0 ) { ZeroMemory( _moves, sizeof( _moves ) ); ZeroMemory( _win, sizeof( _win ) ); } void draw() { _draw++; } void win( int p ) { _win[p]++; } void move( int p, int m ) { _moves[p][m]++; } int getMove( int p, int m ) { return _moves[p][m]; } string format( int a ) { char t[32]; wsprintf( t, "%.3d", a ); string d( t ); return d; } void print() { string d = format( _draw ), pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ), pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ), pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ), ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ), pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ), pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] ); system( "cls" ); cout << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl; cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl; cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << endl << endl; system( "pause" ); } private: int _moves[2][MX_C], _win[2], _draw; }; class rps { private: int makeMove() { int total = 0, r, s; for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) ); r = rand() % total; for( int i = ROCK; i < SCISSORS; i++ ) { s = statistics.getMove( PLAYER, i ); if( r < s ) return ( i + 1 ); r -= s; } return ROCK; } void printMove( int p, int m ) { if( p == COMPUTER ) cout << "My move: "; else cout << "Your move: "; switch( m ) { case ROCK: cout << "ROCK\n"; break; case PAPER: cout << "PAPER\n"; break; case SCISSORS: cout << "SCISSORS\n"; break; case LIZARD: cout << "LIZARD\n"; break; case SPOCK: cout << "SPOCK\n"; } } public: rps() { checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1; checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0; checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1; checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0; checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2; } void play() { int p, r, m; while( true ) { cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? "; cin >> p; if( !p || p < 0 ) break; if( p > 0 && p < 6 ) { p--; cout << endl; printMove( PLAYER, p ); statistics.move( PLAYER, p ); m = makeMove(); statistics.move( COMPUTER, m ); printMove( COMPUTER, m ); r = checker[p][m]; switch( r ) { case DRAW: cout << endl << "DRAW!" << endl << endl; statistics.draw(); break; case COMPUTER: cout << endl << "I WIN!" << endl << endl; statistics.win( COMPUTER ); break; case PLAYER: cout << endl << "YOU WIN!" << endl << endl; statistics.win( PLAYER ); } system( "pause" ); } system( "cls" ); } statistics.print(); } private: stats statistics; int checker[MX_C][MX_C]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); rps game; game.play(); return 0; }
#include <stdio.h> #include <stdlib.h> #define LEN 3 int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0); int i; for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; } int main() { int user_action, my_action; int user_rec[] = {0, 0, 0}; const char *names[] = { "Rock", "Paper", "Scissors" }; char str[2]; const char *winner[] = { "We tied.", "Meself winned.", "You win." }; double p[LEN] = { 1./3, 1./3, 1./3 }; while (1) { my_action = rand_idx(p,LEN); printf("\nYour choice [1-3]:\n" " 1. Rock\n 2. Paper\n 3. Scissors\n> "); if (!scanf("%d", &user_action)) { scanf("%1s", str); if (*str == 'q') { printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]); return 0; } continue; } user_action --; if (user_action > 2 || user_action < 0) { printf("invalid choice; again\n"); continue; } printf("You chose %s; I chose %s. %s\n", names[user_action], names[my_action], winner[(my_action - user_action + 3) % 3]); user_rec[user_action]++; } }
Convert this C++ block to C, preserving its control flow and logic.
#include <iostream> int main() { int dim1, dim2; std::cin >> dim1 >> dim2; double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; array[0][0] = 3.5; std::cout << array[0][0] << std::endl; delete[] array; delete[] array_data; return 0; }
#include <stdio.h> int main(int argc, char **argv) { int user1 = 0, user2 = 0; printf("Enter two integers. Space delimited, please: "); scanf("%d %d",&user1, &user2); int array[user1][user2]; array[user1/2][user2/2] = user1 + user2; printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]); return 0; }
Produce a functionally identical C code for the snippet given in C++.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Transform the following C++ implementation into C, maintaining the same output and logic.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <array> using namespace std; typedef array<pair<char, double>, 26> FreqArray; class VigenereAnalyser { private: array<double, 26> targets; array<double, 26> sortedTargets; FreqArray freq; FreqArray& frequency(const string& input) { for (char c = 'A'; c <= 'Z'; ++c) freq[c - 'A'] = make_pair(c, 0); for (size_t i = 0; i < input.size(); ++i) freq[input[i] - 'A'].second++; return freq; } double correlation(const string& input) { double result = 0.0; frequency(input); sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second < v.second; }); for (size_t i = 0; i < 26; ++i) result += freq[i].second * sortedTargets[i]; return result; } public: VigenereAnalyser(const array<double, 26>& targetFreqs) { targets = targetFreqs; sortedTargets = targets; sort(sortedTargets.begin(), sortedTargets.end()); } pair<string, string> analyze(string input) { string cleaned; for (size_t i = 0; i < input.size(); ++i) { if (input[i] >= 'A' && input[i] <= 'Z') cleaned += input[i]; else if (input[i] >= 'a' && input[i] <= 'z') cleaned += input[i] + 'A' - 'a'; } size_t bestLength = 0; double bestCorr = -100.0; for (size_t i = 2; i < cleaned.size() / 20; ++i) { vector<string> pieces(i); for (size_t j = 0; j < cleaned.size(); ++j) pieces[j % i] += cleaned[j]; double corr = -0.5*i; for (size_t j = 0; j < i; ++j) corr += correlation(pieces[j]); if (corr > bestCorr) { bestLength = i; bestCorr = corr; } } if (bestLength == 0) return make_pair("Text is too short to analyze", ""); vector<string> pieces(bestLength); for (size_t i = 0; i < cleaned.size(); ++i) pieces[i % bestLength] += cleaned[i]; vector<FreqArray> freqs; for (size_t i = 0; i < bestLength; ++i) freqs.push_back(frequency(pieces[i])); string key = ""; for (size_t i = 0; i < bestLength; ++i) { sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second > v.second; }); size_t m = 0; double mCorr = 0.0; for (size_t j = 0; j < 26; ++j) { double corr = 0.0; char c = 'A' + j; for (size_t k = 0; k < 26; ++k) { int d = (freqs[i][k].first - c + 26) % 26; corr += freqs[i][k].second * targets[d]; } if (corr > mCorr) { m = j; mCorr = corr; } } key += m + 'A'; } string result = ""; for (size_t i = 0; i < cleaned.size(); ++i) result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A'; return make_pair(result, key); } }; int main() { string input = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; array<double, 26> english = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074}; VigenereAnalyser va(english); pair<string, string> output = va.analyze(input); cout << "Key: " << output.second << endl << endl; cout << "Text: " << output.first << endl; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; const double freq[] = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; int best_match(const double *a, const double *b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } double freq_every_nth(const int *msg, int len, int interval, char *key) { double sum, d, ret; double out[26], accu[26] = {0}; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; key[j] = rot = best_match(out, freq); key[j] += 'A'; for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } int main() { int txt[strlen(encoded)]; int len = 0, j; char key[100]; double fit, best_fit = 1e100; for (j = 0; encoded[j] != '\0'; j++) if (isupper(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); printf("%f, key length: %2d, %s", fit, j, key); if (fit < best_fit) { best_fit = fit; printf(" <--- best so far"); } printf("\n"); } return 0; }
Write the same algorithm in C as shown in this C++ implementation.
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; for(;;) { std::cout << *++g; } }
#include <stdio.h> #include <stdlib.h> #include <gmp.h> mpz_t tmp1, tmp2, t5, t239, pows; void actan(mpz_t res, unsigned long base, mpz_t pows) { int i, neg = 1; mpz_tdiv_q_ui(res, pows, base); mpz_set(tmp1, res); for (i = 3; ; i += 2) { mpz_tdiv_q_ui(tmp1, tmp1, base * base); mpz_tdiv_q_ui(tmp2, tmp1, i); if (mpz_cmp_ui(tmp2, 0) == 0) break; if (neg) mpz_sub(res, res, tmp2); else mpz_add(res, res, tmp2); neg = !neg; } } char * get_digits(int n, size_t* len) { mpz_ui_pow_ui(pows, 10, n + 20); actan(t5, 5, pows); mpz_mul_ui(t5, t5, 16); actan(t239, 239, pows); mpz_mul_ui(t239, t239, 4); mpz_sub(t5, t5, t239); mpz_ui_pow_ui(pows, 10, 20); mpz_tdiv_q(t5, t5, pows); *len = mpz_sizeinbase(t5, 10); return mpz_get_str(0, 0, t5); } int main(int c, char **v) { unsigned long accu = 16384, done = 0; size_t got; char *s; mpz_init(tmp1); mpz_init(tmp2); mpz_init(t5); mpz_init(t239); mpz_init(pows); while (1) { s = get_digits(accu, &got); got -= 2; while (s[got] == '0' || s[got] == '9') got--; printf("%.*s", (int)(got - done), s + done); free(s); done = got; accu *= 2; } return 0; }
Transform the following C++ implementation into C, maintaining the same output and logic.
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); for (flip = 0, i = 1; i < N; i++) flip += q[i] > q[i + 1]; printf("flips: %d\n", flip); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); for (flip = 0, i = 1; i < N; i++) flip += q[i] > q[i + 1]; printf("flips: %d\n", flip); return 0; }
Generate an equivalent C version of this C++ code.
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) { return f(std::function<B(A)>([w](A x) { return w.o(w)(x); })); }) }; return r.o(r); } typedef std::function<int(int)> Func; typedef std::function<Func(Func)> FuncFunc; FuncFunc almost_fac = [](Func f) { return Func([f](int n) { if (n <= 1) return 1; return n * f(n - 1); }); }; FuncFunc almost_fib = [](Func f) { return Func([f](int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }); }; int main() { auto fib = Y(almost_fib); auto fac = Y(almost_fac); std::cout << "fib(10) = " << fib(10) << std::endl; std::cout << "fac(10) = " << fac(10) << std::endl; return 0; }
#include <stdio.h> #include <stdlib.h> typedef struct func_t *func; typedef struct func_t { func (*fn) (func, func); func _; int num; } func_t; func new(func(*f)(func, func), func _) { func x = malloc(sizeof(func_t)); x->fn = f; x->_ = _; x->num = 0; return x; } func call(func f, func n) { return f->fn(f, n); } func Y(func(*f)(func, func)) { func g = new(f, 0); g->_ = g; return g; } func num(int n) { func x = new(0, 0); x->num = n; return x; } func fac(func self, func n) { int nn = n->num; return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num) : num(1); } func fib(func self, func n) { int nn = n->num; return nn > 1 ? num( call(self->_, num(nn - 1))->num + call(self->_, num(nn - 2))->num ) : num(1); } void show(func n) { printf(" %d", n->num); } int main() { int i; func f = Y(fac); printf("fac: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); f = Y(fib); printf("fib: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); return 0; }