Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"container/list"
"fmt"
)
type BinaryTree struct {
node int
leftSubTree *BinaryTree
rightSubTree *BinaryTree
}
func (bt *BinaryTree) insert(item int) {
if bt.node == 0 {
bt.node = item
bt.leftSubTree = &BinaryTree{}
bt.rightSubTree = &BinaryTree{}
} else if item < bt.node {
bt.leftSubTree.insert(item)
} else {
bt.rightSubTree.insert(item)
}
}
func (bt *BinaryTree) inOrder(ll *list.List) {
if bt.node == 0 {
return
}
bt.leftSubTree.inOrder(ll)
ll.PushBack(bt.node)
bt.rightSubTree.inOrder(ll)
}
func treeSort(ll *list.List) *list.List {
searchTree := &BinaryTree{}
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
searchTree.insert(i)
}
ll2 := list.New()
searchTree.inOrder(ll2)
return ll2
}
func printLinkedList(ll *list.List, f string, sorted bool) {
for e := ll.Front(); e != nil; e = e.Next() {
i := e.Value.(int)
fmt.Printf(f+" ", i)
}
if !sorted {
fmt.Print("-> ")
} else {
fmt.Println()
}
}
func main() {
sl := []int{5, 3, 7, 9, 1}
ll := list.New()
for _, i := range sl {
ll.PushBack(i)
}
printLinkedList(ll, "%d", false)
lls := treeSort(ll)
printLinkedList(lls, "%d", true)
sl2 := []int{'d', 'c', 'e', 'b', 'a'}
ll2 := list.New()
for _, c := range sl2 {
ll2.PushBack(c)
}
printLinkedList(ll2, "%c", false)
lls2 := treeSort(ll2)
printLinkedList(lls2, "%c", true)
}
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
typedef struct node_tag {
int item;
struct node_tag* prev;
struct node_tag* next;
} node_t;
void list_initialize(node_t* list) {
list->prev = list;
list->next = list;
}
void list_destroy(node_t* list) {
node_t* n = list->next;
while (n != list) {
node_t* tmp = n->next;
free(n);
n = tmp;
}
}
void list_append_node(node_t* list, node_t* node) {
node_t* prev = list->prev;
prev->next = node;
list->prev = node;
node->prev = prev;
node->next = list;
}
void list_append_item(node_t* list, int item) {
node_t* node = xmalloc(sizeof(node_t));
node->item = item;
list_append_node(list, node);
}
void list_print(node_t* list) {
printf("[");
node_t* n = list->next;
if (n != list) {
printf("%d", n->item);
n = n->next;
}
for (; n != list; n = n->next)
printf(", %d", n->item);
printf("]\n");
}
void tree_insert(node_t** p, node_t* n) {
while (*p != NULL) {
if (n->item < (*p)->item)
p = &(*p)->prev;
else
p = &(*p)->next;
}
*p = n;
}
void tree_to_list(node_t* list, node_t* node) {
if (node == NULL)
return;
node_t* prev = node->prev;
node_t* next = node->next;
tree_to_list(list, prev);
list_append_node(list, node);
tree_to_list(list, next);
}
void tree_sort(node_t* list) {
node_t* n = list->next;
if (n == list)
return;
node_t* root = NULL;
while (n != list) {
node_t* next = n->next;
n->next = n->prev = NULL;
tree_insert(&root, n);
n = next;
}
list_initialize(list);
tree_to_list(list, root);
}
int main() {
srand(time(0));
node_t list;
list_initialize(&list);
for (int i = 0; i < 16; ++i)
list_append_item(&list, rand() % 100);
printf("before sort: ");
list_print(&list);
tree_sort(&list);
printf(" after sort: ");
list_print(&list);
list_destroy(&list);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
limit := 999999
primes := rcu.Primes(limit)
fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:")
for i := 1; i < len(primes); i++ {
diff := primes[i] - primes[i-1]
if diff > 36 {
s := int(math.Sqrt(float64(diff)))
if diff == s*s {
cp1 := rcu.Commatize(primes[i])
cp2 := rcu.Commatize(primes[i-1])
fmt.Printf("%7s - %7s = %3d = %2d x %2d\n", cp1, cp2, diff, s, s)
}
}
}
}
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int issquare( int p ) {
int i;
for(i=0;i*i<p;i++);
return i*i==p;
}
int main(void) {
int i=3, j=2;
for(i=3;j<=1000000;i=j) {
j=nextprime(i);
if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
}
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
limit := 999999
primes := rcu.Primes(limit)
fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:")
for i := 1; i < len(primes); i++ {
diff := primes[i] - primes[i-1]
if diff > 36 {
s := int(math.Sqrt(float64(diff)))
if diff == s*s {
cp1 := rcu.Commatize(primes[i])
cp2 := rcu.Commatize(primes[i-1])
fmt.Printf("%7s - %7s = %3d = %2d x %2d\n", cp1, cp2, diff, s, s)
}
}
}
}
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int issquare( int p ) {
int i;
for(i=0;i*i<p;i++);
return i*i==p;
}
int main(void) {
int i=3, j=2;
for(i=3;j<=1000000;i=j) {
j=nextprime(i);
if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
}
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
| #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
|
Write the same code in C as shown below in Go. | import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
| #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"log"
"os/exec"
"time"
)
func main() {
out, err := exec.Command("xrandr", "-q").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1024x768").Run()
if err != nil {
log.Fatal(err)
}
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1366x768").Run()
if err != nil {
log.Fatal(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_xrandr(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 8];
strcpy(command, "xrandr ");
strcat(command, arg);
system(command);
}
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr;
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "video_display_modes.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"log"
"os/exec"
"time"
)
func main() {
out, err := exec.Command("xrandr", "-q").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1024x768").Run()
if err != nil {
log.Fatal(err)
}
time.Sleep(3 * time.Second)
err = exec.Command("xrandr", "-s", "1366x768").Run()
if err != nil {
log.Fatal(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_xrandr(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 8];
strcpy(command, "xrandr ");
strcat(command, arg);
system(command);
}
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr;
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "video_display_modes.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
_, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
gc.FlushInput()
}
| #include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char text[256];
getchar();
fseek(stdin, 0, SEEK_END);
fgets(text, sizeof(text), stdin);
puts(text);
return EXIT_SUCCESS;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
| #include <stdio.h>
#include <math.h>
typedef struct { double m; double fm; double simp; } triple;
triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = f(m);
double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);
triple t = {m, fm, simp};
return t;
}
double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {
triple lt = _quad_simpsons_mem(f, a, fa, m, fm);
triple rt = _quad_simpsons_mem(f, m, fm, b, fb);
double delta = lt.simp + rt.simp - whole;
if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;
return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);
}
double quad_asr(double (*f)(double), double a, double b, double eps) {
double fa = f(a);
double fb = f(b);
triple t = _quad_simpsons_mem(f, a, fa, b, fb);
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);
}
int main(){
double a = 0.0, b = 1.0;
double sinx = quad_asr(sin, a, b, 1e-09);
printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
| #include <stdio.h>
#include <math.h>
typedef struct { double m; double fm; double simp; } triple;
triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = f(m);
double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);
triple t = {m, fm, simp};
return t;
}
double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {
triple lt = _quad_simpsons_mem(f, a, fa, m, fm);
triple rt = _quad_simpsons_mem(f, m, fm, b, fb);
double delta = lt.simp + rt.simp - whole;
if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;
return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);
}
double quad_asr(double (*f)(double), double a, double b, double eps) {
double fa = f(a);
double fb = f(b);
triple t = _quad_simpsons_mem(f, a, fa, b, fb);
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);
}
int main(){
double a = 0.0, b = 1.0;
double sinx = quad_asr(sin, a, b, 1e-09);
printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx);
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.Open("rc.fasta")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
headerFound := false
for s.Scan() {
line := s.Text()
switch {
case line == "":
continue
case line[0] != '>':
if !headerFound {
fmt.Println("missing header")
return
}
fmt.Print(line)
case headerFound:
fmt.Println()
fallthrough
default:
fmt.Printf("%s: ", line[1:])
headerFound = true
}
}
if headerFound {
fmt.Println()
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("fasta.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
int state = 0;
while ((read = getline(&line, &len, fp)) != -1) {
if (line[read - 1] == '\n')
line[read - 1] = 0;
if (line[0] == '>') {
if (state == 1)
printf("\n");
printf("%s: ", line+1);
state = 1;
} else {
printf("%s", line);
}
}
printf("\n");
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func main() {
count := 0
fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
for i := 3; i <= 995; i += 2 {
if isPrime(i) && isPrime(i+4) {
fmt.Printf("%3d:%3d ", i, i+4)
count++
if count%7 == 0 {
fmt.Println()
}
if i != 3 {
i += 4
} else {
i += 2
}
}
}
fmt.Printf("\n\n%d pairs found\n", count)
}
| #include <stdio.h>
#include <string.h>
#define LIMIT 1000
void sieve(int max, char *s) {
int p, k;
memset(s, 0, max);
for (p=2; p*p<=max; p++)
if (!s[p])
for (k=p*p; k<=max; k+=p)
s[k]=1;
}
int main(void) {
char primes[LIMIT+1];
int p, count=0;
sieve(LIMIT, primes);
for (p=2; p<=LIMIT; p++) {
if (!primes[p] && !primes[p+4]) {
count++;
printf("%4d: %4d\n", p, p+4);
}
}
printf("There are %d cousin prime pairs below %d.\n", count, LIMIT);
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func main() {
count := 0
fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
for i := 3; i <= 995; i += 2 {
if isPrime(i) && isPrime(i+4) {
fmt.Printf("%3d:%3d ", i, i+4)
count++
if count%7 == 0 {
fmt.Println()
}
if i != 3 {
i += 4
} else {
i += 2
}
}
}
fmt.Printf("\n\n%d pairs found\n", count)
}
| #include <stdio.h>
#include <string.h>
#define LIMIT 1000
void sieve(int max, char *s) {
int p, k;
memset(s, 0, max);
for (p=2; p*p<=max; p++)
if (!s[p])
for (k=p*p; k<=max; k+=p)
s[k]=1;
}
int main(void) {
char primes[LIMIT+1];
int p, count=0;
sieve(LIMIT, primes);
for (p=2; p<=LIMIT; p++) {
if (!primes[p] && !primes[p+4]) {
count++;
printf("%4d: %4d\n", p, p+4);
}
}
printf("There are %d cousin prime pairs below %d.\n", count, LIMIT);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
| #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
| #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"golang.org/x/crypto/ssh/terminal"
"fmt"
"os"
)
func main() {
if terminal.IsTerminal(int(os.Stdin.Fd())) {
fmt.Println("Hello terminal")
} else {
fmt.Println("Who are you? You're not a terminal.")
}
}
| #include <unistd.h>
#include <stdio.h>
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"golang.org/x/crypto/ssh/terminal"
"fmt"
"os"
)
func main() {
if terminal.IsTerminal(int(os.Stdin.Fd())) {
fmt.Println("Hello terminal")
} else {
fmt.Println("Who are you? You're not a terminal.")
}
}
| #include <unistd.h>
#include <stdio.h>
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"log"
"github.com/jezek/xgb"
"github.com/jezek/xgb/xproto"
)
func main() {
X, err := xgb.NewConn()
if err != nil {
log.Fatal(err)
}
points := []xproto.Point{
{10, 10},
{10, 20},
{20, 10},
{20, 20}};
polyline := []xproto.Point{
{50, 10},
{ 5, 20},
{25,-20},
{10, 10}};
segments := []xproto.Segment{
{100, 10, 140, 30},
{110, 25, 130, 60}};
rectangles := []xproto.Rectangle{
{ 10, 50, 40, 20},
{ 80, 50, 10, 40}};
arcs := []xproto.Arc{
{10, 100, 60, 40, 0, 90 << 6},
{90, 100, 55, 40, 0, 270 << 6}};
setup := xproto.Setup(X)
screen := setup.DefaultScreen(X)
foreground, _ := xproto.NewGcontextId(X)
mask := uint32(xproto.GcForeground | xproto.GcGraphicsExposures)
values := []uint32{screen.BlackPixel, 0}
xproto.CreateGC(X, foreground, xproto.Drawable(screen.Root), mask, values)
win, _ := xproto.NewWindowId(X)
winDrawable := xproto.Drawable(win)
mask = uint32(xproto.CwBackPixel | xproto.CwEventMask)
values = []uint32{screen.WhitePixel, xproto.EventMaskExposure}
xproto.CreateWindow(X,
screen.RootDepth,
win,
screen.Root,
0, 0,
150, 150,
10,
xproto.WindowClassInputOutput,
screen.RootVisual,
mask, values)
xproto.MapWindow(X, win)
for {
evt, err := X.WaitForEvent()
switch evt.(type) {
case xproto.ExposeEvent:
xproto.PolyPoint(X, xproto.CoordModeOrigin, winDrawable, foreground, points)
xproto.PolyLine(X, xproto.CoordModePrevious, winDrawable, foreground, polyline)
xproto.PolySegment(X, winDrawable, foreground, segments)
xproto.PolyRectangle(X, winDrawable, foreground, rectangles)
xproto.PolyArc(X, winDrawable, foreground, arcs)
default:
}
if err != nil {
log.Fatal(err)
}
}
return
}
| '--- added a flush to exit cleanly
PRAGMA LDFLAGS `pkg-config --cflags --libs x11`
PRAGMA INCLUDE <X11/Xlib.h>
PRAGMA INCLUDE <X11/Xutil.h>
OPTION PARSE FALSE
'---XLIB is so ugly
ALIAS XNextEvent TO EVENT
ALIAS XOpenDisplay TO DISPLAY
ALIAS DefaultScreen TO SCREEN
ALIAS XCreateSimpleWindow TO CREATE
ALIAS XCloseDisplay TO CLOSE_DISPLAY
ALIAS XSelectInput TO EVENT_TYPE
ALIAS XMapWindow TO MAP_EVENT
ALIAS XFillRectangle TO FILL_RECTANGLE
ALIAS XDrawString TO DRAW_STRING
ALIAS XFlush TO FLUSH
'---pointer to X Display structure
DECLARE d TYPE Display*
'---pointer to the newly created window
'DECLARE w TYPE WINDOW
'---pointer to the XEvent
DECLARE e TYPE XEvent
DECLARE msg TYPE char*
'--- number of screen to place the window on
DECLARE s TYPE int
msg = "Hello, World!"
d = DISPLAY(NULL)
IF d == NULL THEN
EPRINT "Cannot open display" FORMAT "%s%s\n"
END
END IF
s = SCREEN(d)
w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))
EVENT_TYPE(d, w, ExposureMask | KeyPressMask)
MAP_EVENT(d, w)
WHILE (1)
EVENT(d, &e)
IF e.type == Expose THEN
FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)
DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))
END IF
IF e.type == KeyPress THEN
BREAK
END IF
WEND
FLUSH(d)
CLOSE_DISPLAY(d)
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import "fmt"
const n = 64
func pow2(x uint) uint64 {
return uint64(1) << x
}
func evolve(state uint64, rule int) {
for p := 0; p < 10; p++ {
b := uint64(0)
for q := 7; q >= 0; q-- {
st := state
b |= (st & 1) << uint(q)
state = 0
for i := uint(0); i < n; i++ {
var t1, t2, t3 uint64
if i > 0 {
t1 = st >> (i - 1)
} else {
t1 = st >> 63
}
if i == 0 {
t2 = st << 1
} else if i == 1 {
t2 = st << 63
} else {
t2 = st << (n + 1 - i)
}
t3 = 7 & (t1 | t2)
if (uint64(rule) & pow2(uint(t3))) != 0 {
state |= pow2(i)
}
}
}
fmt.Printf("%d ", b)
}
fmt.Println()
}
func main() {
evolve(1, 30)
}
| #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++)
if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
state |= B(i);
}
printf(" %d", b);
}
putchar('\n');
return;
}
int main(void)
{
evolve(1, 30);
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
}
| #include <sys/ioctl.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int
main()
{
struct winsize ws;
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
err(1, "/dev/tty");
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, "/dev/tty");
printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
type state int
const (
ready state = iota
waiting
exit
dispense
refunding
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func fsm() {
fmt.Println("Please enter your option when prompted")
fmt.Println("(any characters after the first will be ignored)")
state := ready
var trans string
scanner := bufio.NewScanner(os.Stdin)
for {
switch state {
case ready:
for {
fmt.Print("\n(D)ispense or (Q)uit : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'd' {
state = waiting
break
} else if option == 'q' {
state = exit
break
}
}
case waiting:
fmt.Println("OK, put your money in the slot")
for {
fmt.Print("(S)elect product or choose a (R)efund : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 's' {
state = dispense
break
} else if option == 'r' {
state = refunding
break
}
}
case dispense:
for {
fmt.Print("(R)emove product : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'r' {
state = ready
break
}
}
case refunding:
fmt.Println("OK, refunding your money")
state = ready
case exit:
fmt.Println("OK, quitting")
return
}
}
}
func main() {
fsm()
}
| #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;
typedef struct statechange {
const int in;
const State out;
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State state;
void (*Action)(void);
const statechange table[MAXINPUTS];
} FSM;
char str[10];
void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); }
void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); }
void Refund(void) { fprintf(stderr, "Please collect refund.\n"); }
void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); }
void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); }
void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); }
const FSM fsm[] = {
{ READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }},
{ WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }},
{ REFUND, &Refund, {{ -1, READY} }},
{ DISPENSE, &Dispense, {{ -1, COLLECT} }},
{ COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }},
{ QUIT, &Quit, {{ -1, QUIT} }},
};
int each;
State state = READY;
for (;;) {
fsm[state].Action();
each = 0;
while (!( ((fsm[state].table[each].in == -1)
|| (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;
state = fsm[state].table[each].out;
}
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"image"
"image/color"
"image/gif"
"log"
"os"
)
var (
black = color.RGBA{0, 0, 0, 255}
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
yellow = color.RGBA{255, 255, 0, 255}
white = color.RGBA{255, 255, 255, 255}
)
var palette = []color.Color{red, green, blue, magenta, cyan, yellow, white, black}
func hline(img *image.Paletted, x1, y, x2 int, ci uint8) {
for ; x1 <= x2; x1++ {
img.SetColorIndex(x1, y, ci)
}
}
func vline(img *image.Paletted, x, y1, y2 int, ci uint8) {
for ; y1 <= y2; y1++ {
img.SetColorIndex(x, y1, ci)
}
}
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 drawRectangle(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
hline(img, x1, y1, x2, ci)
hline(img, x1, y2, x2, ci)
vline(img, x1, y1, y2, ci)
vline(img, x2, y1, y2, ci)
}
func main() {
const nframes = 140
const delay = 10
width, height := 500, 500
anim := gif.GIF{LoopCount: nframes}
rect := image.Rect(0, 0, width, height)
for c := uint8(0); c < 7; c++ {
for f := 0; f < 20; f++ {
img := image.NewPaletted(rect, palette)
setBackgroundColor(img, width, height, 7)
for r := 0; r < 20; r++ {
ix := c
if r < f {
ix = (ix + 1) % 7
}
x := width * (r + 1) / 50
y := height * (r + 1) / 50
w := width - x
h := height - y
drawRectangle(img, x, y, w, h, ix)
}
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
}
file, err := os.Create("vibrating.gif")
if err != nil {
log.Fatal(err)
}
defer file.Close()
if err2 := gif.EncodeAll(file, &anim); err != nil {
log.Fatal(err2)
}
}
|
#include<graphics.h>
void vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)
{
int color = 1,i,x = winWidth/2, y = winHeight/2;
while(!kbhit()){
setcolor(color++);
for(i=num;i>0;i--){
rectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);
delay(msec);
}
if(color>MAXCOLORS){
color = 1;
}
}
}
int main()
{
initwindow(1000,1000,"Vibrating Rectangles...");
vibratingRectangles(1000,1000,30,15,20,500);
closegraph();
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"sort"
)
func main() {
a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}
for len(a) > 1 {
sort.Ints(a)
fmt.Println("Sorted list:", a)
sum := a[0] + a[1]
fmt.Printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum)
a = append(a, sum)
a = a[2:]
}
fmt.Println("Last item is", a[0], "\b.")
}
| #include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
int aa = *(const int *)a;
int bb = *(const int *)b;
if (aa < bb) return -1;
if (aa > bb) return 1;
return 0;
}
int main() {
int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};
int isize = sizeof(int);
int asize = sizeof(a) / isize;
int i, sum;
while (asize > 1) {
qsort(a, asize, isize, compare);
printf("Sorted list: ");
for (i = 0; i < asize; ++i) printf("%d ", a[i]);
printf("\n");
sum = a[0] + a[1];
printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum);
for (i = 2; i < asize; ++i) a[i-2] = a[i];
a[asize - 2] = sum;
asize--;
}
printf("Last item is %d.\n", a[0]);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
freq := 0
for freq < 40 || freq > 10000 {
fmt.Print("Enter frequency in Hz (40 to 10000) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
freq, _ = strconv.Atoi(input)
}
freqS := strconv.Itoa(freq)
vol := 0
for vol < 1 || vol > 50 {
fmt.Print("Enter volume in dB (1 to 50) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
vol, _ = strconv.Atoi(input)
}
volS := strconv.Itoa(vol)
dur := 0.0
for dur < 2 || dur > 10 {
fmt.Print("Enter duration in seconds (2 to 10) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
dur, _ = strconv.ParseFloat(input, 64)
}
durS := strconv.FormatFloat(dur, 'f', -1, 64)
kind := 0
for kind < 1 || kind > 3 {
fmt.Print("Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
kind, _ = strconv.Atoi(input)
}
kindS := "sine"
if kind == 2 {
kindS = "square"
} else if kind == 3 {
kindS = "sawtooth"
}
args := []string{"-n", "synth", durS, kindS, freqS, "vol", volS, "dB"}
cmd := exec.Command("play", args...)
err := cmd.Run()
check(err)
}
| #include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
void C_play(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 5];
strcpy(command, "play ");
strcat(command, args);
system(command);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "play(_)") == 0) return C_play;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "audio_frequency_generator.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;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
freq := 0
for freq < 40 || freq > 10000 {
fmt.Print("Enter frequency in Hz (40 to 10000) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
freq, _ = strconv.Atoi(input)
}
freqS := strconv.Itoa(freq)
vol := 0
for vol < 1 || vol > 50 {
fmt.Print("Enter volume in dB (1 to 50) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
vol, _ = strconv.Atoi(input)
}
volS := strconv.Itoa(vol)
dur := 0.0
for dur < 2 || dur > 10 {
fmt.Print("Enter duration in seconds (2 to 10) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
dur, _ = strconv.ParseFloat(input, 64)
}
durS := strconv.FormatFloat(dur, 'f', -1, 64)
kind := 0
for kind < 1 || kind > 3 {
fmt.Print("Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
kind, _ = strconv.Atoi(input)
}
kindS := "sine"
if kind == 2 {
kindS = "square"
} else if kind == 3 {
kindS = "sawtooth"
}
args := []string{"-n", "synth", durS, kindS, freqS, "vol", volS, "dB"}
cmd := exec.Command("play", args...)
err := cmd.Run()
check(err)
}
| #include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
void C_play(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 5];
strcpy(command, "play ");
strcat(command, args);
system(command);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "play(_)") == 0) return C_play;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "audio_frequency_generator.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;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(79)
ix := 0
n := 1
count := 0
var pi []int
for {
if primes[ix] <= n {
count++
if count == 22 {
break
}
ix++
}
n++
pi = append(pi, count)
}
fmt.Println("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
for i, n := range pi {
fmt.Printf("%2d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
}
| #include <stdio.h>
#include <stdlib.h>
int isprime( int n ) {
int i;
if (n<2) return 0;
for(i=2; i*i<=n; i++) {
if (n % i == 0) {return 0;}
}
return 1;
}
int main(void) {
int n = 0, p = 1;
while (n<22) {
printf( "%d ", n );
p++;
if (isprime(p)) n+=1;
}
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(79)
ix := 0
n := 1
count := 0
var pi []int
for {
if primes[ix] <= n {
count++
if count == 22 {
break
}
ix++
}
n++
pi = append(pi, count)
}
fmt.Println("pi(n), the number of primes <= n, where n >= 1 and pi(n) < 22:")
for i, n := range pi {
fmt.Printf("%2d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\nHighest n for this range = %d.\n", len(pi))
}
| #include <stdio.h>
#include <stdlib.h>
int isprime( int n ) {
int i;
if (n<2) return 0;
for(i=2; i*i<=n; i++) {
if (n % i == 0) {return 0;}
}
return 1;
}
int main(void) {
int n = 0, p = 1;
while (n<22) {
printf( "%d ", n );
p++;
if (isprime(p)) n+=1;
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"rcu"
)
func main() {
numbers1 := [5]int{5, 45, 23, 21, 67}
numbers2 := [5]int{43, 22, 78, 46, 38}
numbers3 := [5]int{9, 98, 12, 98, 53}
numbers := [5]int{}
for n := 0; n < 5; n++ {
numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])
}
fmt.Println(numbers)
}
| #include <stdio.h>
int min(int a, int b) {
if (a < b) return a;
return b;
}
int main() {
int n;
int numbers1[5] = {5, 45, 23, 21, 67};
int numbers2[5] = {43, 22, 78, 46, 38};
int numbers3[5] = {9, 98, 12, 98, 53};
int numbers[5] = {};
for (n = 0; n < 5; ++n) {
numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);
printf("%d ", numbers[n]);
}
printf("\n");
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"math"
)
const CONST = 6364136223846793005
type Pcg32 struct{ state, inc uint64 }
func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }
func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
pcg.state = 0
pcg.inc = (seedSequence << 1) | 1
pcg.nextInt()
pcg.state = pcg.state + seedState
pcg.nextInt()
}
func (pcg *Pcg32) nextInt() uint32 {
old := pcg.state
pcg.state = old*CONST + pcg.inc
pcgshifted := uint32(((old >> 18) ^ old) >> 27)
rot := uint32(old >> 59)
return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}
func (pcg *Pcg32) nextFloat() float64 {
return float64(pcg.nextInt()) / (1 << 32)
}
func main() {
randomGen := Pcg32New()
randomGen.seed(42, 54)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321, 1)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
const uint64_t N = 6364136223846793005;
static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;
uint32_t pcg32_int() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double pcg32_float() {
return ((double)pcg32_int()) / (1LL << 32);
}
void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
pcg32_int();
state = state + seed_state;
pcg32_int();
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
pcg32_seed(42, 54);
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("\n");
pcg32_seed(987654321, 1);
for (i = 0; i < 100000; i++) {
int j = (int)floor(pcg32_float() * 5.0);
counts[j]++;
}
printf("The counts for 100,000 repetitions are:\n");
for (i = 0; i < 5; i++) {
printf(" %d : %d\n", i, counts[i]);
}
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import "fmt"
func main() {
h := []float64{-8, -9, -3, -1, -6, 7}
f := []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}
g := []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96,
96, 31, 55, 36, 29, -43, -7}
fmt.Println(h)
fmt.Println(deconv(g, f))
fmt.Println(f)
fmt.Println(deconv(g, h))
}
func deconv(g, f []float64) []float64 {
h := make([]float64, len(g)-len(f)+1)
for n := range h {
h[n] = g[n]
var lower int
if n >= len(f) {
lower = n - len(f) + 1
}
for i := lower; i < n; i++ {
h[n] -= h[i] * f[n-i]
}
h[n] /= f[0]
}
return h
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx t = cexp(-I * PI * i / n) * out[i + step];
buf[i / 2] = out[i] + t;
buf[(i + n)/2] = out[i] - t;
}
}
}
void fft(cplx buf[], int n)
{
cplx out[n];
for (int i = 0; i < n; i++) out[i] = buf[i];
_fft(buf, out, n, 1);
}
cplx *pad_two(double g[], int len, int *ns)
{
int n = 1;
if (*ns) n = *ns;
else while (n < len) n *= 2;
cplx *buf = calloc(sizeof(cplx), n);
for (int i = 0; i < len; i++) buf[i] = g[i];
*ns = n;
return buf;
}
void deconv(double g[], int lg, double f[], int lf, double out[]) {
int ns = 0;
cplx *g2 = pad_two(g, lg, &ns);
cplx *f2 = pad_two(f, lf, &ns);
fft(g2, ns);
fft(f2, ns);
cplx h[ns];
for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];
fft(h, ns);
for (int i = 0; i >= lf - lg; i--)
out[-i] = h[(i + ns) % ns]/32;
free(g2);
free(f2);
}
int main()
{
PI = atan2(1,1) * 4;
double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};
double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };
double h[] = { -8,-9,-3,-1,-6,7 };
int lg = sizeof(g)/sizeof(double);
int lf = sizeof(f)/sizeof(double);
int lh = sizeof(h)/sizeof(double);
double h2[lh];
double f2[lf];
printf("f[] data is : ");
for (int i = 0; i < lf; i++) printf(" %g", f[i]);
printf("\n");
printf("deconv(g, h): ");
deconv(g, lg, h, lh, f2);
for (int i = 0; i < lf; i++) printf(" %g", f2[i]);
printf("\n");
printf("h[] data is : ");
for (int i = 0; i < lh; i++) printf(" %g", h[i]);
printf("\n");
printf("deconv(g, f): ");
deconv(g, lg, f, lf, h2);
for (int i = 0; i < lh; i++) printf(" %g", h2[i]);
printf("\n");
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"math/rand"
"os/exec"
"raster"
)
func main() {
b := raster.NewBitmap(400, 300)
b.FillRgb(0xc08040)
for i := 0; i < 2000; i++ {
b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)
}
for x := 0; x < 400; x++ {
for y := 240; y < 245; y++ {
b.SetPxRgb(x, y, 0x804020)
}
for y := 260; y < 265; y++ {
b.SetPxRgb(x, y, 0x804020)
}
}
for y := 0; y < 300; y++ {
for x := 80; x < 85; x++ {
b.SetPxRgb(x, y, 0x804020)
}
for x := 95; x < 100; x++ {
b.SetPxRgb(x, y, 0x804020)
}
}
c := exec.Command("cjpeg", "-outfile", "pipeout.jpg")
pipe, err := c.StdinPipe()
if err != nil {
fmt.Println(err)
return
}
err = c.Start()
if err != nil {
fmt.Println(err)
return
}
err = b.WritePpmTo(pipe)
if err != nil {
fmt.Println(err)
return
}
err = pipe.Close()
if err != nil {
fmt.Println(err)
}
}
|
void print_jpg(image img, int qual);
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"golang.org/x/crypto/ripemd160"
)
type Point struct {
x, y [32]byte
}
func (p *Point) SetHex(x, y string) error {
if len(x) != 64 || len(y) != 64 {
return errors.New("invalid hex string length")
}
if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {
return err
}
_, err := hex.Decode(p.y[:], []byte(y))
return err
}
type A25 [25]byte
func (a *A25) doubleSHA256() []byte {
h := sha256.New()
h.Write(a[:21])
d := h.Sum([]byte{})
h = sha256.New()
h.Write(d)
return h.Sum(d[:0])
}
func (a *A25) UpdateChecksum() {
copy(a[21:], a.doubleSHA256())
}
func (a *A25) SetPoint(p *Point) {
c := [65]byte{4}
copy(c[1:], p.x[:])
copy(c[33:], p.y[:])
h := sha256.New()
h.Write(c[:])
s := h.Sum([]byte{})
h = ripemd160.New()
h.Write(s)
h.Sum(a[1:1])
a.UpdateChecksum()
}
var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
func (a *A25) A58() []byte {
var out [34]byte
for n := 33; n >= 0; n-- {
c := 0
for i := 0; i < 25; i++ {
c = c*256 + int(a[i])
a[i] = byte(c / 58)
c %= 58
}
out[n] = tmpl[c]
}
i := 1
for i < 34 && out[i] == '1' {
i++
}
return out[i-1:]
}
func main() {
var p Point
err := p.SetHex(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6")
if err != nil {
fmt.Println(err)
return
}
var a A25
a.SetPoint(&p)
fmt.Println(string(a.A58()))
}
| #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"golang.org/x/crypto/ripemd160"
)
type Point struct {
x, y [32]byte
}
func (p *Point) SetHex(x, y string) error {
if len(x) != 64 || len(y) != 64 {
return errors.New("invalid hex string length")
}
if _, err := hex.Decode(p.x[:], []byte(x)); err != nil {
return err
}
_, err := hex.Decode(p.y[:], []byte(y))
return err
}
type A25 [25]byte
func (a *A25) doubleSHA256() []byte {
h := sha256.New()
h.Write(a[:21])
d := h.Sum([]byte{})
h = sha256.New()
h.Write(d)
return h.Sum(d[:0])
}
func (a *A25) UpdateChecksum() {
copy(a[21:], a.doubleSHA256())
}
func (a *A25) SetPoint(p *Point) {
c := [65]byte{4}
copy(c[1:], p.x[:])
copy(c[33:], p.y[:])
h := sha256.New()
h.Write(c[:])
s := h.Sum([]byte{})
h = ripemd160.New()
h.Write(s)
h.Sum(a[1:1])
a.UpdateChecksum()
}
var tmpl = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
func (a *A25) A58() []byte {
var out [34]byte
for n := 33; n >= 0; n-- {
c := 0
for i := 0; i < 25; i++ {
c = c*256 + int(a[i])
a[i] = byte(c / 58)
c %= 58
}
out[n] = tmpl[c]
}
i := 1
for i < 34 && out[i] == '1' {
i++
}
return out[i-1:]
}
func main() {
var p Point
err := p.SetHex(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6")
if err != nil {
fmt.Println(err)
return
}
var a A25
a.SetPoint(&p)
fmt.Println(string(a.A58()))
}
| #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16s : %s\n", name, name2)
}
}
| #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strings"
)
type pair struct{ first, second string }
var (
fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"},
{"PF", "FF"}, {"SCH", "SSS"}}
lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"},
{"RD", "D"}, {"NT", "D"}, {"ND", "D"}}
mStrs = []pair{{"EV", "AF"}, {"KN", "N"}, {"SCH", "SSS"}, {"PH", "FF"}}
eStrs = []string{"JR", "JNR", "SR", "SNR"}
)
func isVowel(b byte) bool {
return strings.ContainsRune("AEIOU", rune(b))
}
func isRoman(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !strings.ContainsRune("IVX", r) {
return false
}
}
return true
}
func nysiis(word string) string {
if word == "" {
return ""
}
w := strings.ToUpper(word)
ww := strings.FieldsFunc(w, func(r rune) bool {
return r == ' ' || r == ','
})
if len(ww) > 1 {
last := ww[len(ww)-1]
if isRoman(last) {
w = w[:len(w)-len(last)]
}
}
for _, c := range " ,'-" {
w = strings.Replace(w, string(c), "", -1)
}
for _, eStr := range eStrs {
if strings.HasSuffix(w, eStr) {
w = w[:len(w)-len(eStr)]
}
}
for _, fStr := range fStrs {
if strings.HasPrefix(w, fStr.first) {
w = strings.Replace(w, fStr.first, fStr.second, 1)
}
}
for _, lStr := range lStrs {
if strings.HasSuffix(w, lStr.first) {
w = w[:len(w)-2] + lStr.second
}
}
initial := w[0]
var key strings.Builder
key.WriteByte(initial)
w = w[1:]
for _, mStr := range mStrs {
w = strings.Replace(w, mStr.first, mStr.second, -1)
}
sb := []byte{initial}
sb = append(sb, w...)
le := len(sb)
for i := 1; i < le; i++ {
switch sb[i] {
case 'E', 'I', 'O', 'U':
sb[i] = 'A'
case 'Q':
sb[i] = 'G'
case 'Z':
sb[i] = 'S'
case 'M':
sb[i] = 'N'
case 'K':
sb[i] = 'C'
case 'H':
if !isVowel(sb[i-1]) || (i < le-1 && !isVowel(sb[i+1])) {
sb[i] = sb[i-1]
}
case 'W':
if isVowel(sb[i-1]) {
sb[i] = 'A'
}
}
}
if sb[le-1] == 'S' {
sb = sb[:le-1]
le--
}
if le > 1 && string(sb[le-2:]) == "AY" {
sb = sb[:le-2]
sb = append(sb, 'Y')
le--
}
if le > 0 && sb[le-1] == 'A' {
sb = sb[:le-1]
le--
}
prev := initial
for j := 1; j < le; j++ {
c := sb[j]
if prev != c {
key.WriteByte(c)
prev = c
}
}
return key.String()
}
func main() {
names := []string{
"Bishop", "Carlson", "Carr", "Chapman",
"Franklin", "Greene", "Harper", "Jacobs", "Larson", "Lawrence",
"Lawson", "Louis, XVI", "Lynch", "Mackenzie", "Matthews", "May jnr",
"McCormack", "McDaniel", "McDonald", "Mclaughlin", "Morrison",
"O'Banion", "O'Brien", "Richards", "Silva", "Watkins", "Xi",
"Wheeler", "Willis", "brown, sr", "browne, III", "browne, IV",
"knight", "mitchell", "o'daniel", "bevan", "evans", "D'Souza",
"Hoyle-Johnson", "Vaughan Williams", "de Sousa", "de la Mare II",
}
for _, name := range names {
name2 := nysiis(name)
if len(name2) > 6 {
name2 = fmt.Sprintf("%s(%s)", name2[:6], name2[6:])
}
fmt.Printf("%-16s : %s\n", name, name2)
}
}
| #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import "C"
import "unsafe"
var rot = 0.0
var matCol = [4]C.float{1, 0, 0, 0}
func display() {
C.glClear(C.GL_COLOR_BUFFER_BIT | C.GL_DEPTH_BUFFER_BIT)
C.glPushMatrix()
C.glRotatef(30, 1, 1, 0)
C.glRotatef(C.float(rot), 0, 1, 1)
C.glMaterialfv(C.GL_FRONT, C.GL_DIFFUSE, &matCol[0])
C.glutWireTeapot(0.5)
C.glPopMatrix()
C.glFlush()
}
func onIdle() {
rot += 0.01
C.glutPostRedisplay()
}
func initialize() {
white := [4]C.float{1, 1, 1, 0}
shini := [1]C.float{70}
C.glClearColor(0.5, 0.5, 0.5, 0)
C.glShadeModel(C.GL_SMOOTH)
C.glLightfv(C.GL_LIGHT0, C.GL_AMBIENT, &white[0])
C.glLightfv(C.GL_LIGHT0, C.GL_DIFFUSE, &white[0])
C.glMaterialfv(C.GL_FRONT, C.GL_SHININESS, &shini[0])
C.glEnable(C.GL_LIGHTING)
C.glEnable(C.GL_LIGHT0)
C.glEnable(C.GL_DEPTH_TEST)
}
func main() {
argc := C.int(0)
C.glutInit(&argc, nil)
C.glutInitDisplayMode(C.GLUT_SINGLE | C.GLUT_RGB | C.GLUT_DEPTH)
C.glutInitWindowSize(900, 700)
tl := "The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut."
tlc := C.CString(tl)
C.glutCreateWindow(tlc)
initialize()
C.glutDisplayFunc(C.displayFunc())
C.glutIdleFunc(C.idleFunc())
C.glutMainLoop()
C.free(unsafe.Pointer(tlc))
}
| #include<gl/freeglut.h>
double rot = 0;
float matCol[] = {1,0,0,0};
void display(){
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(30,1,1,0);
glRotatef(rot,0,1,1);
glMaterialfv(GL_FRONT,GL_DIFFUSE,matCol);
glutWireTeapot(0.5);
glPopMatrix();
glFlush();
}
void onIdle(){
rot += 0.01;
glutPostRedisplay();
}
void init(){
float pos[] = {1,1,1,0};
float white[] = {1,1,1,0};
float shini[] = {70};
glClearColor(.5,.5,.5,0);
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0,GL_AMBIENT,white);
glLightfv(GL_LIGHT0,GL_DIFFUSE,white);
glMaterialfv(GL_FRONT,GL_SHININESS,shini);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
}
int main(int argC, char* argV[])
{
glutInit(&argC,argV);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(900,700);
glutCreateWindow("The Amazing, Rotating Utah Teapot brought to you in OpenGL via freeglut.");
init();
glutDisplayFunc(display);
glutIdleFunc(onIdle);
glutMainLoop();
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"strconv"
)
const DMAX = 20
const LIMIT = 20
func main() {
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
DIGITS := make([]int, 1+DMAX)
Exp := make([]uint64, 1+DMAX)
Pow := make([]uint64, 1+DMAX)
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
for 0 < level && level < digit {
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] {
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] {
DIGITS[level]++
continue
}
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow {
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
if max < min {
DIGITS[level]++
} else {
level++
}
}
if level < 1 {
break
}
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
for DIGITS[level] < 10 {
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"github.com/fogleman/gg"
"image/color"
"math"
)
var (
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
)
var (
w, h = 640, 640
dc = gg.NewContext(w, h)
deg72 = gg.Radians(72)
scaleFactor = 1 / (2 + math.Cos(deg72)*2)
palette = [5]color.Color{red, green, blue, magenta, cyan}
colorIndex = 0
)
func drawPentagon(x, y, side float64, depth int) {
angle := 3 * deg72
if depth == 0 {
dc.MoveTo(x, y)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * side
y -= math.Sin(angle) * side
dc.LineTo(x, y)
angle += deg72
}
dc.SetColor(palette[colorIndex])
dc.Fill()
colorIndex = (colorIndex + 1) % 5
} else {
side *= scaleFactor
dist := side * (1 + math.Cos(deg72)*2)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * dist
y -= math.Sin(angle) * dist
drawPentagon(x, y, side, depth-1)
angle += deg72
}
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
order := 5
hw := float64(w / 2)
margin := 20.0
radius := hw - 2*margin
side := radius * math.Sin(math.Pi/5) * 2
drawPentagon(hw, 3*margin, side, order-1)
dc.SavePNG("sierpinski_pentagon.png")
}
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
initwindow(windowSide,windowSide,"Polygon Chaos");
vertices = (double**)malloc(numSides*sizeof(double*));
for(i=0;i<numSides;i++){
vertices[i] = (double*)malloc(2 * sizeof(double));
vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
sumX+= vertices[i][0];
sumY+= vertices[i][1];
putpixel(vertices[i][0],vertices[i][1],15);
}
srand((unsigned)time(&t));
seedX = sumX/numSides;
seedY = sumY/numSides;
putpixel(seedX,seedY,15);
for(i=0;i<iter;i++){
choice = rand()%numSides;
seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
putpixel(seedX,seedY,15);
}
free(vertices);
getch();
closegraph();
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"rcu"
)
func main() {
numbers1 := [5]int{5, 45, 23, 21, 67}
numbers2 := [5]int{43, 22, 78, 46, 38}
numbers3 := [5]int{9, 98, 12, 54, 53}
primes := [5]int{}
for n := 0; n < 5; n++ {
max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n])
if max % 2 == 0 {
max++
}
for !rcu.IsPrime(max) {
max += 2
}
primes[n] = max
}
fmt.Println(primes)
}
| #include <stdio.h>
#define TRUE 1
#define FALSE 0
int isPrime(int n) {
int d;
if (n < 2) return FALSE;
if (n%2 == 0) return n == 2;
if (n%3 == 0) return n == 3;
d = 5;
while (d*d <= n) {
if (!(n%d)) return FALSE;
d += 2;
if (!(n%d)) return FALSE;
d += 4;
}
return TRUE;
}
int max(int a, int b) {
if (a > b) return a;
return b;
}
int main() {
int n, m;
int numbers1[5] = { 5, 45, 23, 21, 67};
int numbers2[5] = {43, 22, 78, 46, 38};
int numbers3[5] = { 9, 98, 12, 54, 53};
int primes[5] = {};
for (n = 0; n < 5; ++n) {
m = max(max(numbers1[n], numbers2[n]), numbers3[n]);
if (!(m % 2)) m++;
while (!isPrime(m)) m += 2;
primes[n] = m;
printf("%d ", primes[n]);
}
printf("\n");
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package raster
import "math"
func (g *Grmap) Histogram(bins int) []int {
if bins <= 0 {
bins = g.cols
}
h := make([]int, bins)
for _, p := range g.px {
h[int(p)*(bins-1)/math.MaxUint16]++
}
return h
}
func (g *Grmap) Threshold(t uint16) {
for i, p := range g.px {
if p < t {
g.px[i] = 0
} else {
g.px[i] = math.MaxUint16
}
}
}
| typedef unsigned int histogram_t;
typedef histogram_t *histogram;
#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )
histogram get_histogram(grayimage im);
luminance histogram_median(histogram h);
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
func padovanN(n, t int) []int {
if n < 2 || t < 3 {
ones := make([]int, t)
for i := 0; i < t; i++ {
ones[i] = 1
}
return ones
}
p := padovanN(n-1, t)
for i := n + 1; i < t; i++ {
p[i] = 0
for j := i - 2; j >= i-n-1; j-- {
p[i] += p[j]
}
}
return p
}
func main() {
t := 15
fmt.Println("First", t, "terms of the Padovan n-step number sequences:")
for n := 2; n <= 8; n++ {
fmt.Printf("%d: %3d\n", n, padovanN(n, t))
}
}
| #include <stdio.h>
void padovanN(int n, size_t t, int *p) {
int i, j;
if (n < 2 || t < 3) {
for (i = 0; i < t; ++i) p[i] = 1;
return;
}
padovanN(n-1, t, p);
for (i = n + 1; i < t; ++i) {
p[i] = 0;
for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
}
}
int main() {
int n, i;
const size_t t = 15;
int p[t];
printf("First %ld terms of the Padovan n-step number sequences:\n", t);
for (n = 2; n <= 8; ++n) {
for (i = 0; i < t; ++i) p[i] = 0;
padovanN(n, t, p);
printf("%d: ", n);
for (i = 0; i < t; ++i) printf("%3d ", p[i]);
printf("\n");
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"sync"
"time"
)
var value int
var m sync.Mutex
var wg sync.WaitGroup
func slowInc() {
m.Lock()
v := value
time.Sleep(1e8)
value = v+1
m.Unlock()
wg.Done()
}
func main() {
wg.Add(2)
go slowInc()
go slowInc()
wg.Wait()
fmt.Println(value)
}
| HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"time"
)
func main() {
var bpm = 72.0
var bpb = 4
d := time.Duration(float64(time.Minute) / bpm)
fmt.Println("Delay:", d)
t := time.NewTicker(d)
i := 1
for _ = range t.C {
i--
if i == 0 {
i = bpb
fmt.Printf("\nTICK ")
} else {
fmt.Printf("tick ")
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
struct timeval start, last;
inline int64_t tv_to_u(struct timeval s)
{
return s.tv_sec * 1000000 + s.tv_usec;
}
inline struct timeval u_to_tv(int64_t x)
{
struct timeval s;
s.tv_sec = x / 1000000;
s.tv_usec = x % 1000000;
return s;
}
void draw(int dir, int64_t period, int64_t cur, int64_t next)
{
int len = 40 * (next - cur) / period;
int s, i;
if (len > 20) len = 40 - len;
s = 20 + (dir ? len : -len);
printf("\033[H");
for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');
}
void beat(int delay)
{
struct timeval tv = start;
int dir = 0;
int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;
int64_t draw_interval = 20000;
printf("\033[H\033[J");
while (1) {
gettimeofday(&tv, 0);
slp = next - tv_to_u(tv) - corr;
usleep(slp);
gettimeofday(&tv, 0);
putchar(7);
fflush(stdout);
printf("\033[5;1Hdrift: %d compensate: %d (usec) ",
(int)d, (int)corr);
dir = !dir;
cur = tv_to_u(tv);
d = cur - next;
corr = (corr + d) / 2;
next += delay;
while (cur + d + draw_interval < next) {
usleep(draw_interval);
gettimeofday(&tv, 0);
cur = tv_to_u(tv);
draw(dir, delay, cur, next);
fflush(stdout);
}
}
}
int main(int c, char**v)
{
int bpm;
if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;
if (bpm > 600) {
fprintf(stderr, "frequency %d too high\n", bpm);
exit(1);
}
gettimeofday(&start, 0);
last = start;
beat(60 * 1000000 / bpm);
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. |
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}
| #!/usr/local/bin/script_gcc.sh
#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef char *STRING;
typedef enum{FALSE=0, TRUE=1} BOOL;
const STRING ENDCAT = NULL;
#define DIALECT "c"
const STRING
CC="gcc",
COPTS="-lm -x "DIALECT,
IEXT="."DIALECT,
OEXT=".out";
const BOOL OPT_CACHE = TRUE;
char strcat_out[BUFSIZ];
STRING STRCAT(STRING argv, ... ){
va_list ap;
va_start(ap, argv);
STRING arg;
strcat_out[0]='\0';
for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){
strncat(strcat_out, arg, sizeof strcat_out);
}
va_end(ap);
return strndup(strcat_out, sizeof strcat_out);
}
char itoa_out[BUFSIZ];
STRING itoa_(int i){
sprintf(itoa_out, "%d", i);
return itoa_out;
}
time_t modtime(STRING filename){
struct stat buf;
if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);
return buf.st_mtime;
}
BOOL compile(STRING srcpath, STRING binpath){
int out;
STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT);
FILE *src=fopen(srcpath, "r"),
*compiler=popen(compiler_command, "w");
char buf[BUFSIZ];
BOOL shebang;
for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)
if(!shebang)fwrite(buf, strlen(buf), 1, compiler);
out=pclose(compiler);
return out;
}
void main(int argc, STRING *argv, STRING *envp){
STRING binpath,
srcpath=argv[1],
argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),
*dirnamew, *dirnamex;
argv++;
STRING paths[] = {
dirname(strdup(srcpath)),
STRCAT(getenv("HOME"), "/bin", ENDCAT),
"/usr/local/bin",
".",
STRCAT(getenv("HOME"), "/tmp", ENDCAT),
getenv("HOME"),
STRCAT(getenv("HOME"), "/Desktop", ENDCAT),
ENDCAT
};
for(dirnamew = paths; *dirnamew; dirnamew++){
if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;
}
if(OPT_CACHE == FALSE){
binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS){
if(fork()){
sleep(0.1); unlink(binpath);
} else {
execvp(binpath, argv);
}
}
} else {
time_t modtime_srcpath = modtime(srcpath);
for(dirnamex = paths; *dirnamex; dirnamex++){
binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT);
if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))
execvp(binpath, argv);
}
}
binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS)
execvp(binpath, argv);
perror(STRCAT(binpath, ": executable not available", ENDCAT));
exit(errno);
}
|
Translate this program into C but keep the logic exactly as in Go. |
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}
| #!/usr/local/bin/script_gcc.sh
#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef char *STRING;
typedef enum{FALSE=0, TRUE=1} BOOL;
const STRING ENDCAT = NULL;
#define DIALECT "c"
const STRING
CC="gcc",
COPTS="-lm -x "DIALECT,
IEXT="."DIALECT,
OEXT=".out";
const BOOL OPT_CACHE = TRUE;
char strcat_out[BUFSIZ];
STRING STRCAT(STRING argv, ... ){
va_list ap;
va_start(ap, argv);
STRING arg;
strcat_out[0]='\0';
for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){
strncat(strcat_out, arg, sizeof strcat_out);
}
va_end(ap);
return strndup(strcat_out, sizeof strcat_out);
}
char itoa_out[BUFSIZ];
STRING itoa_(int i){
sprintf(itoa_out, "%d", i);
return itoa_out;
}
time_t modtime(STRING filename){
struct stat buf;
if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);
return buf.st_mtime;
}
BOOL compile(STRING srcpath, STRING binpath){
int out;
STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT);
FILE *src=fopen(srcpath, "r"),
*compiler=popen(compiler_command, "w");
char buf[BUFSIZ];
BOOL shebang;
for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)
if(!shebang)fwrite(buf, strlen(buf), 1, compiler);
out=pclose(compiler);
return out;
}
void main(int argc, STRING *argv, STRING *envp){
STRING binpath,
srcpath=argv[1],
argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),
*dirnamew, *dirnamex;
argv++;
STRING paths[] = {
dirname(strdup(srcpath)),
STRCAT(getenv("HOME"), "/bin", ENDCAT),
"/usr/local/bin",
".",
STRCAT(getenv("HOME"), "/tmp", ENDCAT),
getenv("HOME"),
STRCAT(getenv("HOME"), "/Desktop", ENDCAT),
ENDCAT
};
for(dirnamew = paths; *dirnamew; dirnamew++){
if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;
}
if(OPT_CACHE == FALSE){
binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS){
if(fork()){
sleep(0.1); unlink(binpath);
} else {
execvp(binpath, argv);
}
}
} else {
time_t modtime_srcpath = modtime(srcpath);
for(dirnamex = paths; *dirnamex; dirnamex++){
binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT);
if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))
execvp(binpath, argv);
}
}
binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS)
execvp(binpath, argv);
perror(STRCAT(binpath, ": executable not available", ENDCAT));
exit(errno);
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"sort"
)
func contains(a []int, b int) bool {
for _, j := range a {
if j == b {
return true
}
}
return false
}
func gcd(a, b int) int {
for a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
func areSame(s, t []int) bool {
le := len(s)
if le != len(t) {
return false
}
sort.Ints(s)
sort.Ints(t)
for i := 0; i < le; i++ {
if s[i] != t[i] {
return false
}
}
return true
}
func main() {
const limit = 100
starts := [5]int{2, 5, 7, 9, 10}
var ekg [5][limit]int
for s, start := range starts {
ekg[s][0] = 1
ekg[s][1] = start
for n := 2; n < limit; n++ {
for i := 2; ; i++ {
if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {
ekg[s][n] = i
break
}
}
}
fmt.Printf("EKG(%2d): %v\n", start, ekg[s][:30])
}
for i := 2; i < limit; i++ {
if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {
fmt.Println("\nEKG(5) and EKG(7) converge at term", i+1)
return
}
}
fmt.Println("\nEKG5(5) and EKG(7) do not converge within", limit, "terms")
}
| #include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define LIMIT 100
typedef int bool;
int compareInts(const void *a, const void *b) {
int aa = *(int *)a;
int bb = *(int *)b;
return aa - bb;
}
bool contains(int a[], int b, size_t len) {
int i;
for (i = 0; i < len; ++i) {
if (a[i] == b) return TRUE;
}
return FALSE;
}
int gcd(int a, int b) {
while (a != b) {
if (a > b)
a -= b;
else
b -= a;
}
return a;
}
bool areSame(int s[], int t[], size_t len) {
int i;
qsort(s, len, sizeof(int), compareInts);
qsort(t, len, sizeof(int), compareInts);
for (i = 0; i < len; ++i) {
if (s[i] != t[i]) return FALSE;
}
return TRUE;
}
int main() {
int s, n, i;
int starts[5] = {2, 5, 7, 9, 10};
int ekg[5][LIMIT];
for (s = 0; s < 5; ++s) {
ekg[s][0] = 1;
ekg[s][1] = starts[s];
for (n = 2; n < LIMIT; ++n) {
for (i = 2; ; ++i) {
if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {
ekg[s][n] = i;
break;
}
}
}
printf("EKG(%2d): [", starts[s]);
for (i = 0; i < 30; ++i) printf("%d ", ekg[s][i]);
printf("\b]\n");
}
for (i = 2; i < LIMIT; ++i) {
if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {
printf("\nEKG(5) and EKG(7) converge at term %d\n", i + 1);
return 0;
}
}
printf("\nEKG5(5) and EKG(7) do not converge within %d terms\n", LIMIT);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"strings"
)
func rep(s string) int {
for x := len(s) / 2; x > 0; x-- {
if strings.HasPrefix(s, s[x:]) {
return x
}
}
return 0
}
const m = `
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1`
func main() {
for _, s := range strings.Fields(m) {
if n := rep(s); n > 0 {
fmt.Printf("%q %d rep-string %q\n", s, n, s[:n])
} else {
fmt.Printf("%q not a rep-string\n", s)
}
}
}
| #include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1" };
size_t strslen = sizeof(strs) / sizeof(strs[0]);
size_t i;
for (i = 0; i < strslen; ++i) {
int n = repstr(strs[i]);
if (n)
printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
else
printf("\"%s\" = not a rep-string\n", strs[i]);
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"time"
)
func main() {
fmt.Print("\033[?1049h\033[H")
fmt.Println("Alternate screen buffer\n")
s := "s"
for i := 5; i > 0; i-- {
if i == 1 {
s = ""
}
fmt.Printf("\rgoing back in %d second%s...", i, s)
time.Sleep(time.Second)
}
fmt.Print("\033[?1049l")
}
| #include <stdio.h>
#include <unistd.h>
int main()
{
int i;
printf("\033[?1049h\033[H");
printf("Alternate screen buffer\n");
for (i = 5; i; i--) {
printf("\rgoing back in %d...", i);
fflush(stdout);
sleep(1);
}
printf("\033[?1049l");
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | ch := 'z'
ch = 122
ch = '\x7a'
ch = '\u007a'
ch = '\U0000007a'
ch = '\172'
| char ch = 'z';
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func hammingDist(s1, s2 string) int {
r1 := []rune(s1)
r2 := []rune(s2)
if len(r1) != len(r2) {
return 0
}
count := 0
for i := 0; i < len(r1); i++ {
if r1[i] != r2[i] {
count++
if count == 2 {
break
}
}
}
return count
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 11 {
words = append(words, s)
}
}
count := 0
fmt.Println("Changeable words in", wordList, "\b:")
for _, word1 := range words {
for _, word2 := range words {
if word1 != word2 && hammingDist(word1, word2) == 1 {
count++
fmt.Printf("%2d: %-14s -> %s\n", count, word1, word2)
}
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 32
typedef struct string_tag {
size_t length;
char str[MAX_WORD_SIZE];
} string_t;
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int hamming_distance(const string_t* str1, const string_t* str2) {
size_t len1 = str1->length;
size_t len2 = str2->length;
if (len1 != len2)
return 0;
int count = 0;
const char* s1 = str1->str;
const char* s2 = str2->str;
for (size_t i = 0; i < len1; ++i) {
if (s1[i] != s2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
string_t* dictionary = xmalloc(sizeof(string_t) * capacity);
while (fgets(line, sizeof(line), in)) {
if (size == capacity) {
capacity *= 2;
dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);
}
size_t len = strlen(line) - 1;
if (len > 11) {
string_t* str = &dictionary[size];
str->length = len;
memcpy(str->str, line, len);
str->str[len] = '\0';
++size;
}
}
fclose(in);
printf("Changeable words in %s:\n", filename);
int n = 1;
for (size_t i = 0; i < size; ++i) {
const string_t* str1 = &dictionary[i];
for (size_t j = 0; j < size; ++j) {
const string_t* str2 = &dictionary[j];
if (i != j && hamming_distance(str1, str2) == 1)
printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str);
}
}
free(dictionary);
return EXIT_SUCCESS;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"time"
)
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetResizable(true)
window.SetTitle("Window management")
window.SetBorderWidth(5)
window.Connect("destroy", func() {
gtk.MainQuit()
})
stackbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 10)
check(err, "Unable to create stack box:")
bmax, err := gtk.ButtonNewWithLabel("Maximize")
check(err, "Unable to create maximize button:")
bmax.Connect("clicked", func() {
window.Maximize()
})
bunmax, err := gtk.ButtonNewWithLabel("Unmaximize")
check(err, "Unable to create unmaximize button:")
bunmax.Connect("clicked", func() {
window.Unmaximize()
})
bicon, err := gtk.ButtonNewWithLabel("Iconize")
check(err, "Unable to create iconize button:")
bicon.Connect("clicked", func() {
window.Iconify()
})
bdeicon, err := gtk.ButtonNewWithLabel("Deiconize")
check(err, "Unable to create deiconize button:")
bdeicon.Connect("clicked", func() {
window.Deiconify()
})
bhide, err := gtk.ButtonNewWithLabel("Hide")
check(err, "Unable to create hide button:")
bhide.Connect("clicked", func() {
window.Hide()
time.Sleep(10 * time.Second)
window.Show()
})
bshow, err := gtk.ButtonNewWithLabel("Show")
check(err, "Unable to create show button:")
bshow.Connect("clicked", func() {
window.Show()
})
bmove, err := gtk.ButtonNewWithLabel("Move")
check(err, "Unable to create move button:")
isShifted := false
bmove.Connect("clicked", func() {
w, h := window.GetSize()
if isShifted {
window.Move(w-10, h-10)
} else {
window.Move(w+10, h+10)
}
isShifted = !isShifted
})
bquit, err := gtk.ButtonNewWithLabel("Quit")
check(err, "Unable to create quit button:")
bquit.Connect("clicked", func() {
window.Destroy()
})
stackbox.PackStart(bmax, true, true, 0)
stackbox.PackStart(bunmax, true, true, 0)
stackbox.PackStart(bicon, true, true, 0)
stackbox.PackStart(bdeicon, true, true, 0)
stackbox.PackStart(bhide, true, true, 0)
stackbox.PackStart(bshow, true, true, 0)
stackbox.PackStart(bmove, true, true, 0)
stackbox.PackStart(bquit, true, true, 0)
window.Add(stackbox)
window.ShowAll()
gtk.Main()
}
| #include<windows.h>
#include<unistd.h>
#include<stdio.h>
const char g_szClassName[] = "weirdWindow";
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd[3];
MSG Msg;
int i,x=0,y=0;
char str[3][100];
int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.",
"If you can see two blank windows just behind this message box, you are in luck.",
"Let's get started....",
"Yes, you will be seeing a lot of me :)",
"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)",
"Let's compare the windows for equality.",
"Now let's hide Window 1.",
"Now let's see Window 1 again.",
"Let's close Window 2, bye, bye, Number 2 !",
"Let's minimize Window 1.",
"Now let's maximize Window 1.",
"And finally we come to the fun part, watch Window 1 move !",
"Let's double Window 1 in size for all the good work.",
"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK);
return 0;
}
for(i=0;i<2;i++){
sprintf(str[i],"Window Number %d",i+1);
hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);
if(hwnd[i] == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd[i], nCmdShow);
UpdateWindow(hwnd[i]);
}
for(i=0;i<6;i++){
MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
}
if(hwnd[0]==hwnd[1])
MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
else
MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_HIDE);
MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_SHOW);
MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[1], SW_HIDE);
MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_MINIMIZE);
MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_MAXIMIZE);
MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_RESTORE);
while(x!=maxX/2||y!=maxY/2){
if(x<maxX/2)
x++;
if(y<maxY/2)
y++;
MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);
sleep(10);
}
MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
MoveWindow(hwnd[0],0,0,maxX, maxY,0);
MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
type mlist struct{ value []int }
func (m mlist) bind(f func(lst []int) mlist) mlist {
return f(m.value)
}
func unit(lst []int) mlist {
return mlist{lst}
}
func increment(lst []int) mlist {
lst2 := make([]int, len(lst))
for i, v := range lst {
lst2[i] = v + 1
}
return unit(lst2)
}
func double(lst []int) mlist {
lst2 := make([]int, len(lst))
for i, v := range lst {
lst2[i] = 2 * v
}
return unit(lst2)
}
func main() {
ml1 := unit([]int{3, 4, 5})
ml2 := ml1.bind(increment).bind(double)
fmt.Printf("%v -> %v\n", ml1.value, ml2.value)
}
| #include <stdio.h>
#include <stdlib.h>
#define MONAD void*
#define INTBIND(f, g, x) (f((int*)g(x)))
#define RETURN(type,x) &((type)*)(x)
MONAD boundInt(int *x) {
return (MONAD)(x);
}
MONAD boundInt2str(int *x) {
char buf[100];
char*str= malloc(1+sprintf(buf, "%d", *x));
sprintf(str, "%d", *x);
return (MONAD)(str);
}
void task(int y) {
char *z= INTBIND(boundInt2str, boundInt, &y);
printf("%s\n", z);
free(z);
}
int main() {
task(13);
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
var squares []int
limit := int(math.Sqrt(1000))
i := 1
for i <= limit {
n := i * i
if rcu.IsPrime(n + 1) {
squares = append(squares, n)
}
if i == 1 {
i = 2
} else {
i += 2
}
}
fmt.Println("There are", len(squares), "square numbers 'n' where 'n+1' is prime, viz:")
fmt.Println(squares)
}
| #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math"
"rcu"
)
func main() {
var squares []int
limit := int(math.Sqrt(1000))
i := 1
for i <= limit {
n := i * i
if rcu.IsPrime(n + 1) {
squares = append(squares, n)
}
if i == 1 {
i = 2
} else {
i += 2
}
}
fmt.Println("There are", len(squares), "square numbers 'n' where 'n+1' is prime, viz:")
fmt.Println(squares)
}
| #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
| #include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
int d;
if (n < 2) return false;
if (!(n%2)) return n == 2;
if (!(n%3)) return n == 3;
d = 5;
while (d*d <= n) {
if (!(n%d)) return false;
d += 2;
if (!(n%d)) return false;
d += 4;
}
return true;
}
int main() {
int i, lastSpecial = 3, lastGap = 1;
printf("Special primes under 1,050:\n");
printf("Prime1 Prime2 Gap\n");
printf("%6d %6d %3d\n", 2, 3, lastGap);
for (i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func main() {
c := sieve(1049)
fmt.Println("Special primes under 1,050:")
fmt.Println("Prime1 Prime2 Gap")
lastSpecial := 3
lastGap := 1
fmt.Printf("%6d %6d %3d\n", 2, 3, lastGap)
for i := 5; i < 1050; i += 2 {
if !c[i] && (i-lastSpecial) > lastGap {
lastGap = i - lastSpecial
fmt.Printf("%6d %6d %3d\n", lastSpecial, i, lastGap)
lastSpecial = i
}
}
}
| #include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
int d;
if (n < 2) return false;
if (!(n%2)) return n == 2;
if (!(n%3)) return n == 3;
d = 5;
while (d*d <= n) {
if (!(n%d)) return false;
d += 2;
if (!(n%d)) return false;
d += 4;
}
return true;
}
int main() {
int i, lastSpecial = 3, lastGap = 1;
printf("Special primes under 1,050:\n");
printf("Prime1 Prime2 Gap\n");
printf("%6d %6d %3d\n", 2, 3, lastGap);
for (i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strconv"
)
const (
ul = "╔"
uc = "╦"
ur = "╗"
ll = "╚"
lc = "╩"
lr = "╝"
hb = "═"
vb = "║"
)
var mayan = [5]string{
" ",
" ∙ ",
" ∙∙ ",
"∙∙∙ ",
"∙∙∙∙",
}
const (
m0 = " Θ "
m5 = "────"
)
func dec2vig(n uint64) []uint64 {
vig := strconv.FormatUint(n, 20)
res := make([]uint64, len(vig))
for i, d := range vig {
res[i], _ = strconv.ParseUint(string(d), 20, 64)
}
return res
}
func vig2quin(n uint64) [4]string {
if n >= 20 {
panic("Cant't convert a number >= 20")
}
res := [4]string{mayan[0], mayan[0], mayan[0], mayan[0]}
if n == 0 {
res[3] = m0
return res
}
fives := n / 5
rem := n % 5
res[3-fives] = mayan[rem]
for i := 3; i > 3-int(fives); i-- {
res[i] = m5
}
return res
}
func draw(mayans [][4]string) {
lm := len(mayans)
fmt.Print(ul)
for i := 0; i < lm; i++ {
for j := 0; j < 4; j++ {
fmt.Print(hb)
}
if i < lm-1 {
fmt.Print(uc)
} else {
fmt.Println(ur)
}
}
for i := 1; i < 5; i++ {
fmt.Print(vb)
for j := 0; j < lm; j++ {
fmt.Print(mayans[j][i-1])
fmt.Print(vb)
}
fmt.Println()
}
fmt.Print(ll)
for i := 0; i < lm; i++ {
for j := 0; j < 4; j++ {
fmt.Print(hb)
}
if i < lm-1 {
fmt.Print(lc)
} else {
fmt.Println(lr)
}
}
}
func main() {
numbers := []uint64{4005, 8017, 326205, 886205, 1081439556}
for _, n := range numbers {
fmt.Printf("Converting %d to Mayan:\n", n)
vigs := dec2vig(n)
lv := len(vigs)
mayans := make([][4]string, lv)
for i, vig := range vigs {
mayans[i] = vig2quin(vig)
}
draw(mayans)
fmt.Println()
}
}
| #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
size_t base20(unsigned int n, uint8_t *out) {
uint8_t *start = out;
do {*out++ = n % 20;} while (n /= 20);
size_t length = out - start;
while (out > start) {
uint8_t x = *--out;
*out = *start;
*start++ = x;
}
return length;
}
void make_digit(int n, char *place, size_t line_length) {
static const char *parts[] = {" "," . "," .. ","... ","....","----"};
int i;
for (i=4; i>0; i--, n -= 5)
memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);
if (n == -20) place[4 * line_length + 1] = '@';
}
char *mayan(unsigned int n) {
if (n == 0) return NULL;
uint8_t digits[15];
size_t n_digits = base20(n, digits);
size_t line_length = n_digits*5 + 2;
char *str = malloc(line_length * 6 + 1);
if (str == NULL) return NULL;
str[line_length * 6] = 0;
char *ptr;
unsigned int i;
for (ptr=str, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "+----", 5);
memcpy(ptr-5, "+\n", 2);
memcpy(str+5*line_length, str, line_length);
for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "| ", 5);
memcpy(ptr-5, "|\n", 2);
memcpy(str+2*line_length, str+line_length, line_length);
memcpy(str+3*line_length, str+line_length, 2*line_length);
for (i=0; i<n_digits; i++)
make_digit(digits[i], str+1+5*i, line_length);
return str;
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: mayan <number>\n");
return 1;
}
int i = atoi(argv[1]);
if (i <= 0) {
fprintf(stderr, "number must be positive\n");
return 1;
}
char *m = mayan(i);
printf("%s",m);
free(m);
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"math/big"
)
func sf(n int) *big.Int {
if n < 2 {
return big.NewInt(1)
}
sfact := big.NewInt(1)
fact := big.NewInt(1)
for i := 2; i <= n; i++ {
fact.Mul(fact, big.NewInt(int64(i)))
sfact.Mul(sfact, fact)
}
return sfact
}
func H(n int) *big.Int {
if n < 2 {
return big.NewInt(1)
}
hfact := big.NewInt(1)
for i := 2; i <= n; i++ {
bi := big.NewInt(int64(i))
hfact.Mul(hfact, bi.Exp(bi, bi, nil))
}
return hfact
}
func af(n int) *big.Int {
if n < 1 {
return new(big.Int)
}
afact := new(big.Int)
fact := big.NewInt(1)
sign := new(big.Int)
if n%2 == 0 {
sign.SetInt64(-1)
} else {
sign.SetInt64(1)
}
t := new(big.Int)
for i := 1; i <= n; i++ {
fact.Mul(fact, big.NewInt(int64(i)))
afact.Add(afact, t.Mul(fact, sign))
sign.Neg(sign)
}
return afact
}
func ef(n int) *big.Int {
if n < 1 {
return big.NewInt(1)
}
t := big.NewInt(int64(n))
return t.Exp(t, ef(n-1), nil)
}
func rf(n *big.Int) int {
i := 0
fact := big.NewInt(1)
for {
if fact.Cmp(n) == 0 {
return i
}
if fact.Cmp(n) > 0 {
return -1
}
i++
fact.Mul(fact, big.NewInt(int64(i)))
}
}
func main() {
fmt.Println("First 10 superfactorials:")
for i := 0; i < 10; i++ {
fmt.Println(sf(i))
}
fmt.Println("\nFirst 10 hyperfactorials:")
for i := 0; i < 10; i++ {
fmt.Println(H(i))
}
fmt.Println("\nFirst 10 alternating factorials:")
for i := 0; i < 10; i++ {
fmt.Print(af(i), " ")
}
fmt.Println("\n\nFirst 5 exponential factorials:")
for i := 0; i <= 4; i++ {
fmt.Print(ef(i), " ")
}
fmt.Println("\n\nThe number of digits in 5$ is", len(ef(5).String()))
fmt.Println("\nReverse factorials:")
facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}
for _, fact := range facts {
bfact := big.NewInt(fact)
rfact := rf(bfact)
srfact := fmt.Sprintf("%d", rfact)
if rfact == -1 {
srfact = "none"
}
fmt.Printf("%4s <- rf(%d)\n", srfact, fact)
}
}
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int inverse_factorial(uint64_t f) {
int p = 1;
int i = 1;
if (f == 1) {
return 0;
}
while (p < f) {
p *= i;
i++;
}
if (p == f) {
return i - 1;
}
return -1;
}
uint64_t super_factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= factorial(i);
}
return result;
}
uint64_t hyper_factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= (uint64_t)powl(i, i);
}
return result;
}
uint64_t alternating_factorial(int n) {
uint64_t result = 0;
int i;
for (i = 1; i <= n; i++) {
if ((n - i) % 2 == 0) {
result += factorial(i);
} else {
result -= factorial(i);
}
}
return result;
}
uint64_t exponential_factorial(int n) {
uint64_t result = 0;
int i;
for (i = 1; i <= n; i++) {
result = (uint64_t)powl(i, (long double)result);
}
return result;
}
void test_factorial(int count, uint64_t(*func)(int), char *name) {
int i;
printf("First %d %s:\n", count, name);
for (i = 0; i < count ; i++) {
printf("%llu ", func(i));
}
printf("\n");
}
void test_inverse(uint64_t f) {
int n = inverse_factorial(f);
if (n < 0) {
printf("rf(%llu) = No Solution\n", f);
} else {
printf("rf(%llu) = %d\n", f, n);
}
}
int main() {
int i;
test_factorial(9, super_factorial, "super factorials");
printf("\n");
test_factorial(8, super_factorial, "hyper factorials");
printf("\n");
test_factorial(10, alternating_factorial, "alternating factorials");
printf("\n");
test_factorial(5, exponential_factorial, "exponential factorials");
printf("\n");
test_inverse(1);
test_inverse(2);
test_inverse(6);
test_inverse(24);
test_inverse(120);
test_inverse(720);
test_inverse(5040);
test_inverse(40320);
test_inverse(362880);
test_inverse(3628800);
test_inverse(119);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"rcu"
)
const MAX = 1e7 - 1
var primes = rcu.Primes(MAX)
func specialNP(limit int, showAll bool) {
if showAll {
fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:")
}
count := 0
for i := 1; i < len(primes); i++ {
p2 := primes[i]
if p2 >= limit {
break
}
p1 := primes[i-1]
p3 := p1 + p2 - 1
if rcu.IsPrime(p3) {
if showAll {
fmt.Printf("(%2d, %2d) => %3d\n", p1, p2, p3)
}
count++
}
}
ccount := rcu.Commatize(count)
climit := rcu.Commatize(limit)
fmt.Printf("\nFound %s special neighbor primes under %s.\n", ccount, climit)
}
func main() {
specialNP(100, true)
var pow = 1000
for i := 3; i < 8; i++ {
specialNP(pow, false)
pow *= 10
}
}
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int main(void) {
int p1, p2;
for(p1=3;p1<=99;p1+=2) {
p2=nextprime(p1);
if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {
printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 );
}
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"rcu"
)
const MAX = 1e7 - 1
var primes = rcu.Primes(MAX)
func specialNP(limit int, showAll bool) {
if showAll {
fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:")
}
count := 0
for i := 1; i < len(primes); i++ {
p2 := primes[i]
if p2 >= limit {
break
}
p1 := primes[i-1]
p3 := p1 + p2 - 1
if rcu.IsPrime(p3) {
if showAll {
fmt.Printf("(%2d, %2d) => %3d\n", p1, p2, p3)
}
count++
}
}
ccount := rcu.Commatize(count)
climit := rcu.Commatize(limit)
fmt.Printf("\nFound %s special neighbor primes under %s.\n", ccount, climit)
}
func main() {
specialNP(100, true)
var pow = 1000
for i := 3; i < 8; i++ {
specialNP(pow, false)
pow *= 10
}
}
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int main(void) {
int p1, p2;
for(p1=3;p1<=99;p1+=2) {
p2=nextprime(p1);
if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {
printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 );
}
}
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import "fmt"
var (
a [17][17]int
idx [4]int
)
func findGroup(ctype, min, max, depth int) bool {
if depth == 4 {
cs := ""
if ctype == 0 {
cs = "un"
}
fmt.Printf("Totally %sconnected group:", cs)
for i := 0; i < 4; i++ {
fmt.Printf(" %d", idx[i])
}
fmt.Println()
return true
}
for i := min; i < max; i++ {
n := 0
for ; n < depth; n++ {
if a[idx[n]][i] != ctype {
break
}
}
if n == depth {
idx[n] = i
if findGroup(ctype, 1, max, depth+1) {
return true
}
}
}
return false
}
func main() {
const mark = "01-"
for i := 0; i < 17; i++ {
a[i][i] = 2
}
for k := 1; k <= 8; k <<= 1 {
for i := 0; i < 17; i++ {
j := (i + k) % 17
a[i][j], a[j][i] = 1, 1
}
}
for i := 0; i < 17; i++ {
for j := 0; j < 17; j++ {
fmt.Printf("%c ", mark[a[i][j]])
}
fmt.Println()
}
for i := 0; i < 17; i++ {
idx[0] = i
if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {
fmt.Println("No good.")
return
}
}
fmt.Println("All good.")
}
| #include <stdio.h>
int a[17][17], idx[4];
int find_group(int type, int min_n, int max_n, int depth)
{
int i, n;
if (depth == 4) {
printf("totally %sconnected group:", type ? "" : "un");
for (i = 0; i < 4; i++) printf(" %d", idx[i]);
putchar('\n');
return 1;
}
for (i = min_n; i < max_n; i++) {
for (n = 0; n < depth; n++)
if (a[idx[n]][i] != type) break;
if (n == depth) {
idx[n] = i;
if (find_group(type, 1, max_n, depth + 1))
return 1;
}
}
return 0;
}
int main()
{
int i, j, k;
const char *mark = "01-";
for (i = 0; i < 17; i++)
a[i][i] = 2;
for (k = 1; k <= 8; k <<= 1) {
for (i = 0; i < 17; i++) {
j = (i + k) % 17;
a[i][j] = a[j][i] = 1;
}
}
for (i = 0; i < 17; i++) {
for (j = 0; j < 17; j++)
printf("%c ", mark[a[i][j]]);
putchar('\n');
}
for (i = 0; i < 17; i++) {
idx[0] = i;
if (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {
puts("no good");
return 0;
}
}
puts("all good");
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"github.com/go-vgo/robotgo"
)
func main() {
w, h := robotgo.GetScreenSize()
fmt.Printf("Screen size: %d x %d\n", w, h)
fpid, err := robotgo.FindIds("firefox")
if err == nil && len(fpid) > 0 {
pid := fpid[0]
robotgo.ActivePID(pid)
robotgo.MaxWindow(pid)
_, _, w, h = robotgo.GetBounds(pid)
fmt.Printf("Max usable : %d x %d\n", w, h)
}
}
| #include<windows.h>
#include<stdio.h>
int main()
{
printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
tput("rev")
fmt.Print("Rosetta")
tput("sgr0")
fmt.Println(" Code")
}
func tput(arg string) error {
cmd := exec.Command("tput", arg)
cmd.Stdout = os.Stdout
return cmd.Run()
}
| #include <stdio.h>
int main()
{
printf("\033[7mReversed\033[m Normal\n");
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"math"
"strings"
)
func main() {
for _, n := range [...]int64{
0, 4, 6, 11, 13, 75, 100, 337, -164,
math.MaxInt64,
} {
fmt.Println(fourIsMagic(n))
}
}
func fourIsMagic(n int64) string {
s := say(n)
s = strings.ToUpper(s[:1]) + s[1:]
t := s
for n != 4 {
n = int64(len(s))
s = say(n)
t += " is " + s + ", " + s
}
t += " is magic."
return t
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
| #include <stdint.h>
#include <stdio.h>
#include <glib.h>
typedef struct named_number_tag {
const char* name;
uint64_t number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 1000000000000 },
{ "quadrillion", 1000000000000000ULL },
{ "quintillion", 1000000000000000000ULL }
};
const named_number* get_named_number(uint64_t n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_number);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
size_t append_number_name(GString* str, uint64_t n) {
static const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
static const char* tens[] = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
size_t len = str->len;
if (n < 20) {
g_string_append(str, small[n]);
}
else if (n < 100) {
g_string_append(str, tens[n/10 - 2]);
if (n % 10 != 0) {
g_string_append_c(str, '-');
g_string_append(str, small[n % 10]);
}
} else {
const named_number* num = get_named_number(n);
uint64_t p = num->number;
append_number_name(str, n/p);
g_string_append_c(str, ' ');
g_string_append(str, num->name);
if (n % p != 0) {
g_string_append_c(str, ' ');
append_number_name(str, n % p);
}
}
return str->len - len;
}
GString* magic(uint64_t n) {
GString* str = g_string_new(NULL);
for (unsigned int i = 0; ; ++i) {
size_t count = append_number_name(str, n);
if (i == 0)
str->str[0] = g_ascii_toupper(str->str[0]);
if (n == 4) {
g_string_append(str, " is magic.");
break;
}
g_string_append(str, " is ");
append_number_name(str, count);
g_string_append(str, ", ");
n = count;
}
return str;
}
void test_magic(uint64_t n) {
GString* str = magic(n);
printf("%s\n", str->str);
g_string_free(str, TRUE);
}
int main() {
test_magic(5);
test_magic(13);
test_magic(78);
test_magic(797);
test_magic(2739);
test_magic(4000);
test_magic(7893);
test_magic(93497412);
test_magic(2673497412U);
test_magic(10344658531277200972ULL);
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"log"
"os/exec"
"strings"
"time"
)
func main() {
s := "Actions speak louder than words."
prev := ""
prevLen := 0
bs := ""
for _, word := range strings.Fields(s) {
cmd := exec.Command("espeak", word)
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
if prevLen > 0 {
bs = strings.Repeat("\b", prevLen)
}
fmt.Printf("%s%s%s ", bs, prev, strings.ToUpper(word))
prev = word + " "
prevLen = len(word) + 1
}
bs = strings.Repeat("\b", prevLen)
time.Sleep(time.Second)
fmt.Printf("%s%s\n", bs, prev)
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
void C_espeak(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 10];
strcpy(command, "espeak \"");
strcat(command, arg);
strcat(command, "\"");
system(command);
}
void C_flushStdout(WrenVM* vm) {
fflush(stdout);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
if (isStatic && strcmp(signature, "espeak(_)") == 0) return C_espeak;
if (isStatic && strcmp(signature, "flushStdout()") == 0) return C_flushStdout;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "speech_engine_highlight_words.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"log"
"os/exec"
"strings"
"time"
)
func main() {
s := "Actions speak louder than words."
prev := ""
prevLen := 0
bs := ""
for _, word := range strings.Fields(s) {
cmd := exec.Command("espeak", word)
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
if prevLen > 0 {
bs = strings.Repeat("\b", prevLen)
}
fmt.Printf("%s%s%s ", bs, prev, strings.ToUpper(word))
prev = word + " "
prevLen = len(word) + 1
}
bs = strings.Repeat("\b", prevLen)
time.Sleep(time.Second)
fmt.Printf("%s%s\n", bs, prev)
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
void C_espeak(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 10];
strcpy(command, "espeak \"");
strcat(command, arg);
strcat(command, "\"");
system(command);
}
void C_flushStdout(WrenVM* vm) {
fflush(stdout);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
if (isStatic && strcmp(signature, "espeak(_)") == 0) return C_espeak;
if (isStatic && strcmp(signature, "flushStdout()") == 0) return C_flushStdout;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "speech_engine_highlight_words.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"log"
"math"
"strings"
)
var error = "Argument must be a numeric literal or a decimal numeric string."
func getNumDecimals(n interface{}) int {
switch v := n.(type) {
case int:
return 0
case float64:
if v == math.Trunc(v) {
return 0
}
s := fmt.Sprintf("%g", v)
return len(strings.Split(s, ".")[1])
case string:
if v == "" {
log.Fatal(error)
}
if v[0] == '+' || v[0] == '-' {
v = v[1:]
}
for _, c := range v {
if strings.IndexRune("0123456789.", c) == -1 {
log.Fatal(error)
}
}
s := strings.Split(v, ".")
ls := len(s)
if ls == 1 {
return 0
} else if ls == 2 {
return len(s[1])
} else {
log.Fatal("Too many decimal points")
}
default:
log.Fatal(error)
}
return 0
}
func main() {
var a = []interface{}{12, 12.345, 12.345555555555, "12.3450", "12.34555555555555555555", 12.345e53}
for _, n := range a {
d := getNumDecimals(n)
switch v := n.(type) {
case string:
fmt.Printf("%q has %d decimals\n", v, d)
case float32, float64:
fmt.Printf("%g has %d decimals\n", v, d)
default:
fmt.Printf("%d has %d decimals\n", v, d)
}
}
}
| #include <stdio.h>
int findNumOfDec(double x) {
char buffer[128];
int pos, num;
sprintf(buffer, "%.14f", x);
pos = 0;
num = 0;
while (buffer[pos] != 0 && buffer[pos] != '.') {
pos++;
}
if (buffer[pos] != 0) {
pos++;
while (buffer[pos] != 0) {
pos++;
}
pos--;
while (buffer[pos] == '0') {
pos--;
}
while (buffer[pos] != '.') {
num++;
pos--;
}
}
return num;
}
void test(double x) {
int num = findNumOfDec(x);
printf("%f has %d decimals\n", x, num);
}
int main() {
test(12.0);
test(12.345);
test(12.345555555555);
test(12.3450);
test(12.34555555555555555555);
test(1.2345e+54);
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | const (
apple = iota
banana
cherry
)
| enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"math/big"
)
const branches = 4
const nMax = 500
var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)
func tree(br, n, l, sum int, cnt *big.Int) {
for b := br + 1; b <= branches; b++ {
sum += n
if sum > nMax {
return
}
if l*2 >= sum && b >= branches {
return
}
if b == br+1 {
c[br].Mul(&rooted[n], cnt)
} else {
tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
c[br].Mul(&c[br], tmp)
c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
}
if l*2 < sum {
unrooted[sum].Add(&unrooted[sum], &c[br])
}
if b < branches {
rooted[sum].Add(&rooted[sum], &c[br])
}
for m := n - 1; m > 0; m-- {
tree(b, m, l, sum, &c[br])
}
}
}
func bicenter(s int) {
if s&1 == 0 {
tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
unrooted[s].Add(&unrooted[s], tmp)
}
}
func main() {
rooted[0].SetInt64(1)
rooted[1].SetInt64(1)
unrooted[0].SetInt64(1)
unrooted[1].SetInt64(1)
for n := 1; n <= nMax; n++ {
tree(0, n, n, 1, big.NewInt(1))
bicenter(n)
fmt.Printf("%d: %d\n", n, &unrooted[n])
}
}
| #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
for (b = br + 1; b <= BRANCH; b++) {
s = sum + (b - br) * n;
if (s >= MAX_N) return;
c = choose(rooted[n], b - br) * cnt;
if (l * 2 < s) unrooted[s] += c;
if (b == BRANCH) return;
rooted[s] += c;
for (m = n; --m; ) tree(b, m, c, s, l);
}
}
void bicenter(int s)
{
if (s & 1) return;
unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}
int main()
{
xint n;
for (n = 1; n < MAX_N; n++) {
tree(0, n, 1, 1, n);
bicenter(n);
printf("%"FMT": %"FMT"\n", n, unrooted[n]);
}
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"math/big"
)
const branches = 4
const nMax = 500
var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)
func tree(br, n, l, sum int, cnt *big.Int) {
for b := br + 1; b <= branches; b++ {
sum += n
if sum > nMax {
return
}
if l*2 >= sum && b >= branches {
return
}
if b == br+1 {
c[br].Mul(&rooted[n], cnt)
} else {
tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
c[br].Mul(&c[br], tmp)
c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
}
if l*2 < sum {
unrooted[sum].Add(&unrooted[sum], &c[br])
}
if b < branches {
rooted[sum].Add(&rooted[sum], &c[br])
}
for m := n - 1; m > 0; m-- {
tree(b, m, l, sum, &c[br])
}
}
}
func bicenter(s int) {
if s&1 == 0 {
tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
unrooted[s].Add(&unrooted[s], tmp)
}
}
func main() {
rooted[0].SetInt64(1)
rooted[1].SetInt64(1)
unrooted[0].SetInt64(1)
unrooted[1].SetInt64(1)
for n := 1; n <= nMax; n++ {
tree(0, n, n, 1, big.NewInt(1))
bicenter(n)
fmt.Printf("%d: %d\n", n, &unrooted[n])
}
}
| #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
for (b = br + 1; b <= BRANCH; b++) {
s = sum + (b - br) * n;
if (s >= MAX_N) return;
c = choose(rooted[n], b - br) * cnt;
if (l * 2 < s) unrooted[s] += c;
if (b == BRANCH) return;
rooted[s] += c;
for (m = n; --m; ) tree(b, m, c, s, l);
}
}
void bicenter(int s)
{
if (s & 1) return;
unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}
int main()
{
xint n;
for (n = 1; n < MAX_N; n++) {
tree(0, n, 1, 1, n);
bicenter(n);
printf("%"FMT": %"FMT"\n", n, unrooted[n]);
}
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import "fmt"
func printMinCells(n int) {
fmt.Printf("Minimum number of cells after, before, above and below %d x %d square:\n", n, n)
p := 1
if n > 20 {
p = 2
}
for r := 0; r < n; r++ {
cells := make([]int, n)
for c := 0; c < n; c++ {
nums := []int{n - r - 1, r, c, n - c - 1}
min := n
for _, num := range nums {
if num < min {
min = num
}
}
cells[c] = min
}
fmt.Printf("%*d \n", p, cells)
}
}
func main() {
for _, n := range []int{23, 10, 9, 2, 1} {
printMinCells(n)
fmt.Println()
}
}
| #include<stdio.h>
#include<stdlib.h>
#define min(a, b) (a<=b?a:b)
void minab( unsigned int n ) {
int i, j;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf( "%2d ", min( min(i, n-1-i), min(j, n-1-j) ));
}
printf( "\n" );
}
return;
}
int main(void) {
minab(10);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1)
dc.Clear()
for i := 0; i <= 5; i++ {
index := (i * 2) % 5
p := points[index]
dc.LineTo(p.X, p.Y)
}
dc.SetHexColor("#6495ED")
dc.SetFillRule(gg.FillRuleWinding)
dc.FillPreserve()
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(5)
dc.Stroke()
dc.SavePNG("pentagram.png")
}
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1)
dc.Clear()
for i := 0; i <= 5; i++ {
index := (i * 2) % 5
p := points[index]
dc.LineTo(p.X, p.Y)
}
dc.SetHexColor("#6495ED")
dc.SetFillRule(gg.FillRuleWinding)
dc.FillPreserve()
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(5)
dc.Stroke()
dc.SavePNG("pentagram.png")
}
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func parseIPPort(address string) (net.IP, *uint64, error) {
ip := net.ParseIP(address)
if ip != nil {
return ip, nil, nil
}
host, portStr, err := net.SplitHostPort(address)
if err != nil {
return nil, nil, fmt.Errorf("splithostport failed: %w", err)
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse port: %w", err)
}
ip = net.ParseIP(host)
if ip == nil {
return nil, nil, fmt.Errorf("failed to parse ip address")
}
return ip, &port, nil
}
func ipVersion(ip net.IP) int {
if ip.To4() == nil {
return 6
}
return 4
}
func main() {
testCases := []string{
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:443",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80",
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
writeTSV := func(w io.Writer, args ...interface{}) {
fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...)
fmt.Fprintf(w, "\n")
}
writeTSV(w, "Input", "Address", "Space", "Port")
for _, addr := range testCases {
ip, port, err := parseIPPort(addr)
if err != nil {
panic(err)
}
portStr := "n/a"
if port != nil {
portStr = fmt.Sprint(*port)
}
ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip))
writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)
}
w.Flush()
}
| #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f,
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10;
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
if ( bIsIPv6local )
{
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else
{
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
abyAddrLocal = abyAddr;
if ( NULL == abyAddrLocal )
abyAddrLocal = abyDummyAddr;
if ( ! bIsIPv6local )
{
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort )
{
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
else
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
if ( NULL != pchOpenBracket )
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL;
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx )
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText );
if ( pszTextBefore == *ppszText )
{
if ( NULL != pbyZerosLoc )
{
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0;
}
if ( ':' != **ppszText )
return 0;
if ( 0 == nIdx )
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText )
{
const char* pszTextlocal = pszTextBefore;
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal;
if ( ! bParseResultlocal || bIsIPv6local )
return 0;
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx;
bIPv4Detected = 1;
break;
}
if ( nVal > 65535 )
return 0;
*(pbyAddrCursor++) = nVal >> 8;
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText )
{
++(*ppszText);
}
else
{
break;
}
}
}
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal );
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
int nZeros = 16 - nTail - nHead;
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
memset ( pbyZerosLoc, 0, nZeros );
}
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort )
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
}
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}
|
Write a version of this Go function in C with identical behavior. | package main
import "C"
import "log"
import "unsafe"
var ps, vs, prog, r_mod C.GLuint
var angle = float32(0)
func render() {
C.glClear(C.GL_COLOR_BUFFER_BIT)
C.glUniform1f_macro(C.GLint(r_mod), C.GLfloat(C.rand())/C.GLfloat(C.RAND_MAX))
C.glLoadIdentity()
C.glRotatef(C.float(angle), C.float(angle*0.1), 1, 0)
C.glBegin(C.GL_TRIANGLES)
C.glVertex3f(-1, -0.5, 0)
C.glVertex3f(0, 1, 0)
C.glVertex3f(1, 0, 0)
C.glEnd()
angle += 0.02
C.glutSwapBuffers()
}
func setShader() {
f := "varying float x, y, z;" +
"uniform float r_mod;" +
"float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }" +
"void main() {" +
" gl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);" +
"}"
v := "varying float x, y, z;" +
"void main() {" +
" gl_Position = ftransform();" +
" x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;" +
" x += y; y -= x; z += x - y;" +
"}"
fc, vc := C.CString(f), C.CString(v)
defer C.free(unsafe.Pointer(fc))
defer C.free(unsafe.Pointer(vc))
vs = C.glCreateShader_macro(C.GL_VERTEX_SHADER)
ps = C.glCreateShader_macro(C.GL_FRAGMENT_SHADER)
C.glShaderSource_macro(ps, 1, &fc, nil)
C.glShaderSource_macro(vs, 1, &vc, nil)
C.glCompileShader_macro(vs)
C.glCompileShader_macro(ps)
prog = C.glCreateProgram_macro()
C.glAttachShader_macro(prog, ps)
C.glAttachShader_macro(prog, vs)
C.glLinkProgram_macro(prog)
C.glUseProgram_macro(prog)
rms := C.CString("r_mod")
r_mod = C.GLuint(C.glGetUniformLocation_macro(prog, rms))
C.free(unsafe.Pointer(rms))
}
func main() {
argc := C.int(0)
C.glutInit(&argc, nil)
C.glutInitDisplayMode(C.GLUT_DOUBLE | C.GLUT_RGB)
C.glutInitWindowSize(200, 200)
tl := "Pixel Shader"
tlc := C.CString(tl)
C.glutCreateWindow(tlc)
defer C.free(unsafe.Pointer(tlc))
C.glutIdleFunc(C.idleFunc())
C.glewInit()
glv := C.CString("GL_VERSION_2_0")
if C.glewIsSupported(glv) == 0 {
log.Fatal("GL 2.0 unsupported")
}
defer C.free(unsafe.Pointer(glv))
setShader()
C.glutMainLoop()
}
| #include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/glut.h>
GLuint ps, vs, prog, r_mod;
float angle = 0;
void render(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glUniform1f(r_mod, rand() / (float)RAND_MAX);
glLoadIdentity();
glRotatef(angle, angle * .1, 1, 0);
glBegin(GL_TRIANGLES);
glVertex3f(-1, -.5, 0);
glVertex3f(0, 1, 0);
glVertex3f(1, 0, 0);
glEnd();
angle += .02;
glutSwapBuffers();
}
void set_shader()
{
const char *f =
"varying float x, y, z;"
"uniform float r_mod;"
"float rand(float s, float r) { return mod(mod(s, r + r_mod) * 112341.0, 1.0); }"
"void main() {"
" gl_FragColor = vec4(rand(gl_FragCoord.x, x), rand(gl_FragCoord.y, y), rand(gl_FragCoord.z, z), 1.0);"
"}";
const char *v =
"varying float x, y, z;"
"void main() {"
" gl_Position = ftransform();"
" x = gl_Position.x; y = gl_Position.y; z = gl_Position.z;"
" x += y; y -= x; z += x - y;"
"}";
vs = glCreateShader(GL_VERTEX_SHADER);
ps = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(ps, 1, &f, 0);
glShaderSource(vs, 1, &v, 0);
glCompileShader(vs);
glCompileShader(ps);
prog = glCreateProgram();
glAttachShader(prog, ps);
glAttachShader(prog, vs);
glLinkProgram(prog);
glUseProgram(prog);
r_mod = glGetUniformLocation(prog, "r_mod");
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(200, 200);
glutCreateWindow("Stuff");
glutIdleFunc(render);
glewInit();
if (!glewIsSupported("GL_VERSION_2_0")) {
fprintf(stderr, "GL 2.0 unsupported\n");
return 1;
}
set_shader();
glutMainLoop();
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
gc "github.com/rthornton128/goncurses"
"log"
"math/rand"
"time"
)
const rowDelay = 40000
func main() {
start := time.Now()
rand.Seed(time.Now().UnixNano())
chars := []byte("0123456789")
totalChars := len(chars)
stdscr, err := gc.Init()
if err != nil {
log.Fatal("init", err)
}
defer gc.End()
gc.Echo(false)
gc.Cursor(0)
if !gc.HasColors() {
log.Fatal("Program requires a colour capable terminal")
}
if err := gc.StartColor(); err != nil {
log.Fatal(err)
}
if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {
log.Fatal("InitPair failed: ", err)
}
stdscr.ColorOn(1)
maxY, maxX := stdscr.MaxYX()
columnsRow := make([]int, maxX)
columnsActive := make([]int, maxX)
for i := 0; i < maxX; i++ {
columnsRow[i] = -1
columnsActive[i] = 0
}
for {
for i := 0; i < maxX; i++ {
if columnsRow[i] == -1 {
columnsRow[i] = rand.Intn(maxY + 1)
columnsActive[i] = rand.Intn(2)
}
}
for i := 0; i < maxX; i++ {
if columnsActive[i] == 1 {
charIndex := rand.Intn(totalChars)
stdscr.MovePrintf(columnsRow[i], i, "%c", chars[charIndex])
} else {
stdscr.MovePrintf(columnsRow[i], i, "%c", ' ')
}
columnsRow[i]++
if columnsRow[i] >= maxY {
columnsRow[i] = -1
}
if rand.Intn(1001) == 0 {
if columnsActive[i] == 0 {
columnsActive[i] = 1
} else {
columnsActive[i] = 0
}
}
}
time.Sleep(rowDelay * time.Microsecond)
stdscr.Refresh()
elapsed := time.Since(start)
if elapsed.Minutes() >= 1 {
break
}
}
}
|
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#define ROW_DELAY 40000
int get_rand_in_range(int min, int max)
{
return (rand() % ((max + 1) - min) + min);
}
int main(void)
{
srand(time(NULL));
char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int total_chars = sizeof(chars);
initscr();
noecho();
curs_set(FALSE);
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
attron(COLOR_PAIR(1));
int max_x = 0, max_y = 0;
getmaxyx(stdscr, max_y, max_x);
int columns_row[max_x];
int columns_active[max_x];
int i;
for (i = 0; i < max_x; i++)
{
columns_row[i] = -1;
columns_active[i] = 0;
}
while (1)
{
for (i = 0; i < max_x; i++)
{
if (columns_row[i] == -1)
{
columns_row[i] = get_rand_in_range(0, max_y);
columns_active[i] = get_rand_in_range(0, 1);
}
}
for (i = 0; i < max_x; i++)
{
if (columns_active[i] == 1)
{
int char_index = get_rand_in_range(0, total_chars);
mvprintw(columns_row[i], i, "%c", chars[char_index]);
}
else
{
mvprintw(columns_row[i], i, " ");
}
columns_row[i]++;
if (columns_row[i] >= max_y)
{
columns_row[i] = -1;
}
if (get_rand_in_range(0, 1000) == 0)
{
columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
}
}
usleep(ROW_DELAY);
refresh();
}
endwin();
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
gc "github.com/rthornton128/goncurses"
"log"
"math/rand"
"time"
)
const rowDelay = 40000
func main() {
start := time.Now()
rand.Seed(time.Now().UnixNano())
chars := []byte("0123456789")
totalChars := len(chars)
stdscr, err := gc.Init()
if err != nil {
log.Fatal("init", err)
}
defer gc.End()
gc.Echo(false)
gc.Cursor(0)
if !gc.HasColors() {
log.Fatal("Program requires a colour capable terminal")
}
if err := gc.StartColor(); err != nil {
log.Fatal(err)
}
if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {
log.Fatal("InitPair failed: ", err)
}
stdscr.ColorOn(1)
maxY, maxX := stdscr.MaxYX()
columnsRow := make([]int, maxX)
columnsActive := make([]int, maxX)
for i := 0; i < maxX; i++ {
columnsRow[i] = -1
columnsActive[i] = 0
}
for {
for i := 0; i < maxX; i++ {
if columnsRow[i] == -1 {
columnsRow[i] = rand.Intn(maxY + 1)
columnsActive[i] = rand.Intn(2)
}
}
for i := 0; i < maxX; i++ {
if columnsActive[i] == 1 {
charIndex := rand.Intn(totalChars)
stdscr.MovePrintf(columnsRow[i], i, "%c", chars[charIndex])
} else {
stdscr.MovePrintf(columnsRow[i], i, "%c", ' ')
}
columnsRow[i]++
if columnsRow[i] >= maxY {
columnsRow[i] = -1
}
if rand.Intn(1001) == 0 {
if columnsActive[i] == 0 {
columnsActive[i] = 1
} else {
columnsActive[i] = 0
}
}
}
time.Sleep(rowDelay * time.Microsecond)
stdscr.Refresh()
elapsed := time.Since(start)
if elapsed.Minutes() >= 1 {
break
}
}
}
|
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#define ROW_DELAY 40000
int get_rand_in_range(int min, int max)
{
return (rand() % ((max + 1) - min) + min);
}
int main(void)
{
srand(time(NULL));
char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int total_chars = sizeof(chars);
initscr();
noecho();
curs_set(FALSE);
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
attron(COLOR_PAIR(1));
int max_x = 0, max_y = 0;
getmaxyx(stdscr, max_y, max_x);
int columns_row[max_x];
int columns_active[max_x];
int i;
for (i = 0; i < max_x; i++)
{
columns_row[i] = -1;
columns_active[i] = 0;
}
while (1)
{
for (i = 0; i < max_x; i++)
{
if (columns_row[i] == -1)
{
columns_row[i] = get_rand_in_range(0, max_y);
columns_active[i] = get_rand_in_range(0, 1);
}
}
for (i = 0; i < max_x; i++)
{
if (columns_active[i] == 1)
{
int char_index = get_rand_in_range(0, total_chars);
mvprintw(columns_row[i], i, "%c", chars[char_index]);
}
else
{
mvprintw(columns_row[i], i, " ");
}
columns_row[i]++;
if (columns_row[i] >= max_y)
{
columns_row[i] = -1;
}
if (get_rand_in_range(0, 1000) == 0)
{
columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
}
}
usleep(ROW_DELAY);
refresh();
}
endwin();
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
fileName := "loop.wav"
scanner := bufio.NewScanner(os.Stdin)
reps := 0
for reps < 1 || reps > 6 {
fmt.Print("Enter number of repetitions (1 to 6) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
reps, _ = strconv.Atoi(input)
}
delay := 0
for delay < 50 || delay > 500 {
fmt.Print("Enter delay between repetitions in microseconds (50 to 500) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
delay, _ = strconv.Atoi(input)
}
decay := 0.0
for decay < 0.2 || decay > 0.9 {
fmt.Print("Enter decay between repetitions (0.2 to 0.9) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
decay, _ = strconv.ParseFloat(input, 64)
}
args := []string{fileName, "echo", "0.8", "0.7"}
decay2 := 1.0
for i := 1; i <= reps; i++ {
delayStr := strconv.Itoa(i * delay)
decay2 *= decay
decayStr := strconv.FormatFloat(decay2, 'f', -1, 64)
args = append(args, delayStr, decayStr)
}
cmd := exec.Command("play", args...)
err := cmd.Run()
check(err)
}
| #include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
void C_play(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 5];
strcpy(command, "play ");
strcat(command, args);
system(command);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "play(_)") == 0) return C_play;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "audio_overlap_loop.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
fileName := "loop.wav"
scanner := bufio.NewScanner(os.Stdin)
reps := 0
for reps < 1 || reps > 6 {
fmt.Print("Enter number of repetitions (1 to 6) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
reps, _ = strconv.Atoi(input)
}
delay := 0
for delay < 50 || delay > 500 {
fmt.Print("Enter delay between repetitions in microseconds (50 to 500) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
delay, _ = strconv.Atoi(input)
}
decay := 0.0
for decay < 0.2 || decay > 0.9 {
fmt.Print("Enter decay between repetitions (0.2 to 0.9) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
decay, _ = strconv.ParseFloat(input, 64)
}
args := []string{fileName, "echo", "0.8", "0.7"}
decay2 := 1.0
for i := 1; i <= reps; i++ {
delayStr := strconv.Itoa(i * delay)
decay2 *= decay
decayStr := strconv.FormatFloat(decay2, 'f', -1, 64)
args = append(args, delayStr, decayStr)
}
cmd := exec.Command("play", args...)
err := cmd.Run()
check(err)
}
| #include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
void C_play(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 5];
strcpy(command, "play ");
strcat(command, args);
system(command);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "play(_)") == 0) return C_play;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "audio_overlap_loop.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import "fmt"
type Item struct {
Name string
Value int
Weight, Volume float64
}
type Result struct {
Counts []int
Sum int
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func Knapsack(items []Item, weight, volume float64) (best Result) {
if len(items) == 0 {
return
}
n := len(items) - 1
maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))
for count := 0; count <= maxCount; count++ {
sol := Knapsack(items[:n],
weight-float64(count)*items[n].Weight,
volume-float64(count)*items[n].Volume)
sol.Sum += items[n].Value * count
if sol.Sum > best.Sum {
sol.Counts = append(sol.Counts, count)
best = sol
}
}
return
}
func main() {
items := []Item{
{"Panacea", 3000, 0.3, 0.025},
{"Ichor", 1800, 0.2, 0.015},
{"Gold", 2500, 2.0, 0.002},
}
var sumCount, sumValue int
var sumWeight, sumVolume float64
result := Knapsack(items, 25, 0.25)
for i := range result.Counts {
fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n",
items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),
items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])
sumCount += result.Counts[i]
sumValue += items[i].Value * result.Counts[i]
sumWeight += items[i].Weight * float64(result.Counts[i])
sumVolume += items[i].Volume * float64(result.Counts[i])
}
fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n",
sumCount, sumWeight, sumVolume, sumValue)
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
double value;
double weight;
double volume;
} item_t;
item_t items[] = {
{"panacea", 3000.0, 0.3, 0.025},
{"ichor", 1800.0, 0.2, 0.015},
{"gold", 2500.0, 2.0, 0.002},
};
int n = sizeof (items) / sizeof (item_t);
int *count;
int *best;
double best_value;
void knapsack (int i, double value, double weight, double volume) {
int j, m1, m2, m;
if (i == n) {
if (value > best_value) {
best_value = value;
for (j = 0; j < n; j++) {
best[j] = count[j];
}
}
return;
}
m1 = weight / items[i].weight;
m2 = volume / items[i].volume;
m = m1 < m2 ? m1 : m2;
for (count[i] = m; count[i] >= 0; count[i]--) {
knapsack(
i + 1,
value + count[i] * items[i].value,
weight - count[i] * items[i].weight,
volume - count[i] * items[i].volume
);
}
}
int main () {
count = malloc(n * sizeof (int));
best = malloc(n * sizeof (int));
best_value = 0;
knapsack(0, 0.0, 25.0, 0.25);
int i;
for (i = 0; i < n; i++) {
printf("%d %s\n", best[i], items[i].name);
}
printf("best value: %.0f\n", best_value);
free(count); free(best);
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var pack [52]byte
for i := 0; i < 26; i++ {
pack[i] = 'R'
pack[26+i] = 'B'
}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(52, func(i, j int) {
pack[i], pack[j] = pack[j], pack[i]
})
var red, black, discard []byte
for i := 0; i < 51; i += 2 {
switch pack[i] {
case 'B':
black = append(black, pack[i+1])
case 'R':
red = append(red, pack[i+1])
}
discard = append(discard, pack[i])
}
lr, lb, ld := len(red), len(black), len(discard)
fmt.Println("After dealing the cards the state of the stacks is:")
fmt.Printf(" Red : %2d cards -> %c\n", lr, red)
fmt.Printf(" Black : %2d cards -> %c\n", lb, black)
fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard)
min := lr
if lb < min {
min = lb
}
n := 1 + rand.Intn(min)
rp := rand.Perm(lr)[:n]
bp := rand.Perm(lb)[:n]
fmt.Printf("\n%d card(s) are to be swapped.\n\n", n)
fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:")
fmt.Printf(" Red : %2d\n", rp)
fmt.Printf(" Black : %2d\n", bp)
for i := 0; i < n; i++ {
red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]
}
fmt.Println("\nAfter swapping, the state of the red and black stacks is:")
fmt.Printf(" Red : %c\n", red)
fmt.Printf(" Black : %c\n", black)
rcount, bcount := 0, 0
for _, c := range red {
if c == 'R' {
rcount++
}
}
for _, c := range black {
if c == 'B' {
bcount++
}
}
fmt.Println("\nThe number of red cards in the red stack =", rcount)
fmt.Println("The number of black cards in the black stack =", bcount)
if rcount == bcount {
fmt.Println("So the asssertion is correct!")
} else {
fmt.Println("So the asssertion is incorrect!")
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = "HCDS";
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
#if PRINT_DISCARDED
printf("Discarded:");
#endif
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top);
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var pack [52]byte
for i := 0; i < 26; i++ {
pack[i] = 'R'
pack[26+i] = 'B'
}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(52, func(i, j int) {
pack[i], pack[j] = pack[j], pack[i]
})
var red, black, discard []byte
for i := 0; i < 51; i += 2 {
switch pack[i] {
case 'B':
black = append(black, pack[i+1])
case 'R':
red = append(red, pack[i+1])
}
discard = append(discard, pack[i])
}
lr, lb, ld := len(red), len(black), len(discard)
fmt.Println("After dealing the cards the state of the stacks is:")
fmt.Printf(" Red : %2d cards -> %c\n", lr, red)
fmt.Printf(" Black : %2d cards -> %c\n", lb, black)
fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard)
min := lr
if lb < min {
min = lb
}
n := 1 + rand.Intn(min)
rp := rand.Perm(lr)[:n]
bp := rand.Perm(lb)[:n]
fmt.Printf("\n%d card(s) are to be swapped.\n\n", n)
fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:")
fmt.Printf(" Red : %2d\n", rp)
fmt.Printf(" Black : %2d\n", bp)
for i := 0; i < n; i++ {
red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]
}
fmt.Println("\nAfter swapping, the state of the red and black stacks is:")
fmt.Printf(" Red : %c\n", red)
fmt.Printf(" Black : %c\n", black)
rcount, bcount := 0, 0
for _, c := range red {
if c == 'R' {
rcount++
}
}
for _, c := range black {
if c == 'B' {
bcount++
}
}
fmt.Println("\nThe number of red cards in the red stack =", rcount)
fmt.Println("The number of black cards in the black stack =", bcount)
if rcount == bcount {
fmt.Println("So the asssertion is correct!")
} else {
fmt.Println("So the asssertion is incorrect!")
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = "HCDS";
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
#if PRINT_DISCARDED
printf("Discarded:");
#endif
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top);
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var pack [52]byte
for i := 0; i < 26; i++ {
pack[i] = 'R'
pack[26+i] = 'B'
}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(52, func(i, j int) {
pack[i], pack[j] = pack[j], pack[i]
})
var red, black, discard []byte
for i := 0; i < 51; i += 2 {
switch pack[i] {
case 'B':
black = append(black, pack[i+1])
case 'R':
red = append(red, pack[i+1])
}
discard = append(discard, pack[i])
}
lr, lb, ld := len(red), len(black), len(discard)
fmt.Println("After dealing the cards the state of the stacks is:")
fmt.Printf(" Red : %2d cards -> %c\n", lr, red)
fmt.Printf(" Black : %2d cards -> %c\n", lb, black)
fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard)
min := lr
if lb < min {
min = lb
}
n := 1 + rand.Intn(min)
rp := rand.Perm(lr)[:n]
bp := rand.Perm(lb)[:n]
fmt.Printf("\n%d card(s) are to be swapped.\n\n", n)
fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:")
fmt.Printf(" Red : %2d\n", rp)
fmt.Printf(" Black : %2d\n", bp)
for i := 0; i < n; i++ {
red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]]
}
fmt.Println("\nAfter swapping, the state of the red and black stacks is:")
fmt.Printf(" Red : %c\n", red)
fmt.Printf(" Black : %c\n", black)
rcount, bcount := 0, 0
for _, c := range red {
if c == 'R' {
rcount++
}
}
for _, c := range black {
if c == 'B' {
bcount++
}
}
fmt.Println("\nThe number of red cards in the red stack =", rcount)
fmt.Println("The number of black cards in the black stack =", bcount)
if rcount == bcount {
fmt.Println("So the asssertion is correct!")
} else {
fmt.Println("So the asssertion is incorrect!")
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = "HCDS";
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
#if PRINT_DISCARDED
printf("Discarded:");
#endif
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top);
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
func main() {
log.SetFlags(0)
log.SetPrefix("textonyms: ")
wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
t := NewTextonym(phoneMap)
_, err := ReadFromFile(t, *wordlist)
if err != nil {
log.Fatal(err)
}
t.Report(os.Stdout, *wordlist)
}
var phoneMap = map[byte][]rune{
'2': []rune("ABC"),
'3': []rune("DEF"),
'4': []rune("GHI"),
'5': []rune("JKL"),
'6': []rune("MNO"),
'7': []rune("PQRS"),
'8': []rune("TUV"),
'9': []rune("WXYZ"),
}
func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
n, err := r.ReadFrom(f)
if cerr := f.Close(); err == nil && cerr != nil {
err = cerr
}
return n, err
}
type Textonym struct {
numberMap map[string][]string
letterMap map[rune]byte
count int
textonyms int
}
func NewTextonym(dm map[byte][]rune) *Textonym {
lm := make(map[rune]byte, 26)
for d, ll := range dm {
for _, l := range ll {
lm[l] = d
}
}
return &Textonym{letterMap: lm}
}
func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {
t.numberMap = make(map[string][]string)
buf := make([]byte, 0, 32)
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
scan:
for sc.Scan() {
buf = buf[:0]
word := sc.Text()
n += int64(len(word)) + 1
for _, r := range word {
d, ok := t.letterMap[unicode.ToUpper(r)]
if !ok {
continue scan
}
buf = append(buf, d)
}
num := string(buf)
t.numberMap[num] = append(t.numberMap[num], word)
t.count++
if len(t.numberMap[num]) == 2 {
t.textonyms++
}
}
return n, sc.Err()
}
func (t *Textonym) Most() (most int, subset map[string][]string) {
for k, v := range t.numberMap {
switch {
case len(v) > most:
subset = make(map[string][]string)
most = len(v)
fallthrough
case len(v) == most:
subset[k] = v
}
}
return most, subset
}
func (t *Textonym) Report(w io.Writer, name string) {
fmt.Fprintf(w, `
There are %v words in %q which can be represented by the digit key mapping.
They require %v digit combinations to represent them.
%v digit combinations represent Textonyms.
`,
t.count, name, len(t.numberMap), t.textonyms)
n, sub := t.Most()
fmt.Fprintln(w, "\nThe numbers mapping to the most words map to",
n, "words each:")
for k, v := range sub {
fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", "))
}
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
return '5';
case 'm': case 'n': case 'o':
return '6';
case 'p': case 'q': case 'r': case 's':
return '7';
case 't': case 'u': case 'v':
return '8';
case 'w': case 'x': case 'y': case 'z':
return '9';
default:
return 0;
}
}
bool text_string(const GString* word, GString* text) {
g_string_set_size(text, word->len);
for (size_t i = 0; i < word->len; ++i) {
char c = text_char(g_ascii_tolower(word->str[i]));
if (c == 0)
return false;
text->str[i] = c;
}
return true;
}
typedef struct textonym_tag {
const char* text;
size_t length;
GPtrArray* words;
} textonym_t;
int compare_by_text_length(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->length > t2->length)
return -1;
if (t1->length < t2->length)
return 1;
return strcmp(t1->text, t2->text);
}
int compare_by_word_count(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->words->len > t2->words->len)
return -1;
if (t1->words->len < t2->words->len)
return 1;
return strcmp(t1->text, t2->text);
}
void print_words(GPtrArray* words) {
for (guint i = 0, n = words->len; i < n; ++i) {
if (i > 0)
printf(", ");
printf("%s", g_ptr_array_index(words, i));
}
printf("\n");
}
void print_top_words(GArray* textonyms, guint top) {
for (guint i = 0; i < top; ++i) {
const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
printf("%s = ", t->text);
print_words(t->words);
}
}
void free_strings(gpointer ptr) {
g_ptr_array_free(ptr, TRUE);
}
bool find_textonyms(const char* filename, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return false;
}
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, free_strings);
GString* word = g_string_sized_new(64);
GString* text = g_string_sized_new(64);
guint count = 0;
gsize term_pos;
while (g_io_channel_read_line_string(channel, word, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
g_string_truncate(word, term_pos);
if (!text_string(word, text))
continue;
GPtrArray* words = g_hash_table_lookup(ht, text->str);
if (words == NULL) {
words = g_ptr_array_new_full(1, g_free);
g_hash_table_insert(ht, g_strdup(text->str), words);
}
g_ptr_array_add(words, g_strdup(word->str));
++count;
}
g_io_channel_unref(channel);
g_string_free(word, TRUE);
g_string_free(text, TRUE);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_hash_table_destroy(ht);
return false;
}
GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
while (g_hash_table_iter_next(&iter, &key, &value)) {
GPtrArray* v = value;
if (v->len > 1) {
textonym_t textonym;
textonym.text = key;
textonym.length = strlen(key);
textonym.words = v;
g_array_append_val(words, textonym);
}
}
printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
count, filename);
guint size = g_hash_table_size(ht);
printf("They require %u digit combinations to represent them.\n", size);
guint textonyms = words->len;
printf("%u digit combinations represent Textonyms.\n", textonyms);
guint top = 5;
if (textonyms < top)
top = textonyms;
printf("\nTop %u by number of words:\n", top);
g_array_sort(words, compare_by_word_count);
print_top_words(words, top);
printf("\nTop %u by length:\n", top);
g_array_sort(words, compare_by_text_length);
print_top_words(words, top);
g_array_free(words, TRUE);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s word-list\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
if (!find_textonyms(argv[1], &error)) {
if (error != NULL) {
fprintf(stderr, "%s: %s\n", argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package raster
const b2Seg = 20
func (b *Bitmap) Bézier2(x1, y1, x2, y2, x3, y3 int, p Pixel) {
var px, py [b2Seg + 1]int
fx1, fy1 := float64(x1), float64(y1)
fx2, fy2 := float64(x2), float64(y2)
fx3, fy3 := float64(x3), float64(y3)
for i := range px {
c := float64(i) / b2Seg
a := 1 - c
a, b, c := a*a, 2 * c * a, c*c
px[i] = int(a*fx1 + b*fx2 + c*fx3)
py[i] = int(a*fy1 + b*fy2 + c*fy3)
}
x0, y0 := px[0], py[0]
for i := 1; i <= b2Seg; i++ {
x1, y1 := px[i], py[i]
b.Line(x0, y0, x1, y1, p)
x0, y0 = x1, y1
}
}
func (b *Bitmap) Bézier2Rgb(x1, y1, x2, y2, x3, y3 int, c Rgb) {
b.Bézier2(x1, y1, x2, y2, x3, y3, c.Pixel())
}
| void quad_bezier(
image img,
unsigned int x1, unsigned int y1,
unsigned int x2, unsigned int y2,
unsigned int x3, unsigned int y3,
color_component r,
color_component g,
color_component b );
|
Please provide an equivalent version of this Go code in C. | package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
const sec = "00:00:01"
scanner := bufio.NewScanner(os.Stdin)
name := ""
for name == "" {
fmt.Print("Enter name of audio file to be trimmed : ")
scanner.Scan()
name = scanner.Text()
check(scanner.Err())
}
name2 := ""
for name2 == "" {
fmt.Print("Enter name of output file : ")
scanner.Scan()
name2 = scanner.Text()
check(scanner.Err())
}
squelch := 0.0
for squelch < 1 || squelch > 10 {
fmt.Print("Enter squelch level % max (1 to 10) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
squelch, _ = strconv.ParseFloat(input, 64)
}
squelchS := strconv.FormatFloat(squelch, 'f', -1, 64) + "%"
tmp1 := "tmp1_" + name
tmp2 := "tmp2_" + name
args := []string{name, tmp1, "silence", "1", sec, squelchS}
cmd := exec.Command("sox", args...)
err := cmd.Run()
check(err)
args = []string{tmp1, tmp2, "reverse"}
cmd = exec.Command("sox", args...)
err = cmd.Run()
check(err)
args = []string{tmp2, tmp1, "silence", "1", sec, squelchS}
cmd = exec.Command("sox", args...)
err = cmd.Run()
check(err)
args = []string{tmp1, name2, "reverse"}
cmd = exec.Command("sox", args...)
err = cmd.Run()
check(err)
err = os.Remove(tmp1)
check(err)
err = os.Remove(tmp2)
check(err)
}
| #include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
void C_getInput(WrenVM* vm) {
int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2;
char input[maxSize];
fgets(input, maxSize, stdin);
__fpurge(stdin);
input[strcspn(input, "\n")] = 0;
wrenSetSlotString(vm, 0, (const char*)input);
}
void C_sox(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 4];
strcpy(command, "sox ");
strcat(command, args);
system(command);
}
void C_removeFile(WrenVM* vm) {
const char *name = wrenGetSlotString(vm, 1);
if (remove(name) != 0) perror("Error deleting file.");
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput;
if (isStatic && strcmp(signature, "sox(_)") == 0) return C_sox;
if (isStatic && strcmp(signature, "removeFile(_)") == 0) return C_removeFile;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "waveform_analysis_top_and_tail.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. |
package astar
import "container/heap"
type Node interface {
To() []Arc
Heuristic(from Node) int
}
type Arc struct {
To Node
Cost int
}
type rNode struct {
n Node
from Node
l int
g int
f int
fx int
}
type openHeap []*rNode
func Route(start, end Node) (route []Node, cost int) {
cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}
r := map[Node]*rNode{start: cr}
oh := openHeap{cr}
for len(oh) > 0 {
bestRoute := heap.Pop(&oh).(*rNode)
bestNode := bestRoute.n
if bestNode == end {
cost = bestRoute.g
route = make([]Node, bestRoute.l)
for i := len(route) - 1; i >= 0; i-- {
route[i] = bestRoute.n
bestRoute = r[bestRoute.from]
}
return
}
l := bestRoute.l + 1
for _, to := range bestNode.To() {
g := bestRoute.g + to.Cost
if alt, ok := r[to.To]; !ok {
alt = &rNode{n: to.To, from: bestNode, l: l,
g: g, f: g + end.Heuristic(to.To)}
r[to.To] = alt
heap.Push(&oh, alt)
} else {
if g >= alt.g {
continue
}
alt.from = bestNode
alt.l = l
alt.g = g
alt.f = end.Heuristic(alt.n)
if alt.fx < 0 {
heap.Push(&oh, alt)
} else {
heap.Fix(&oh, alt.fx)
}
}
}
}
return nil, 0
}
func (h openHeap) Len() int { return len(h) }
func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }
func (h openHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].fx = i
h[j].fx = j
}
func (p *openHeap) Push(x interface{}) {
h := *p
fx := len(h)
h = append(h, x.(*rNode))
h[fx].fx = fx
*p = h
}
func (p *openHeap) Pop() interface{} {
h := *p
last := len(h) - 1
*p = h[:last]
h[last].fx = -1
return h[last]
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
struct stop {
double col, row;
int * n;
int n_len;
double f, g, h;
int from;
};
int ind[map_size_rows][map_size_cols] = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
struct route {
int x;
int y;
double d;
};
int main() {
int i, j, k, l, b, found;
int p_len = 0;
int * path = NULL;
int c_len = 0;
int * closed = NULL;
int o_len = 1;
int * open = (int*)calloc(o_len, sizeof(int));
double min, tempg;
int s;
int e;
int current;
int s_len = 0;
struct stop * stops = NULL;
int r_len = 0;
struct route * routes = NULL;
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (!map[i][j]) {
++s_len;
stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));
int t = s_len - 1;
stops[t].col = j;
stops[t].row = i;
stops[t].from = -1;
stops[t].g = DBL_MAX;
stops[t].n_len = 0;
stops[t].n = NULL;
ind[i][j] = t;
}
}
}
s = 0;
e = s_len - 1;
for (i = 0; i < s_len; i++) {
stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));
}
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (ind[i][j] >= 0) {
for (k = i - 1; k <= i + 1; k++) {
for (l = j - 1; l <= j + 1; l++) {
if ((k == i) and (l == j)) {
continue;
}
if (ind[k][l] >= 0) {
++r_len;
routes = (struct route *)realloc(routes, r_len * sizeof(struct route));
int t = r_len - 1;
routes[t].x = ind[i][j];
routes[t].y = ind[k][l];
routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));
++stops[routes[t].x].n_len;
stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));
stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;
}
}
}
}
}
}
open[0] = s;
stops[s].g = 0;
stops[s].f = stops[s].g + stops[s].h;
found = 0;
while (o_len and not found) {
min = DBL_MAX;
for (i = 0; i < o_len; i++) {
if (stops[open[i]].f < min) {
current = open[i];
min = stops[open[i]].f;
}
}
if (current == e) {
found = 1;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
while (stops[current].from >= 0) {
current = stops[current].from;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
}
}
for (i = 0; i < o_len; i++) {
if (open[i] == current) {
if (i not_eq (o_len - 1)) {
for (j = i; j < (o_len - 1); j++) {
open[j] = open[j + 1];
}
}
--o_len;
open = (int*)realloc(open, o_len * sizeof(int));
break;
}
}
++c_len;
closed = (int*)realloc(closed, c_len * sizeof(int));
closed[c_len - 1] = current;
for (i = 0; i < stops[current].n_len; i++) {
b = 0;
for (j = 0; j < c_len; j++) {
if (routes[stops[current].n[i]].y == closed[j]) {
b = 1;
}
}
if (b) {
continue;
}
tempg = stops[current].g + routes[stops[current].n[i]].d;
b = 1;
if (o_len > 0) {
for (j = 0; j < o_len; j++) {
if (routes[stops[current].n[i]].y == open[j]) {
b = 0;
}
}
}
if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {
stops[routes[stops[current].n[i]].y].from = current;
stops[routes[stops[current].n[i]].y].g = tempg;
stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;
if (b) {
++o_len;
open = (int*)realloc(open, o_len * sizeof(int));
open[o_len - 1] = routes[stops[current].n[i]].y;
}
}
}
}
for (i = 0; i < map_size_rows; i++) {
for (j = 0; j < map_size_cols; j++) {
if (map[i][j]) {
putchar(0xdb);
} else {
b = 0;
for (k = 0; k < p_len; k++) {
if (ind[i][j] == path[k]) {
++b;
}
}
if (b) {
putchar('x');
} else {
putchar('.');
}
}
}
putchar('\n');
}
if (not found) {
puts("IMPOSSIBLE");
} else {
printf("path cost is %d:\n", p_len);
for (i = p_len - 1; i >= 0; i--) {
printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row);
}
}
for (i = 0; i < s_len; ++i) {
free(stops[i].n);
}
free(stops);
free(routes);
free(path);
free(open);
free(closed);
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. |
package astar
import "container/heap"
type Node interface {
To() []Arc
Heuristic(from Node) int
}
type Arc struct {
To Node
Cost int
}
type rNode struct {
n Node
from Node
l int
g int
f int
fx int
}
type openHeap []*rNode
func Route(start, end Node) (route []Node, cost int) {
cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}
r := map[Node]*rNode{start: cr}
oh := openHeap{cr}
for len(oh) > 0 {
bestRoute := heap.Pop(&oh).(*rNode)
bestNode := bestRoute.n
if bestNode == end {
cost = bestRoute.g
route = make([]Node, bestRoute.l)
for i := len(route) - 1; i >= 0; i-- {
route[i] = bestRoute.n
bestRoute = r[bestRoute.from]
}
return
}
l := bestRoute.l + 1
for _, to := range bestNode.To() {
g := bestRoute.g + to.Cost
if alt, ok := r[to.To]; !ok {
alt = &rNode{n: to.To, from: bestNode, l: l,
g: g, f: g + end.Heuristic(to.To)}
r[to.To] = alt
heap.Push(&oh, alt)
} else {
if g >= alt.g {
continue
}
alt.from = bestNode
alt.l = l
alt.g = g
alt.f = end.Heuristic(alt.n)
if alt.fx < 0 {
heap.Push(&oh, alt)
} else {
heap.Fix(&oh, alt.fx)
}
}
}
}
return nil, 0
}
func (h openHeap) Len() int { return len(h) }
func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }
func (h openHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].fx = i
h[j].fx = j
}
func (p *openHeap) Push(x interface{}) {
h := *p
fx := len(h)
h = append(h, x.(*rNode))
h[fx].fx = fx
*p = h
}
func (p *openHeap) Pop() interface{} {
h := *p
last := len(h) - 1
*p = h[:last]
h[last].fx = -1
return h[last]
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
struct stop {
double col, row;
int * n;
int n_len;
double f, g, h;
int from;
};
int ind[map_size_rows][map_size_cols] = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
struct route {
int x;
int y;
double d;
};
int main() {
int i, j, k, l, b, found;
int p_len = 0;
int * path = NULL;
int c_len = 0;
int * closed = NULL;
int o_len = 1;
int * open = (int*)calloc(o_len, sizeof(int));
double min, tempg;
int s;
int e;
int current;
int s_len = 0;
struct stop * stops = NULL;
int r_len = 0;
struct route * routes = NULL;
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (!map[i][j]) {
++s_len;
stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));
int t = s_len - 1;
stops[t].col = j;
stops[t].row = i;
stops[t].from = -1;
stops[t].g = DBL_MAX;
stops[t].n_len = 0;
stops[t].n = NULL;
ind[i][j] = t;
}
}
}
s = 0;
e = s_len - 1;
for (i = 0; i < s_len; i++) {
stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));
}
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (ind[i][j] >= 0) {
for (k = i - 1; k <= i + 1; k++) {
for (l = j - 1; l <= j + 1; l++) {
if ((k == i) and (l == j)) {
continue;
}
if (ind[k][l] >= 0) {
++r_len;
routes = (struct route *)realloc(routes, r_len * sizeof(struct route));
int t = r_len - 1;
routes[t].x = ind[i][j];
routes[t].y = ind[k][l];
routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));
++stops[routes[t].x].n_len;
stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));
stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;
}
}
}
}
}
}
open[0] = s;
stops[s].g = 0;
stops[s].f = stops[s].g + stops[s].h;
found = 0;
while (o_len and not found) {
min = DBL_MAX;
for (i = 0; i < o_len; i++) {
if (stops[open[i]].f < min) {
current = open[i];
min = stops[open[i]].f;
}
}
if (current == e) {
found = 1;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
while (stops[current].from >= 0) {
current = stops[current].from;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
}
}
for (i = 0; i < o_len; i++) {
if (open[i] == current) {
if (i not_eq (o_len - 1)) {
for (j = i; j < (o_len - 1); j++) {
open[j] = open[j + 1];
}
}
--o_len;
open = (int*)realloc(open, o_len * sizeof(int));
break;
}
}
++c_len;
closed = (int*)realloc(closed, c_len * sizeof(int));
closed[c_len - 1] = current;
for (i = 0; i < stops[current].n_len; i++) {
b = 0;
for (j = 0; j < c_len; j++) {
if (routes[stops[current].n[i]].y == closed[j]) {
b = 1;
}
}
if (b) {
continue;
}
tempg = stops[current].g + routes[stops[current].n[i]].d;
b = 1;
if (o_len > 0) {
for (j = 0; j < o_len; j++) {
if (routes[stops[current].n[i]].y == open[j]) {
b = 0;
}
}
}
if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {
stops[routes[stops[current].n[i]].y].from = current;
stops[routes[stops[current].n[i]].y].g = tempg;
stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;
if (b) {
++o_len;
open = (int*)realloc(open, o_len * sizeof(int));
open[o_len - 1] = routes[stops[current].n[i]].y;
}
}
}
}
for (i = 0; i < map_size_rows; i++) {
for (j = 0; j < map_size_cols; j++) {
if (map[i][j]) {
putchar(0xdb);
} else {
b = 0;
for (k = 0; k < p_len; k++) {
if (ind[i][j] == path[k]) {
++b;
}
}
if (b) {
putchar('x');
} else {
putchar('.');
}
}
}
putchar('\n');
}
if (not found) {
puts("IMPOSSIBLE");
} else {
printf("path cost is %d:\n", p_len);
for (i = p_len - 1; i >= 0; i--) {
printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row);
}
}
for (i = 0; i < s_len; ++i) {
free(stops[i].n);
}
free(stops);
free(routes);
free(path);
free(open);
free(closed);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. |
package astar
import "container/heap"
type Node interface {
To() []Arc
Heuristic(from Node) int
}
type Arc struct {
To Node
Cost int
}
type rNode struct {
n Node
from Node
l int
g int
f int
fx int
}
type openHeap []*rNode
func Route(start, end Node) (route []Node, cost int) {
cr := &rNode{n: start, l: 1, f: end.Heuristic(start)}
r := map[Node]*rNode{start: cr}
oh := openHeap{cr}
for len(oh) > 0 {
bestRoute := heap.Pop(&oh).(*rNode)
bestNode := bestRoute.n
if bestNode == end {
cost = bestRoute.g
route = make([]Node, bestRoute.l)
for i := len(route) - 1; i >= 0; i-- {
route[i] = bestRoute.n
bestRoute = r[bestRoute.from]
}
return
}
l := bestRoute.l + 1
for _, to := range bestNode.To() {
g := bestRoute.g + to.Cost
if alt, ok := r[to.To]; !ok {
alt = &rNode{n: to.To, from: bestNode, l: l,
g: g, f: g + end.Heuristic(to.To)}
r[to.To] = alt
heap.Push(&oh, alt)
} else {
if g >= alt.g {
continue
}
alt.from = bestNode
alt.l = l
alt.g = g
alt.f = end.Heuristic(alt.n)
if alt.fx < 0 {
heap.Push(&oh, alt)
} else {
heap.Fix(&oh, alt.fx)
}
}
}
}
return nil, 0
}
func (h openHeap) Len() int { return len(h) }
func (h openHeap) Less(i, j int) bool { return h[i].f < h[j].f }
func (h openHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
h[i].fx = i
h[j].fx = j
}
func (p *openHeap) Push(x interface{}) {
h := *p
fx := len(h)
h = append(h, x.(*rNode))
h[fx].fx = fx
*p = h
}
func (p *openHeap) Pop() interface{} {
h := *p
last := len(h) - 1
*p = h[:last]
h[last].fx = -1
return h[last]
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
struct stop {
double col, row;
int * n;
int n_len;
double f, g, h;
int from;
};
int ind[map_size_rows][map_size_cols] = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
struct route {
int x;
int y;
double d;
};
int main() {
int i, j, k, l, b, found;
int p_len = 0;
int * path = NULL;
int c_len = 0;
int * closed = NULL;
int o_len = 1;
int * open = (int*)calloc(o_len, sizeof(int));
double min, tempg;
int s;
int e;
int current;
int s_len = 0;
struct stop * stops = NULL;
int r_len = 0;
struct route * routes = NULL;
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (!map[i][j]) {
++s_len;
stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));
int t = s_len - 1;
stops[t].col = j;
stops[t].row = i;
stops[t].from = -1;
stops[t].g = DBL_MAX;
stops[t].n_len = 0;
stops[t].n = NULL;
ind[i][j] = t;
}
}
}
s = 0;
e = s_len - 1;
for (i = 0; i < s_len; i++) {
stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));
}
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (ind[i][j] >= 0) {
for (k = i - 1; k <= i + 1; k++) {
for (l = j - 1; l <= j + 1; l++) {
if ((k == i) and (l == j)) {
continue;
}
if (ind[k][l] >= 0) {
++r_len;
routes = (struct route *)realloc(routes, r_len * sizeof(struct route));
int t = r_len - 1;
routes[t].x = ind[i][j];
routes[t].y = ind[k][l];
routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));
++stops[routes[t].x].n_len;
stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));
stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;
}
}
}
}
}
}
open[0] = s;
stops[s].g = 0;
stops[s].f = stops[s].g + stops[s].h;
found = 0;
while (o_len and not found) {
min = DBL_MAX;
for (i = 0; i < o_len; i++) {
if (stops[open[i]].f < min) {
current = open[i];
min = stops[open[i]].f;
}
}
if (current == e) {
found = 1;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
while (stops[current].from >= 0) {
current = stops[current].from;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
}
}
for (i = 0; i < o_len; i++) {
if (open[i] == current) {
if (i not_eq (o_len - 1)) {
for (j = i; j < (o_len - 1); j++) {
open[j] = open[j + 1];
}
}
--o_len;
open = (int*)realloc(open, o_len * sizeof(int));
break;
}
}
++c_len;
closed = (int*)realloc(closed, c_len * sizeof(int));
closed[c_len - 1] = current;
for (i = 0; i < stops[current].n_len; i++) {
b = 0;
for (j = 0; j < c_len; j++) {
if (routes[stops[current].n[i]].y == closed[j]) {
b = 1;
}
}
if (b) {
continue;
}
tempg = stops[current].g + routes[stops[current].n[i]].d;
b = 1;
if (o_len > 0) {
for (j = 0; j < o_len; j++) {
if (routes[stops[current].n[i]].y == open[j]) {
b = 0;
}
}
}
if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {
stops[routes[stops[current].n[i]].y].from = current;
stops[routes[stops[current].n[i]].y].g = tempg;
stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;
if (b) {
++o_len;
open = (int*)realloc(open, o_len * sizeof(int));
open[o_len - 1] = routes[stops[current].n[i]].y;
}
}
}
}
for (i = 0; i < map_size_rows; i++) {
for (j = 0; j < map_size_cols; j++) {
if (map[i][j]) {
putchar(0xdb);
} else {
b = 0;
for (k = 0; k < p_len; k++) {
if (ind[i][j] == path[k]) {
++b;
}
}
if (b) {
putchar('x');
} else {
putchar('.');
}
}
}
putchar('\n');
}
if (not found) {
puts("IMPOSSIBLE");
} else {
printf("path cost is %d:\n", p_len);
for (i = p_len - 1; i >= 0; i--) {
printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row);
}
}
for (i = 0; i < s_len; ++i) {
free(stops[i].n);
}
free(stops);
free(routes);
free(path);
free(open);
free(closed);
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(strings.TrimSpace(scanner.Text()))
if len(word) >= 3 {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func rotate(runes []rune) {
first := runes[0]
copy(runes, runes[1:])
runes[len(runes)-1] = first
}
func main() {
dicts := []string{"mit_10000.txt", "unixdict.txt"}
for _, dict := range dicts {
fmt.Printf("Using %s:\n\n", dict)
words := readWords(dict)
n := len(words)
used := make(map[string]bool)
outer:
for _, word := range words {
runes := []rune(word)
variants := []string{word}
for i := 0; i < len(runes)-1; i++ {
rotate(runes)
word2 := string(runes)
if word == word2 || used[word2] {
continue outer
}
ix := sort.SearchStrings(words, word2)
if ix == n || words[ix] != word2 {
continue outer
}
variants = append(variants, word2)
}
for _, variant := range variants {
used[variant] = true
}
fmt.Println(variants)
}
fmt.Println()
}
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int string_compare(gconstpointer p1, gconstpointer p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return NULL;
}
GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
GString* line = g_string_sized_new(64);
gsize term_pos;
while (g_io_channel_read_line_string(channel, line, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
char* word = g_strdup(line->str);
word[term_pos] = '\0';
g_ptr_array_add(dict, word);
}
g_string_free(line, TRUE);
g_io_channel_unref(channel);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_ptr_array_free(dict, TRUE);
return NULL;
}
g_ptr_array_sort(dict, string_compare);
return dict;
}
void rotate(char* str, size_t len) {
char c = str[0];
memmove(str, str + 1, len - 1);
str[len - 1] = c;
}
char* dictionary_search(const GPtrArray* dictionary, const char* word) {
char** result = bsearch(&word, dictionary->pdata, dictionary->len,
sizeof(char*), string_compare);
return result != NULL ? *result : NULL;
}
void find_teacup_words(GPtrArray* dictionary) {
GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
GPtrArray* teacup_words = g_ptr_array_new();
GString* temp = g_string_sized_new(8);
for (size_t i = 0, n = dictionary->len; i < n; ++i) {
char* word = g_ptr_array_index(dictionary, i);
size_t len = strlen(word);
if (len < 3 || g_hash_table_contains(found, word))
continue;
g_ptr_array_set_size(teacup_words, 0);
g_string_assign(temp, word);
bool is_teacup_word = true;
for (size_t i = 0; i < len - 1; ++i) {
rotate(temp->str, len);
char* w = dictionary_search(dictionary, temp->str);
if (w == NULL) {
is_teacup_word = false;
break;
}
if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
g_ptr_array_add(teacup_words, w);
}
if (is_teacup_word && teacup_words->len > 0) {
printf("%s", word);
g_hash_table_add(found, word);
for (size_t i = 0; i < teacup_words->len; ++i) {
char* teacup_word = g_ptr_array_index(teacup_words, i);
printf(" %s", teacup_word);
g_hash_table_add(found, teacup_word);
}
printf("\n");
}
}
g_string_free(temp, TRUE);
g_ptr_array_free(teacup_words, TRUE);
g_hash_table_destroy(found);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s dictionary\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
GPtrArray* dictionary = load_dictionary(argv[1], &error);
if (dictionary == NULL) {
if (error != NULL) {
fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
find_teacup_words(dictionary);
g_ptr_array_free(dictionary, TRUE);
return EXIT_SUCCESS;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import "fmt"
type is func() uint64
func newSum() is {
var ms is
ms = func() uint64 {
ms = newSum()
return ms()
}
var msd, d uint64
return func() uint64 {
if d < 9 {
d++
} else {
d = 0
msd = ms()
}
return msd + d
}
}
func newHarshard() is {
i := uint64(0)
sum := newSum()
return func() uint64 {
for i++; i%sum() != 0; i++ {
}
return i
}
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("Gap Index of gap Starting Niven")
fmt.Println("=== ============= ==============")
h := newHarshard()
pg := uint64(0)
pn := h()
for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {
g := n - pn
if g > pg {
fmt.Printf("%3d %13s %14s\n", g, commatize(i), commatize(pn))
pg = g
}
pn = n
}
}
| #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t digit_sum(uint64_t n, uint64_t sum) {
++sum;
while (n > 0 && n % 10 == 0) {
sum -= 9;
n /= 10;
}
return sum;
}
inline bool divisible(uint64_t n, uint64_t d) {
if ((d & 1) == 0 && (n & 1) == 1)
return false;
return n % d == 0;
}
int main() {
setlocale(LC_ALL, "");
uint64_t previous = 1, gap = 0, sum = 0;
int niven_index = 0, gap_index = 1;
printf("Gap index Gap Niven index Niven number\n");
for (uint64_t niven = 1; gap_index <= 32; ++niven) {
sum = digit_sum(niven, sum);
if (divisible(niven, sum)) {
if (niven > previous + gap) {
gap = niven - previous;
printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
gap, niven_index, previous);
}
previous = niven;
++niven_index;
}
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"runtime"
)
type point struct {
x, y float64
}
func add(x, y int) int {
result := x + y
debug("x", x)
debug("y", y)
debug("result", result)
debug("result+1", result+1)
return result
}
func debug(s string, x interface{}) {
_, _, lineNo, _ := runtime.Caller(1)
fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x)
}
func main() {
add(2, 7)
b := true
debug("b", b)
s := "Hello"
debug("s", s)
p := point{2, 3}
debug("p", p)
q := &p
debug("q", q)
}
| #include <stdio.h>
#define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x)
int add(int x, int y) {
int result = x + y;
DEBUG_INT(x);
DEBUG_INT(y);
DEBUG_INT(result);
DEBUG_INT(result+1);
return result;
}
int main() {
add(2, 7);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n /= 10
}
return rev
}
func main() {
c := sieve(999)
reversedPrimes := []int{2}
for i := 3; i < 500; i += 2 {
if !c[i] && !c[reversed(i)] {
reversedPrimes = append(reversedPrimes, i)
}
}
fmt.Println("Primes under 500 which are also primes when the digits are reversed:")
for i, p := range reversedPrimes {
fmt.Printf("%5d", p)
if (i+1) % 10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such primes found.\n", len(reversedPrimes))
}
| #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func reversed(n int) int {
rev := 0
for n > 0 {
rev = rev*10 + n%10
n /= 10
}
return rev
}
func main() {
c := sieve(999)
reversedPrimes := []int{2}
for i := 3; i < 500; i += 2 {
if !c[i] && !c[reversed(i)] {
reversedPrimes = append(reversedPrimes, i)
}
}
fmt.Println("Primes under 500 which are also primes when the digits are reversed:")
for i, p := range reversedPrimes {
fmt.Printf("%5d", p)
if (i+1) % 10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such primes found.\n", len(reversedPrimes))
}
| #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"github.com/fogleman/gg"
"math"
)
func superEllipse(dc *gg.Context, n float64, a int) {
hw := float64(dc.Width() / 2)
hh := float64(dc.Height() / 2)
y := make([]float64, a+1)
for x := 0; x <= a; x++ {
aa := math.Pow(float64(a), n)
xx := math.Pow(float64(x), n)
y[x] = math.Pow(aa-xx, 1.0/n)
}
for x := a; x >= 0; x-- {
dc.LineTo(hw+float64(x), hh-y[x])
}
for x := 0; x <= a; x++ {
dc.LineTo(hw+float64(x), hh+y[x])
}
for x := a; x >= 0; x-- {
dc.LineTo(hw-float64(x), hh+y[x])
}
for x := 0; x <= a; x++ {
dc.LineTo(hw-float64(x), hh-y[x])
}
dc.SetRGB(1, 1, 1)
dc.Fill()
}
func main() {
dc := gg.NewContext(500, 500)
dc.SetRGB(0, 0, 0)
dc.Clear()
superEllipse(dc, 2.5, 200)
dc.SavePNG("superellipse.png")
}
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
double a,b,n,i,incr = 0.0001;
printf("Enter major and minor axes of the SuperEllipse : ");
scanf("%lf%lf",&a,&b);
printf("Enter n : ");
scanf("%lf",&n);
initwindow(500,500,"Superellipse");
for(i=0;i<2*pi;i+=incr){
putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
}
printf("Done. %lf",i);
getch();
closegraph();
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"math/rand"
)
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
func ident(n int) []int {
p := make([]int, n)
for i := range p {
p[i] = i
}
return p
}
func MRRank(p []int) (r int) {
p = append([]int{}, p...)
inv := inverse(p)
for i := len(p) - 1; i > 0; i-- {
s := p[i]
p[inv[i]] = s
inv[s] = inv[i]
}
for i := 1; i < len(p); i++ {
r = r*(i+1) + p[i]
}
return
}
func inverse(p []int) []int {
r := make([]int, len(p))
for i, x := range p {
r[x] = i
}
return r
}
func fact(n int) (f int) {
for f = n; n > 2; {
n--
f *= n
}
return
}
func main() {
n := 3
fmt.Println("permutations of", n, "items")
f := fact(n)
for i := 0; i < f; i++ {
p := MRPerm(i, n)
fmt.Println(i, p, MRRank(p))
}
n = 12
fmt.Println("permutations of", n, "items")
f = fact(n)
m := map[int]bool{}
for len(m) < 4 {
r := rand.Intn(f)
if m[r] {
continue
}
m[r] = true
fmt.Println(r, MRPerm(r, n))
}
}
| #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf("%3d: ", r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf("[ ");
else printf(", ");
printf("%d", tv[i]);
}
printf(" ] = %d\n", get_rank(4, tv));
}
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"math/rand"
)
func MRPerm(q, n int) []int {
p := ident(n)
var r int
for n > 0 {
q, r = q/n, q%n
n--
p[n], p[r] = p[r], p[n]
}
return p
}
func ident(n int) []int {
p := make([]int, n)
for i := range p {
p[i] = i
}
return p
}
func MRRank(p []int) (r int) {
p = append([]int{}, p...)
inv := inverse(p)
for i := len(p) - 1; i > 0; i-- {
s := p[i]
p[inv[i]] = s
inv[s] = inv[i]
}
for i := 1; i < len(p); i++ {
r = r*(i+1) + p[i]
}
return
}
func inverse(p []int) []int {
r := make([]int, len(p))
for i, x := range p {
r[x] = i
}
return r
}
func fact(n int) (f int) {
for f = n; n > 2; {
n--
f *= n
}
return
}
func main() {
n := 3
fmt.Println("permutations of", n, "items")
f := fact(n)
for i := 0; i < f; i++ {
p := MRPerm(i, n)
fmt.Println(i, p, MRRank(p))
}
n = 12
fmt.Println("permutations of", n, "items")
f = fact(n)
m := map[int]bool{}
for len(m) < 4 {
r := rand.Intn(f)
if m[r] {
continue
}
m[r] = true
fmt.Println(r, MRPerm(r, n))
}
}
| #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf("%3d: ", r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf("[ ");
else printf(", ");
printf("%d", tv[i]);
}
printf(" ] = %d\n", get_rank(4, tv));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.