Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
| #include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1);
}
int main()
{
recurse(0);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import "fmt"
func mod(n, m int) int {
return ((n % m) + m) % m
}
func isPrime(n int) bool {
if n < 2 { return false }
if n % 2 == 0 { return n == 2 }
if n % 3 == 0 { return n == 3 }
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 carmichael(p1 int) {
for h3 := 2; h3 < p1; h3++ {
for d := 1; d < h3 + p1; d++ {
if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {
p2 := 1 + (p1 - 1) * (h3 + p1) / d
if !isPrime(p2) { continue }
p3 := 1 + p1 * p2 / h3
if !isPrime(p3) { continue }
if p2 * p3 % (p1 - 1) != 1 { continue }
c := p1 * p2 * p3
fmt.Printf("%2d %4d %5d %d\n", p1, p2, p3, c)
}
}
}
}
func main() {
fmt.Println("The following are Carmichael munbers for p1 <= 61:\n")
fmt.Println("p1 p2 p3 product")
fmt.Println("== == == =======")
for p1 := 2; p1 <= 61; p1++ {
if isPrime(p1) { carmichael(p1) }
}
}
| #include <stdio.h>
#define mod(n,m) ((((n) % (m)) + (m)) % (m))
int is_prime(unsigned int n)
{
if (n <= 3) {
return n > 1;
}
else if (!(n % 2) || !(n % 3)) {
return 0;
}
else {
unsigned int i;
for (i = 5; i*i <= n; i += 6)
if (!(n % i) || !(n % (i + 2)))
return 0;
return 1;
}
}
void carmichael3(int p1)
{
if (!is_prime(p1)) return;
int h3, d, p2, p3;
for (h3 = 1; h3 < p1; ++h3) {
for (d = 1; d < h3 + p1; ++d) {
if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) {
p2 = 1 + ((p1 - 1) * (h3 + p1)/d);
if (!is_prime(p2)) continue;
p3 = 1 + (p1 * p2 / h3);
if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue;
printf("%d %d %d\n", p1, p2, p3);
}
}
}
}
int main(void)
{
int p1;
for (p1 = 2; p1 < 62; ++p1)
carmichael3(p1);
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
arithmetic := []int{1}
primes := []int{}
limit := int(1e6)
for n := 3; len(arithmetic) < limit; n++ {
divs := rcu.Divisors(n)
if len(divs) == 2 {
primes = append(primes, n)
arithmetic = append(arithmetic, n)
} else {
mean := float64(rcu.SumInts(divs)) / float64(len(divs))
if mean == math.Trunc(mean) {
arithmetic = append(arithmetic, n)
}
}
}
fmt.Println("The first 100 arithmetic numbers are:")
rcu.PrintTable(arithmetic[0:100], 10, 3, false)
for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
last := arithmetic[x-1]
lastc := rcu.Commatize(last)
fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
pcount := sort.SearchInts(primes, last) + 1
if !rcu.IsPrime(last) {
pcount--
}
comp := x - pcount - 1
compc := rcu.Commatize(comp)
fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
}
}
| #include <stdio.h>
void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
unsigned int* psum) {
unsigned int divisor_count = 1;
unsigned int divisor_sum = 1;
unsigned int power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
++divisor_count;
divisor_sum += power;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1, sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
++count;
sum += power;
}
divisor_count *= count;
divisor_sum *= sum;
}
if (n > 1) {
divisor_count *= 2;
divisor_sum *= n + 1;
}
*pcount = divisor_count;
*psum = divisor_sum;
}
int main() {
unsigned int arithmetic_count = 0;
unsigned int composite_count = 0;
for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
unsigned int divisor_count;
unsigned int divisor_sum;
divisor_count_and_sum(n, &divisor_count, &divisor_sum);
if (divisor_sum % divisor_count != 0)
continue;
++arithmetic_count;
if (divisor_count > 2)
++composite_count;
if (arithmetic_count <= 100) {
printf("%3u ", n);
if (arithmetic_count % 10 == 0)
printf("\n");
}
if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
arithmetic_count == 100000 || arithmetic_count == 1000000) {
printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
printf("Number of composite arithmetic numbers <= %u: %u\n", n,
composite_count);
}
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
arithmetic := []int{1}
primes := []int{}
limit := int(1e6)
for n := 3; len(arithmetic) < limit; n++ {
divs := rcu.Divisors(n)
if len(divs) == 2 {
primes = append(primes, n)
arithmetic = append(arithmetic, n)
} else {
mean := float64(rcu.SumInts(divs)) / float64(len(divs))
if mean == math.Trunc(mean) {
arithmetic = append(arithmetic, n)
}
}
}
fmt.Println("The first 100 arithmetic numbers are:")
rcu.PrintTable(arithmetic[0:100], 10, 3, false)
for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
last := arithmetic[x-1]
lastc := rcu.Commatize(last)
fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
pcount := sort.SearchInts(primes, last) + 1
if !rcu.IsPrime(last) {
pcount--
}
comp := x - pcount - 1
compc := rcu.Commatize(comp)
fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
}
}
| #include <stdio.h>
void divisor_count_and_sum(unsigned int n, unsigned int* pcount,
unsigned int* psum) {
unsigned int divisor_count = 1;
unsigned int divisor_sum = 1;
unsigned int power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
++divisor_count;
divisor_sum += power;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1, sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
++count;
sum += power;
}
divisor_count *= count;
divisor_sum *= sum;
}
if (n > 1) {
divisor_count *= 2;
divisor_sum *= n + 1;
}
*pcount = divisor_count;
*psum = divisor_sum;
}
int main() {
unsigned int arithmetic_count = 0;
unsigned int composite_count = 0;
for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) {
unsigned int divisor_count;
unsigned int divisor_sum;
divisor_count_and_sum(n, &divisor_count, &divisor_sum);
if (divisor_sum % divisor_count != 0)
continue;
++arithmetic_count;
if (divisor_count > 2)
++composite_count;
if (arithmetic_count <= 100) {
printf("%3u ", n);
if (arithmetic_count % 10 == 0)
printf("\n");
}
if (arithmetic_count == 1000 || arithmetic_count == 10000 ||
arithmetic_count == 100000 || arithmetic_count == 1000000) {
printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
printf("Number of composite arithmetic numbers <= %u: %u\n", n,
composite_count);
}
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"code.google.com/p/x-go-binding/ui/x11"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"os"
"time"
)
var randcol = genrandcol()
func genrandcol() <-chan color.Color {
c := make(chan color.Color)
go func() {
for {
select {
case c <- image.Black:
case c <- image.White:
}
}
}()
return c
}
func gennoise(screen draw.Image) {
for y := 0; y < 240; y++ {
for x := 0; x < 320; x++ {
screen.Set(x, y, <-randcol)
}
}
}
func fps() chan<- bool {
up := make(chan bool)
go func() {
var frames int64
var lasttime time.Time
var totaltime time.Duration
for {
<-up
frames++
now := time.Now()
totaltime += now.Sub(lasttime)
if totaltime > time.Second {
fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
frames = 0
totaltime = 0
}
lasttime = now
}
}()
return up
}
func main() {
win, err := x11.NewWindow()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer win.Close()
go func() {
upfps := fps()
screen := win.Screen()
for {
gennoise(screen)
win.FlushImage()
upfps <- true
}
}()
for _ = range win.EventChan() {
}
}
| #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL/SDL.h>
unsigned int frames = 0;
unsigned int t_acc = 0;
void print_fps ()
{
static Uint32 last_t = 0;
Uint32 t = SDL_GetTicks();
Uint32 dt = t - last_t;
t_acc += dt;
if (t_acc > 1000)
{
unsigned int el_time = t_acc / 1000;
printf("- fps: %g\n",
(float) frames / (float) el_time);
t_acc = 0;
frames = 0;
}
last_t = t;
}
void blit_noise(SDL_Surface *surf)
{
unsigned int i;
long dim = surf->w * surf->h;
while (1)
{
SDL_LockSurface(surf);
for (i=0; i < dim; ++i) {
((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);
}
SDL_UnlockSurface(surf);
SDL_Flip(surf);
++frames;
print_fps();
}
}
int main(void)
{
SDL_Surface *surf = NULL;
srand((unsigned int)time(NULL));
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);
blit_noise(surf);
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
| #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key(int no_timeout)
{
int c = 0;
struct timeval tv;
fd_set fs;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (get_key(0));
printf("Prompt again [Y/N]? ");
fflush(stdout);
c = get_key(1);
if (c == 'Y' || c == 'y') {
printf("\n");
continue;
}
if (c == 'N' || c == 'n') {
printf("\nDone\n");
break;
}
printf("\nYes or no?\n");
}
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
| #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key(int no_timeout)
{
int c = 0;
struct timeval tv;
fd_set fs;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (get_key(0));
printf("Prompt again [Y/N]? ");
fflush(stdout);
c = get_key(1);
if (c == 'Y' || c == 'y') {
printf("\n");
continue;
}
if (c == 'N' || c == 'n') {
printf("\nDone\n");
break;
}
printf("\nYes or no?\n");
}
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
func isPerfect(n int64) bool {
switch n {
case 6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128:
return true
}
return false
}
func main() {
for n := int64(1); ; n++ {
if isPerfect(n) != computePerfect(n) {
panic("bug")
}
if n%1e3 == 0 {
fmt.Println("tested", n)
}
}
}
| #include "stdio.h"
#include "math.h"
int perfect(int n) {
int max = (int)sqrt((double)n) + 1;
int tot = 1;
int i;
for (i = 2; i < max; i++)
if ( (n % i) == 0 ) {
tot += i;
int q = n / i;
if (q > i)
tot += q;
}
return tot == n;
}
int main() {
int n;
for (n = 2; n < 33550337; n++)
if (perfect(n))
printf("%d\n", n);
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math"
"math/cmplx"
)
type matrix struct {
ele []complex128
cols int
}
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
}
|
#include<stdlib.h>
#include<stdio.h>
#include<complex.h>
typedef struct
{
int rows, cols;
complex **z;
} matrix;
matrix
transpose (matrix a)
{
int i, j;
matrix b;
b.rows = a.cols;
b.cols = a.rows;
b.z = malloc (b.rows * sizeof (complex *));
for (i = 0; i < b.rows; i++)
{
b.z[i] = malloc (b.cols * sizeof (complex));
for (j = 0; j < b.cols; j++)
{
b.z[i][j] = conj (a.z[j][i]);
}
}
return b;
}
int
isHermitian (matrix a)
{
int i, j;
matrix b = transpose (a);
if (b.rows == a.rows && b.cols == a.cols)
{
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if (b.z[i][j] != a.z[i][j])
return 0;
}
}
}
else
return 0;
return 1;
}
matrix
multiply (matrix a, matrix b)
{
matrix c;
int i, j;
if (a.cols == b.rows)
{
c.rows = a.rows;
c.cols = b.cols;
c.z = malloc (c.rows * (sizeof (complex *)));
for (i = 0; i < c.rows; i++)
{
c.z[i] = malloc (c.cols * sizeof (complex));
c.z[i][j] = 0 + 0 * I;
for (j = 0; j < b.cols; j++)
{
c.z[i][j] += a.z[i][j] * b.z[j][i];
}
}
}
return c;
}
int
isNormal (matrix a)
{
int i, j;
matrix a_ah, ah_a;
if (a.rows != a.cols)
return 0;
a_ah = multiply (a, transpose (a));
ah_a = multiply (transpose (a), a);
for (i = 0; i < a.rows; i++)
{
for (j = 0; j < a.cols; j++)
{
if (a_ah.z[i][j] != ah_a.z[i][j])
return 0;
}
}
return 1;
}
int
isUnitary (matrix a)
{
matrix b;
int i, j;
if (isNormal (a) == 1)
{
b = multiply (a, transpose(a));
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))
return 0;
}
}
return 1;
}
return 0;
}
int
main ()
{
complex z = 3 + 4 * I;
matrix a, aT;
int i, j;
printf ("Enter rows and columns :");
scanf ("%d%d", &a.rows, &a.cols);
a.z = malloc (a.rows * sizeof (complex *));
printf ("Randomly Generated Complex Matrix A is : ");
for (i = 0; i < a.rows; i++)
{
printf ("\n");
a.z[i] = malloc (a.cols * sizeof (complex));
for (j = 0; j < a.cols; j++)
{
a.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j]));
}
}
aT = transpose (a);
printf ("\n\nTranspose of Complex Matrix A is : ");
for (i = 0; i < aT.rows; i++)
{
printf ("\n");
aT.z[i] = malloc (aT.cols * sizeof (complex));
for (j = 0; j < aT.cols; j++)
{
aT.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j]));
}
}
printf ("\n\nComplex Matrix A %s hermitian",
isHermitian (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s unitary",
isUnitary (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s normal",
isNormal (a) == 1 ? "is" : "is not");
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"math"
"math/cmplx"
)
type matrix struct {
ele []complex128
cols int
}
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
}
|
#include<stdlib.h>
#include<stdio.h>
#include<complex.h>
typedef struct
{
int rows, cols;
complex **z;
} matrix;
matrix
transpose (matrix a)
{
int i, j;
matrix b;
b.rows = a.cols;
b.cols = a.rows;
b.z = malloc (b.rows * sizeof (complex *));
for (i = 0; i < b.rows; i++)
{
b.z[i] = malloc (b.cols * sizeof (complex));
for (j = 0; j < b.cols; j++)
{
b.z[i][j] = conj (a.z[j][i]);
}
}
return b;
}
int
isHermitian (matrix a)
{
int i, j;
matrix b = transpose (a);
if (b.rows == a.rows && b.cols == a.cols)
{
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if (b.z[i][j] != a.z[i][j])
return 0;
}
}
}
else
return 0;
return 1;
}
matrix
multiply (matrix a, matrix b)
{
matrix c;
int i, j;
if (a.cols == b.rows)
{
c.rows = a.rows;
c.cols = b.cols;
c.z = malloc (c.rows * (sizeof (complex *)));
for (i = 0; i < c.rows; i++)
{
c.z[i] = malloc (c.cols * sizeof (complex));
c.z[i][j] = 0 + 0 * I;
for (j = 0; j < b.cols; j++)
{
c.z[i][j] += a.z[i][j] * b.z[j][i];
}
}
}
return c;
}
int
isNormal (matrix a)
{
int i, j;
matrix a_ah, ah_a;
if (a.rows != a.cols)
return 0;
a_ah = multiply (a, transpose (a));
ah_a = multiply (transpose (a), a);
for (i = 0; i < a.rows; i++)
{
for (j = 0; j < a.cols; j++)
{
if (a_ah.z[i][j] != ah_a.z[i][j])
return 0;
}
}
return 1;
}
int
isUnitary (matrix a)
{
matrix b;
int i, j;
if (isNormal (a) == 1)
{
b = multiply (a, transpose(a));
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))
return 0;
}
}
return 1;
}
return 0;
}
int
main ()
{
complex z = 3 + 4 * I;
matrix a, aT;
int i, j;
printf ("Enter rows and columns :");
scanf ("%d%d", &a.rows, &a.cols);
a.z = malloc (a.rows * sizeof (complex *));
printf ("Randomly Generated Complex Matrix A is : ");
for (i = 0; i < a.rows; i++)
{
printf ("\n");
a.z[i] = malloc (a.cols * sizeof (complex));
for (j = 0; j < a.cols; j++)
{
a.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j]));
}
}
aT = transpose (a);
printf ("\n\nTranspose of Complex Matrix A is : ");
for (i = 0; i < aT.rows; i++)
{
printf ("\n");
aT.z[i] = malloc (aT.cols * sizeof (complex));
for (j = 0; j < aT.cols; j++)
{
aT.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j]));
}
}
printf ("\n\nComplex Matrix A %s hermitian",
isHermitian (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s unitary",
isUnitary (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s normal",
isNormal (a) == 1 ? "is" : "is not");
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
| #include <stdio.h>
#include <gmp.h>
void jacobsthal(mpz_t r, unsigned long n) {
mpz_t s;
mpz_init(s);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(s, 1);
if (n % 2) mpz_neg(s, s);
mpz_sub(r, r, s);
mpz_div_ui(r, r, 3);
}
void jacobsthal_lucas(mpz_t r, unsigned long n) {
mpz_t a;
mpz_init(a);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(a, 1);
if (n % 2) mpz_neg(a, a);
mpz_add(r, r, a);
}
int main() {
int i, count;
mpz_t jac[30], j;
printf("First 30 Jacobsthal numbers:\n");
for (i = 0; i < 30; ++i) {
mpz_init(jac[i]);
jacobsthal(jac[i], i);
gmp_printf("%9Zd ", jac[i]);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 30 Jacobsthal-Lucas numbers:\n");
mpz_init(j);
for (i = 0; i < 30; ++i) {
jacobsthal_lucas(j, i);
gmp_printf("%9Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal oblong numbers:\n");
for (i = 0; i < 20; ++i) {
mpz_mul(j, jac[i], jac[i+1]);
gmp_printf("%11Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal primes:\n");
for (i = 0, count = 0; count < 20; ++i) {
jacobsthal(j, i);
if (mpz_probab_prime_p(j, 15) > 0) {
gmp_printf("%Zd\n", j);
++count;
}
}
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"math/big"
)
func jacobsthal(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
s := big.NewInt(1)
if n%2 != 0 {
s.Neg(s)
}
t.Sub(t, s)
return t.Div(t, big.NewInt(3))
}
func jacobsthalLucas(n uint) *big.Int {
t := big.NewInt(1)
t.Lsh(t, n)
a := big.NewInt(1)
if n%2 != 0 {
a.Neg(a)
}
return t.Add(t, a)
}
func main() {
jac := make([]*big.Int, 30)
fmt.Println("First 30 Jacobsthal numbers:")
for i := uint(0); i < 30; i++ {
jac[i] = jacobsthal(i)
fmt.Printf("%9d ", jac[i])
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
for i := uint(0); i < 30; i++ {
fmt.Printf("%9d ", jacobsthalLucas(i))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
for i := uint(0); i < 20; i++ {
t := big.NewInt(0)
fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 20 Jacobsthal primes:")
for n, count := uint(0), 0; count < 20; n++ {
j := jacobsthal(n)
if j.ProbablyPrime(10) {
fmt.Println(j)
count++
}
}
}
| #include <stdio.h>
#include <gmp.h>
void jacobsthal(mpz_t r, unsigned long n) {
mpz_t s;
mpz_init(s);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(s, 1);
if (n % 2) mpz_neg(s, s);
mpz_sub(r, r, s);
mpz_div_ui(r, r, 3);
}
void jacobsthal_lucas(mpz_t r, unsigned long n) {
mpz_t a;
mpz_init(a);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(a, 1);
if (n % 2) mpz_neg(a, a);
mpz_add(r, r, a);
}
int main() {
int i, count;
mpz_t jac[30], j;
printf("First 30 Jacobsthal numbers:\n");
for (i = 0; i < 30; ++i) {
mpz_init(jac[i]);
jacobsthal(jac[i], i);
gmp_printf("%9Zd ", jac[i]);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 30 Jacobsthal-Lucas numbers:\n");
mpz_init(j);
for (i = 0; i < 30; ++i) {
jacobsthal_lucas(j, i);
gmp_printf("%9Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal oblong numbers:\n");
for (i = 0; i < 20; ++i) {
mpz_mul(j, jac[i], jac[i+1]);
gmp_printf("%11Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal primes:\n");
for (i = 0, count = 0; count < 20; ++i) {
jacobsthal(j, i);
if (mpz_probab_prime_p(j, 15) > 0) {
gmp_printf("%Zd\n", j);
++count;
}
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, aMax)
for pole, space := 0, all; pole < aMax; pole++ {
abacus[pole] = space[:len(a)]
space = space[len(a):]
}
var wg sync.WaitGroup
wg.Add(len(a))
for row, n := range a {
go func(row, n int) {
for pole := 0; pole < n; pole++ {
abacus[pole][row] = bead
}
wg.Done()
}(row, n)
}
wg.Wait()
wg.Add(aMax)
for _, pole := range abacus {
go func(pole []byte) {
top := 0
for row, space := range pole {
if space == bead {
pole[row] = 0
pole[top] = bead
top++
}
}
wg.Done()
}(pole)
}
wg.Wait()
for row := range a {
x := 0
for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
x++
}
a[len(a)-1-row] = x
}
}
| #include <stdio.h>
#include <stdlib.h>
void bead_sort(int *a, int len)
{
int i, j, max, sum;
unsigned char *beads;
# define BEAD(i, j) beads[i * max + j]
for (i = 1, max = a[0]; i < len; i++)
if (a[i] > max) max = a[i];
beads = calloc(1, max * len);
for (i = 0; i < len; i++)
for (j = 0; j < a[i]; j++)
BEAD(i, j) = 1;
for (j = 0; j < max; j++) {
for (sum = i = 0; i < len; i++) {
sum += BEAD(i, j);
BEAD(i, j) = 0;
}
for (i = len - sum; i < len; i++) BEAD(i, j) = 1;
}
for (i = 0; i < len; i++) {
for (j = 0; j < max && BEAD(i, j); j++);
a[i] = j;
}
free(beads);
}
int main()
{
int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};
int len = sizeof(x)/sizeof(x[0]);
bead_sort(x, len);
for (i = 0; i < len; i++)
printf("%d\n", x[i]);
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, aMax)
for pole, space := 0, all; pole < aMax; pole++ {
abacus[pole] = space[:len(a)]
space = space[len(a):]
}
var wg sync.WaitGroup
wg.Add(len(a))
for row, n := range a {
go func(row, n int) {
for pole := 0; pole < n; pole++ {
abacus[pole][row] = bead
}
wg.Done()
}(row, n)
}
wg.Wait()
wg.Add(aMax)
for _, pole := range abacus {
go func(pole []byte) {
top := 0
for row, space := range pole {
if space == bead {
pole[row] = 0
pole[top] = bead
top++
}
}
wg.Done()
}(pole)
}
wg.Wait()
for row := range a {
x := 0
for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
x++
}
a[len(a)-1-row] = x
}
}
| #include <stdio.h>
#include <stdlib.h>
void bead_sort(int *a, int len)
{
int i, j, max, sum;
unsigned char *beads;
# define BEAD(i, j) beads[i * max + j]
for (i = 1, max = a[0]; i < len; i++)
if (a[i] > max) max = a[i];
beads = calloc(1, max * len);
for (i = 0; i < len; i++)
for (j = 0; j < a[i]; j++)
BEAD(i, j) = 1;
for (j = 0; j < max; j++) {
for (sum = i = 0; i < len; i++) {
sum += BEAD(i, j);
BEAD(i, j) = 0;
}
for (i = len - sum; i < len; i++) BEAD(i, j) = 1;
}
for (i = 0; i < len; i++) {
for (j = 0; j < max && BEAD(i, j); j++);
a[i] = j;
}
free(beads);
}
int main()
{
int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};
int len = sizeof(x)/sizeof(x[0]);
bead_sort(x, len);
for (i = 0; i < len; i++)
printf("%d\n", x[i]);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func()
func initDraw() {
draw = map[int]func(){
1: func() { horiz(6, 10, 0) },
2: func() { horiz(6, 10, 4) },
3: func() { diagd(6, 10, 0) },
4: func() { diagu(6, 10, 4) },
5: func() { draw[1](); draw[4]() },
6: func() { verti(0, 4, 10) },
7: func() { draw[1](); draw[6]() },
8: func() { draw[2](); draw[6]() },
9: func() { draw[1](); draw[8]() },
10: func() { horiz(0, 4, 0) },
20: func() { horiz(0, 4, 4) },
30: func() { diagu(0, 4, 4) },
40: func() { diagd(0, 4, 0) },
50: func() { draw[10](); draw[40]() },
60: func() { verti(0, 4, 0) },
70: func() { draw[10](); draw[60]() },
80: func() { draw[20](); draw[60]() },
90: func() { draw[10](); draw[80]() },
100: func() { horiz(6, 10, 14) },
200: func() { horiz(6, 10, 10) },
300: func() { diagu(6, 10, 14) },
400: func() { diagd(6, 10, 10) },
500: func() { draw[100](); draw[400]() },
600: func() { verti(10, 14, 10) },
700: func() { draw[100](); draw[600]() },
800: func() { draw[200](); draw[600]() },
900: func() { draw[100](); draw[800]() },
1000: func() { horiz(0, 4, 14) },
2000: func() { horiz(0, 4, 10) },
3000: func() { diagd(0, 4, 10) },
4000: func() { diagu(0, 4, 14) },
5000: func() { draw[1000](); draw[4000]() },
6000: func() { verti(10, 14, 0) },
7000: func() { draw[1000](); draw[6000]() },
8000: func() { draw[2000](); draw[6000]() },
9000: func() { draw[1000](); draw[8000]() },
}
}
func printNumeral() {
for i := 0; i < 15; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("%s ", n[i][j])
}
fmt.Println()
}
fmt.Println()
}
func main() {
initDraw()
numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}
for _, number := range numbers {
initN()
fmt.Printf("%d:\n", number)
thousands := number / 1000
number %= 1000
hundreds := number / 100
number %= 100
tens := number / 10
ones := number % 10
if thousands > 0 {
draw[thousands*1000]()
}
if hundreds > 0 {
draw[hundreds*100]()
}
if tens > 0 {
draw[tens*10]()
}
if ones > 0 {
draw[ones]()
}
printNumeral()
}
}
| #include <stdio.h>
#define GRID_SIZE 15
char canvas[GRID_SIZE][GRID_SIZE];
void initN() {
int i, j;
for (i = 0; i < GRID_SIZE; i++) {
for (j = 0; j < GRID_SIZE; j++) {
canvas[i][j] = ' ';
}
canvas[i][5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
size_t r;
for (r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
void write(FILE *out) {
int i;
for (i = 0; i < GRID_SIZE; i++) {
fprintf(out, "%-.*s", GRID_SIZE, canvas[i]);
putc('\n', out);
}
}
void test(int n) {
printf("%d:\n", n);
initN();
draw(n);
write(stdout);
printf("\n\n");
}
int main() {
test(0);
test(1);
test(20);
test(300);
test(4000);
test(5555);
test(6789);
test(9999);
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import "fmt"
var n = make([][]string, 15)
func initN() {
for i := 0; i < 15; i++ {
n[i] = make([]string, 11)
for j := 0; j < 11; j++ {
n[i][j] = " "
}
n[i][5] = "x"
}
}
func horiz(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r][c] = "x"
}
}
func verti(r1, r2, c int) {
for r := r1; r <= r2; r++ {
n[r][c] = "x"
}
}
func diagd(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r+c-c1][c] = "x"
}
}
func diagu(c1, c2, r int) {
for c := c1; c <= c2; c++ {
n[r-c+c1][c] = "x"
}
}
var draw map[int]func()
func initDraw() {
draw = map[int]func(){
1: func() { horiz(6, 10, 0) },
2: func() { horiz(6, 10, 4) },
3: func() { diagd(6, 10, 0) },
4: func() { diagu(6, 10, 4) },
5: func() { draw[1](); draw[4]() },
6: func() { verti(0, 4, 10) },
7: func() { draw[1](); draw[6]() },
8: func() { draw[2](); draw[6]() },
9: func() { draw[1](); draw[8]() },
10: func() { horiz(0, 4, 0) },
20: func() { horiz(0, 4, 4) },
30: func() { diagu(0, 4, 4) },
40: func() { diagd(0, 4, 0) },
50: func() { draw[10](); draw[40]() },
60: func() { verti(0, 4, 0) },
70: func() { draw[10](); draw[60]() },
80: func() { draw[20](); draw[60]() },
90: func() { draw[10](); draw[80]() },
100: func() { horiz(6, 10, 14) },
200: func() { horiz(6, 10, 10) },
300: func() { diagu(6, 10, 14) },
400: func() { diagd(6, 10, 10) },
500: func() { draw[100](); draw[400]() },
600: func() { verti(10, 14, 10) },
700: func() { draw[100](); draw[600]() },
800: func() { draw[200](); draw[600]() },
900: func() { draw[100](); draw[800]() },
1000: func() { horiz(0, 4, 14) },
2000: func() { horiz(0, 4, 10) },
3000: func() { diagd(0, 4, 10) },
4000: func() { diagu(0, 4, 14) },
5000: func() { draw[1000](); draw[4000]() },
6000: func() { verti(10, 14, 0) },
7000: func() { draw[1000](); draw[6000]() },
8000: func() { draw[2000](); draw[6000]() },
9000: func() { draw[1000](); draw[8000]() },
}
}
func printNumeral() {
for i := 0; i < 15; i++ {
for j := 0; j < 11; j++ {
fmt.Printf("%s ", n[i][j])
}
fmt.Println()
}
fmt.Println()
}
func main() {
initDraw()
numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999}
for _, number := range numbers {
initN()
fmt.Printf("%d:\n", number)
thousands := number / 1000
number %= 1000
hundreds := number / 100
number %= 100
tens := number / 10
ones := number % 10
if thousands > 0 {
draw[thousands*1000]()
}
if hundreds > 0 {
draw[hundreds*100]()
}
if tens > 0 {
draw[tens*10]()
}
if ones > 0 {
draw[ones]()
}
printNumeral()
}
}
| #include <stdio.h>
#define GRID_SIZE 15
char canvas[GRID_SIZE][GRID_SIZE];
void initN() {
int i, j;
for (i = 0; i < GRID_SIZE; i++) {
for (j = 0; j < GRID_SIZE; j++) {
canvas[i][j] = ' ';
}
canvas[i][5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
size_t r;
for (r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
void write(FILE *out) {
int i;
for (i = 0; i < GRID_SIZE; i++) {
fprintf(out, "%-.*s", GRID_SIZE, canvas[i]);
putc('\n', out);
}
}
void test(int n) {
printf("%d:\n", n);
initN();
draw(n);
write(stdout);
printf("\n\n");
}
int main() {
test(0);
test(1);
test(20);
test(300);
test(4000);
test(5555);
test(6789);
test(9999);
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
}
| #include <gmp.h>
#include <stdio.h>
#include <string.h>
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18);
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
char *s = mpz_get_str(0, 10, a);
printf("size really is %d\n", len = strlen(s));
printf("Digits: %.20s...%s\n", s, s + len - 20);
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
void draw_sphere(double R, double k, double ambient)
{
int i, j, intensity;
double b;
double vec[3], x, y;
for (i = floor(-R); i <= ceil(R); i++) {
x = i + .5;
for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
y = j / 2. + .5;
if (x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = sqrt(R * R - x * x - y * y);
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
} else
putchar(' ');
}
putchar('\n');
}
}
int main()
{
normalize(light);
draw_sphere(20, 4, .1);
draw_sphere(10, 2, .4);
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
void draw_sphere(double R, double k, double ambient)
{
int i, j, intensity;
double b;
double vec[3], x, y;
for (i = floor(-R); i <= ceil(R); i++) {
x = i + .5;
for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
y = j / 2. + .5;
if (x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = sqrt(R * R - x * x - y * y);
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
} else
putchar(' ');
}
putchar('\n');
}
}
int main()
{
normalize(light);
draw_sphere(20, 4, .1);
draw_sphere(10, 2, .4);
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
)
var index map[string][]int
var indexed []doc
type doc struct {
file string
title string
}
func main() {
index = make(map[string][]int)
if err := indexDir("docs"); err != nil {
fmt.Println(err)
return
}
ui()
}
func indexDir(dir string) error {
df, err := os.Open(dir)
if err != nil {
return err
}
fis, err := df.Readdir(-1)
if err != nil {
return err
}
if len(fis) == 0 {
return errors.New(fmt.Sprintf("no files in %s", dir))
}
indexed := 0
for _, fi := range fis {
if !fi.IsDir() {
if indexFile(dir + "/" + fi.Name()) {
indexed++
}
}
}
return nil
}
func indexFile(fn string) bool {
f, err := os.Open(fn)
if err != nil {
fmt.Println(err)
return false
}
x := len(indexed)
indexed = append(indexed, doc{fn, fn})
pdoc := &indexed[x]
r := bufio.NewReader(f)
lines := 0
for {
b, isPrefix, err := r.ReadLine()
switch {
case err == io.EOF:
return true
case err != nil:
fmt.Println(err)
return true
case isPrefix:
fmt.Printf("%s: unexpected long line\n", fn)
return true
case lines < 20 && bytes.HasPrefix(b, []byte("Title:")):
pdoc.title = string(b[7:])
}
wordLoop:
for _, bword := range bytes.Fields(b) {
bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@")
if len(bword) > 0 {
word := string(bword)
dl := index[word]
for _, d := range dl {
if d == x {
continue wordLoop
}
}
index[word] = append(dl, x)
}
}
}
return true
}
func ui() {
fmt.Println(len(index), "words indexed in", len(indexed), "files")
fmt.Println("enter single words to search for")
fmt.Println("enter a blank line when done")
var word string
for {
fmt.Print("search word: ")
wc, _ := fmt.Scanln(&word)
if wc == 0 {
return
}
switch dl := index[word]; len(dl) {
case 0:
fmt.Println("no match")
case 1:
fmt.Println("one match:")
fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title)
default:
fmt.Println(len(dl), "matches:")
for _, d := range dl {
fmt.Println(" ", indexed[d].file, indexed[d].title)
}
}
}
}
| #include <stdio.h>
#include <stdlib.h>
char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./";
int chr_idx[256] = {0};
char idx_chr[256] = {0};
#define FNAME 0
typedef struct trie_t *trie, trie_t;
struct trie_t {
trie next[sizeof(chr_legal)];
int eow;
};
trie trie_new() { return calloc(sizeof(trie_t), 1); }
#define find_word(r, w) trie_trav(r, w, 1)
trie trie_trav(trie root, const char * str, int no_create)
{
int c;
while (root) {
if ((c = str[0]) == '\0') {
if (!root->eow && no_create) return 0;
break;
}
if (! (c = chr_idx[c]) ) {
str++;
continue;
}
if (!root->next[c]) {
if (no_create) return 0;
root->next[c] = trie_new();
}
root = root->next[c];
str++;
}
return root;
}
int trie_all(trie root, char path[], int depth, int (*callback)(char *))
{
int i;
if (root->eow && !callback(path)) return 0;
for (i = 1; i < sizeof(chr_legal); i++) {
if (!root->next[i]) continue;
path[depth] = idx_chr[i];
path[depth + 1] = '\0';
if (!trie_all(root->next[i], path, depth + 1, callback))
return 0;
}
return 1;
}
void add_index(trie root, const char *word, const char *fname)
{
trie x = trie_trav(root, word, 0);
x->eow = 1;
if (!x->next[FNAME])
x->next[FNAME] = trie_new();
x = trie_trav(x->next[FNAME], fname, 0);
x->eow = 1;
}
int print_path(char *path)
{
printf(" %s", path);
return 1;
}
const char *files[] = { "f1.txt", "source/f2.txt", "other_file" };
const char *text[][5] ={{ "it", "is", "what", "it", "is" },
{ "what", "is", "it", 0 },
{ "it", "is", "a", "banana", 0 }};
trie init_tables()
{
int i, j;
trie root = trie_new();
for (i = 0; i < sizeof(chr_legal); i++) {
chr_idx[(int)chr_legal[i]] = i + 1;
idx_chr[i + 1] = chr_legal[i];
}
#define USE_ADVANCED_FILE_HANDLING 0
#if USE_ADVANCED_FILE_HANDLING
void read_file(const char * fname) {
char cmd[1024];
char word[1024];
sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname);
FILE *in = popen(cmd, "r");
while (!feof(in)) {
fscanf(in, "%1000s", word);
add_index(root, word, fname);
}
pclose(in);
};
read_file("f1.txt");
read_file("source/f2.txt");
read_file("other_file");
#else
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
if (!text[i][j]) break;
add_index(root, text[i][j], files[i]);
}
}
#endif
return root;
}
void search_index(trie root, const char *word)
{
char path[1024];
printf("Search for \"%s\": ", word);
trie found = find_word(root, word);
if (!found) printf("not found\n");
else {
trie_all(found->next[FNAME], path, 0, print_path);
printf("\n");
}
}
int main()
{
trie root = init_tables();
search_index(root, "what");
search_index(root, "is");
search_index(root, "banana");
search_index(root, "boo");
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
)
var index map[string][]int
var indexed []doc
type doc struct {
file string
title string
}
func main() {
index = make(map[string][]int)
if err := indexDir("docs"); err != nil {
fmt.Println(err)
return
}
ui()
}
func indexDir(dir string) error {
df, err := os.Open(dir)
if err != nil {
return err
}
fis, err := df.Readdir(-1)
if err != nil {
return err
}
if len(fis) == 0 {
return errors.New(fmt.Sprintf("no files in %s", dir))
}
indexed := 0
for _, fi := range fis {
if !fi.IsDir() {
if indexFile(dir + "/" + fi.Name()) {
indexed++
}
}
}
return nil
}
func indexFile(fn string) bool {
f, err := os.Open(fn)
if err != nil {
fmt.Println(err)
return false
}
x := len(indexed)
indexed = append(indexed, doc{fn, fn})
pdoc := &indexed[x]
r := bufio.NewReader(f)
lines := 0
for {
b, isPrefix, err := r.ReadLine()
switch {
case err == io.EOF:
return true
case err != nil:
fmt.Println(err)
return true
case isPrefix:
fmt.Printf("%s: unexpected long line\n", fn)
return true
case lines < 20 && bytes.HasPrefix(b, []byte("Title:")):
pdoc.title = string(b[7:])
}
wordLoop:
for _, bword := range bytes.Fields(b) {
bword := bytes.Trim(bword, ".,-~?!\"'`;:()<>[]{}\\|/=_+*&^%$#@")
if len(bword) > 0 {
word := string(bword)
dl := index[word]
for _, d := range dl {
if d == x {
continue wordLoop
}
}
index[word] = append(dl, x)
}
}
}
return true
}
func ui() {
fmt.Println(len(index), "words indexed in", len(indexed), "files")
fmt.Println("enter single words to search for")
fmt.Println("enter a blank line when done")
var word string
for {
fmt.Print("search word: ")
wc, _ := fmt.Scanln(&word)
if wc == 0 {
return
}
switch dl := index[word]; len(dl) {
case 0:
fmt.Println("no match")
case 1:
fmt.Println("one match:")
fmt.Println(" ", indexed[dl[0]].file, indexed[dl[0]].title)
default:
fmt.Println(len(dl), "matches:")
for _, d := range dl {
fmt.Println(" ", indexed[d].file, indexed[d].title)
}
}
}
}
| #include <stdio.h>
#include <stdlib.h>
char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./";
int chr_idx[256] = {0};
char idx_chr[256] = {0};
#define FNAME 0
typedef struct trie_t *trie, trie_t;
struct trie_t {
trie next[sizeof(chr_legal)];
int eow;
};
trie trie_new() { return calloc(sizeof(trie_t), 1); }
#define find_word(r, w) trie_trav(r, w, 1)
trie trie_trav(trie root, const char * str, int no_create)
{
int c;
while (root) {
if ((c = str[0]) == '\0') {
if (!root->eow && no_create) return 0;
break;
}
if (! (c = chr_idx[c]) ) {
str++;
continue;
}
if (!root->next[c]) {
if (no_create) return 0;
root->next[c] = trie_new();
}
root = root->next[c];
str++;
}
return root;
}
int trie_all(trie root, char path[], int depth, int (*callback)(char *))
{
int i;
if (root->eow && !callback(path)) return 0;
for (i = 1; i < sizeof(chr_legal); i++) {
if (!root->next[i]) continue;
path[depth] = idx_chr[i];
path[depth + 1] = '\0';
if (!trie_all(root->next[i], path, depth + 1, callback))
return 0;
}
return 1;
}
void add_index(trie root, const char *word, const char *fname)
{
trie x = trie_trav(root, word, 0);
x->eow = 1;
if (!x->next[FNAME])
x->next[FNAME] = trie_new();
x = trie_trav(x->next[FNAME], fname, 0);
x->eow = 1;
}
int print_path(char *path)
{
printf(" %s", path);
return 1;
}
const char *files[] = { "f1.txt", "source/f2.txt", "other_file" };
const char *text[][5] ={{ "it", "is", "what", "it", "is" },
{ "what", "is", "it", 0 },
{ "it", "is", "a", "banana", 0 }};
trie init_tables()
{
int i, j;
trie root = trie_new();
for (i = 0; i < sizeof(chr_legal); i++) {
chr_idx[(int)chr_legal[i]] = i + 1;
idx_chr[i + 1] = chr_legal[i];
}
#define USE_ADVANCED_FILE_HANDLING 0
#if USE_ADVANCED_FILE_HANDLING
void read_file(const char * fname) {
char cmd[1024];
char word[1024];
sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname);
FILE *in = popen(cmd, "r");
while (!feof(in)) {
fscanf(in, "%1000s", word);
add_index(root, word, fname);
}
pclose(in);
};
read_file("f1.txt");
read_file("source/f2.txt");
read_file("other_file");
#else
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
if (!text[i][j]) break;
add_index(root, text[i][j], files[i]);
}
}
#endif
return root;
}
void search_index(trie root, const char *word)
{
char path[1024];
printf("Search for \"%s\": ", word);
trie found = find_word(root, word);
if (!found) printf("not found\n");
else {
trie_all(found->next[FNAME], path, 0, print_path);
printf("\n");
}
}
int main()
{
trie root = init_tables();
search_index(root, "what");
search_index(root, "is");
search_index(root, "banana");
search_index(root, "boo");
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
import "math/rand"
import "time"
func main() {
rand.Seed(time.Now().UnixNano())
for {
a := rand.Intn(20)
fmt.Println(a)
if a == 10 {
break
}
b := rand.Intn(20)
fmt.Println(b)
}
}
| int main(){
time_t t;
int a, b;
srand((unsigned)time(&t));
for(;;){
a = rand() % 20;
printf("%d\n", a);
if(a == 10)
break;
b = rand() % 20;
printf("%d\n", b);
}
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
}
| #include <stdio.h>
int main()
{
FILE *lp;
lp = fopen("/dev/lp0","w");
fprintf(lp,"Hello world!\n");
fclose(lp);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"os"
)
func main() {
lp0, err := os.Create("/dev/lp0")
if err != nil {
panic(err)
}
defer lp0.Close()
fmt.Fprintln(lp0, "Hello World!")
}
| #include <stdio.h>
int main()
{
FILE *lp;
lp = fopen("/dev/lp0","w");
fprintf(lp,"Hello world!\n");
fclose(lp);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import "fmt"
func maxl(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := 0; i < len(hm);i++{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func maxr(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := len(hm) - 1 ; i >= 0;i--{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func min(a,b []int) []int {
res := make([]int,len(a))
for i := 0; i < len(a);i++{
if a[i] >= b[i]{
res[i] = b[i]
}else {
res[i] = a[i]
}
}
return res
}
func diff(hm, min []int) []int {
res := make([]int,len(hm))
for i := 0; i < len(hm);i++{
if min[i] > hm[i]{
res[i] = min[i] - hm[i]
}
}
return res
}
func sum(a []int) int {
res := 0
for i := 0; i < len(a);i++{
res += a[i]
}
return res
}
func waterCollected(hm []int) int {
maxr := maxr(hm)
maxl := maxl(hm)
min := min(maxr,maxl)
diff := diff(hm,min)
sum := sum(diff)
return sum
}
func main() {
fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
fmt.Println(waterCollected([]int{5, 5, 5, 5}))
fmt.Println(waterCollected([]int{5, 6, 7, 8}))
fmt.Println(waterCollected([]int{8, 7, 7, 6}))
fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
| #include<stdlib.h>
#include<stdio.h>
int getWater(int* arr,int start,int end,int cutoff){
int i, sum = 0;
for(i=start;i<=end;i++)
sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);
return sum;
}
int netWater(int* arr,int size){
int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;
if(size<3)
return 0;
for(i=0;i<size-1;i++){
start:if(i!=size-2 && arr[i]>arr[i+1]){
ref1 = i;
for(j=ref1+1;j<size;j++){
if(arr[j]>=arr[ref1]){
ref2 = j;
sum += getWater(arr,ref1+1,ref2-1,ref1);
i = ref2;
goto start;
}
else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){
marker = j+1;
markerSet = 1;
}
}
if(markerSet==1){
sum += getWater(arr,ref1+1,marker-1,marker);
i = marker;
markerSet = 0;
goto start;
}
}
}
return sum;
}
int main(int argC,char* argV[])
{
int *arr,i;
if(argC==1)
printf("Usage : %s <followed by space separated series of integers>");
else{
arr = (int*)malloc((argC-1)*sizeof(int));
for(i=1;i<argC;i++)
arr[i-1] = atoi(argV[i]);
printf("Water collected : %d",netWater(arr,argC-1));
}
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"rcu"
"sort"
"strconv"
)
func combinations(a []int, k int) [][]int {
n := len(a)
c := make([]int, k)
var combs [][]int
var combine func(start, end, index int)
combine = func(start, end, index int) {
if index == k {
t := make([]int, len(c))
copy(t, c)
combs = append(combs, t)
return
}
for i := start; i <= end && end-i+1 >= k-index; i++ {
c[index] = a[i]
combine(i+1, end, index+1)
}
}
combine(0, n-1, 0)
return combs
}
func powerset(a []int) (res [][]int) {
if len(a) == 0 {
return
}
for i := 1; i <= len(a); i++ {
res = append(res, combinations(a, i)...)
}
return
}
func main() {
ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
var descPrimes []int
for i := 1; i < len(ps); i++ {
s := ""
for _, e := range ps[i] {
s += string(e + '0')
}
p, _ := strconv.Atoi(s)
if rcu.IsPrime(p) {
descPrimes = append(descPrimes, p)
}
}
sort.Ints(descPrimes)
fmt.Println("There are", len(descPrimes), "descending primes, namely:")
for i := 0; i < len(descPrimes); i++ {
fmt.Printf("%8d ", descPrimes[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println()
}
| #include <stdio.h>
int ispr(unsigned int n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (unsigned int j = 3; j * j <= n; j += 2)
if (n % j == 0) return 0; return 1; }
int main() {
unsigned int c = 0, nc, pc = 9, i, a, b, l,
ps[128], nxt[128];
for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;
while (1) {
nc = 0;
for (i = 0; i < pc; i++) {
if (ispr(a = ps[i]))
printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
for (b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
else break;
}
printf("\n%d descending primes found", c);
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1)
p := uint64(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
}
}
}
for i := uint64(3); i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
func squareFree(from, to uint64) (results []uint64) {
limit := uint64(math.Sqrt(float64(to)))
primes := sieve(limit)
outer:
for i := from; i <= to; i++ {
for _, p := range primes {
p2 := p * p
if p2 > i {
break
}
if i%p2 == 0 {
continue outer
}
}
results = append(results, i)
}
return
}
const trillion uint64 = 1000000000000
func main() {
fmt.Println("Square-free integers from 1 to 145:")
sf := squareFree(1, 145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%20 == 0 {
fmt.Println()
}
fmt.Printf("%4d", sf[i])
}
fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
sf = squareFree(trillion, trillion+145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%5 == 0 {
fmt.Println()
}
fmt.Printf("%14d", sf[i])
}
fmt.Println("\n\nNumber of square-free integers:\n")
a := [...]uint64{100, 1000, 10000, 100000, 1000000}
for _, n := range a {
fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000
typedef unsigned char bool;
typedef unsigned long long uint64;
void sieve(uint64 limit, uint64 *primes, uint64 *length) {
uint64 i, count, p, p2;
bool *c = calloc(limit + 1, sizeof(bool));
primes[0] = 2;
count = 1;
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;
}
}
for (i = 3; i <= limit; i += 2) {
if (!c[i]) primes[count++] = i;
}
*length = count;
free(c);
}
void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {
uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);
uint64 *primes = malloc((limit + 1) * sizeof(uint64));
bool add;
sieve(limit, primes, &np);
for (i = from; i <= to; ++i) {
add = TRUE;
for (j = 0; j < np; ++j) {
p = primes[j];
p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) {
add = FALSE;
break;
}
}
if (add) results[count++] = i;
}
*len = count;
free(primes);
}
int main() {
uint64 i, *sf, len;
sf = malloc(1000000 * sizeof(uint64));
printf("Square-free integers from 1 to 145:\n");
squareFree(1, 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 20 == 0) {
printf("\n");
}
printf("%4lld", sf[i]);
}
printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145);
squareFree(TRILLION, TRILLION + 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 5 == 0) {
printf("\n");
}
printf("%14lld", sf[i]);
}
printf("\n\nNumber of square-free integers:\n");
int a[5] = {100, 1000, 10000, 100000, 1000000};
for (i = 0; i < 5; ++i) {
squareFree(1, a[i], sf, &len);
printf(" from %d to %d = %lld\n", 1, a[i], len);
}
free(sf);
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1)
p := uint64(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
}
}
}
for i := uint64(3); i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
func squareFree(from, to uint64) (results []uint64) {
limit := uint64(math.Sqrt(float64(to)))
primes := sieve(limit)
outer:
for i := from; i <= to; i++ {
for _, p := range primes {
p2 := p * p
if p2 > i {
break
}
if i%p2 == 0 {
continue outer
}
}
results = append(results, i)
}
return
}
const trillion uint64 = 1000000000000
func main() {
fmt.Println("Square-free integers from 1 to 145:")
sf := squareFree(1, 145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%20 == 0 {
fmt.Println()
}
fmt.Printf("%4d", sf[i])
}
fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
sf = squareFree(trillion, trillion+145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%5 == 0 {
fmt.Println()
}
fmt.Printf("%14d", sf[i])
}
fmt.Println("\n\nNumber of square-free integers:\n")
a := [...]uint64{100, 1000, 10000, 100000, 1000000}
for _, n := range a {
fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000
typedef unsigned char bool;
typedef unsigned long long uint64;
void sieve(uint64 limit, uint64 *primes, uint64 *length) {
uint64 i, count, p, p2;
bool *c = calloc(limit + 1, sizeof(bool));
primes[0] = 2;
count = 1;
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;
}
}
for (i = 3; i <= limit; i += 2) {
if (!c[i]) primes[count++] = i;
}
*length = count;
free(c);
}
void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {
uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);
uint64 *primes = malloc((limit + 1) * sizeof(uint64));
bool add;
sieve(limit, primes, &np);
for (i = from; i <= to; ++i) {
add = TRUE;
for (j = 0; j < np; ++j) {
p = primes[j];
p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) {
add = FALSE;
break;
}
}
if (add) results[count++] = i;
}
*len = count;
free(primes);
}
int main() {
uint64 i, *sf, len;
sf = malloc(1000000 * sizeof(uint64));
printf("Square-free integers from 1 to 145:\n");
squareFree(1, 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 20 == 0) {
printf("\n");
}
printf("%4lld", sf[i]);
}
printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145);
squareFree(TRILLION, TRILLION + 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 5 == 0) {
printf("\n");
}
printf("%14lld", sf[i]);
}
printf("\n\nNumber of square-free integers:\n");
int a[5] = {100, 1000, 10000, 100000, 1000000};
for (i = 0; i < 5; ++i) {
squareFree(1, a[i], sf, &len);
printf(" from %d to %d = %lld\n", 1, a[i], len);
}
free(sf);
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import "fmt"
func jaro(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_distance = match_distance/2 - 1
str1_matches := make([]bool, len(str1))
str2_matches := make([]bool, len(str2))
matches := 0.
transpositions := 0.
for i := range str1 {
start := i - match_distance
if start < 0 {
start = 0
}
end := i + match_distance + 1
if end > len(str2) {
end = len(str2)
}
for k := start; k < end; k++ {
if str2_matches[k] {
continue
}
if str1[i] != str2[k] {
continue
}
str1_matches[i] = true
str2_matches[k] = true
matches++
break
}
}
if matches == 0 {
return 0
}
k := 0
for i := range str1 {
if !str1_matches[i] {
continue
}
for !str2_matches[k] {
k++
}
if str1[i] != str2[k] {
transpositions++
}
k++
}
transpositions /= 2
return (matches/float64(len(str1)) +
matches/float64(len(str2)) +
(matches-transpositions)/matches) / 3
}
func main() {
fmt.Printf("%f\n", jaro("MARTHA", "MARHTA"))
fmt.Printf("%f\n", jaro("DIXON", "DICKSONX"))
fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"))
}
| #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
double jaro(const char *str1, const char *str2) {
int str1_len = strlen(str1);
int str2_len = strlen(str2);
if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;
int match_distance = (int) max(str1_len, str2_len)/2 - 1;
int *str1_matches = calloc(str1_len, sizeof(int));
int *str2_matches = calloc(str2_len, sizeof(int));
double matches = 0.0;
double transpositions = 0.0;
for (int i = 0; i < str1_len; i++) {
int start = max(0, i - match_distance);
int end = min(i + match_distance + 1, str2_len);
for (int k = start; k < end; k++) {
if (str2_matches[k]) continue;
if (str1[i] != str2[k]) continue;
str1_matches[i] = TRUE;
str2_matches[k] = TRUE;
matches++;
break;
}
}
if (matches == 0) {
free(str1_matches);
free(str2_matches);
return 0.0;
}
int k = 0;
for (int i = 0; i < str1_len; i++) {
if (!str1_matches[i]) continue;
while (!str2_matches[k]) k++;
if (str1[i] != str2[k]) transpositions++;
k++;
}
transpositions /= 2.0;
free(str1_matches);
free(str2_matches);
return ((matches / str1_len) +
(matches / str2_len) +
((matches - transpositions) / matches)) / 3.0;
}
int main() {
printf("%f\n", jaro("MARTHA", "MARHTA"));
printf("%f\n", jaro("DIXON", "DICKSONX"));
printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"));
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
type pair struct{ x, y int }
func main() {
const max = 1685
var all []pair
for a := 2; a < max; a++ {
for b := a + 1; b < max-a; b++ {
all = append(all, pair{a, b})
}
}
fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
products := countProducts(all)
var sPairs []pair
pairs:
for _, p := range all {
s := p.x + p.y
for a := 2; a < s/2+s&1; a++ {
b := s - a
if products[a*b] == 1 {
continue pairs
}
}
sPairs = append(sPairs, p)
}
fmt.Println("S starts with", len(sPairs), "possible pairs.")
sProducts := countProducts(sPairs)
var pPairs []pair
for _, p := range sPairs {
if sProducts[p.x*p.y] == 1 {
pPairs = append(pPairs, p)
}
}
fmt.Println("P then has", len(pPairs), "possible pairs.")
pSums := countSums(pPairs)
var final []pair
for _, p := range pPairs {
if pSums[p.x+p.y] == 1 {
final = append(final, p)
}
}
switch len(final) {
case 1:
fmt.Println("Answer:", final[0].x, "and", final[0].y)
case 0:
fmt.Println("No possible answer.")
default:
fmt.Println(len(final), "possible answers:", final)
}
}
func countProducts(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x*p.y]++
}
return m
}
func countSums(list []pair) map[int]int {
m := make(map[int]int)
for _, p := range list {
m[p.x+p.y]++
}
return m
}
func decomposeSum(s int) []pair {
pairs := make([]pair, 0, s/2)
for a := 2; a < s/2+s&1; a++ {
pairs = append(pairs, pair{a, s - a})
}
return pairs
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t {
int x, y;
struct node_t *prev, *next;
} node;
node *new_node(int x, int y) {
node *n = malloc(sizeof(node));
n->x = x;
n->y = y;
n->next = NULL;
n->prev = NULL;
return n;
}
void free_node(node **n) {
if (n == NULL) {
return;
}
(*n)->prev = NULL;
(*n)->next = NULL;
free(*n);
*n = NULL;
}
typedef struct list_t {
node *head;
node *tail;
} list;
list make_list() {
list lst = { NULL, NULL };
return lst;
}
void append_node(list *const lst, int x, int y) {
if (lst == NULL) {
return;
}
node *n = new_node(x, y);
if (lst->head == NULL) {
lst->head = n;
lst->tail = n;
} else {
n->prev = lst->tail;
lst->tail->next = n;
lst->tail = n;
}
}
void remove_node(list *const lst, const node *const n) {
if (lst == NULL || n == NULL) {
return;
}
if (n->prev != NULL) {
n->prev->next = n->next;
if (n->next != NULL) {
n->next->prev = n->prev;
} else {
lst->tail = n->prev;
}
} else {
if (n->next != NULL) {
n->next->prev = NULL;
lst->head = n->next;
}
}
free_node(&n);
}
void free_list(list *const lst) {
node *ptr;
if (lst == NULL) {
return;
}
ptr = lst->head;
while (ptr != NULL) {
node *nxt = ptr->next;
free_node(&ptr);
ptr = nxt;
}
lst->head = NULL;
lst->tail = NULL;
}
void print_list(const list *lst) {
node *it;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
int prod = it->x * it->y;
printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod);
}
}
void print_count(const list *const lst) {
node *it;
int c = 0;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
c++;
}
if (c == 0) {
printf("no candidates\n");
} else if (c == 1) {
printf("one candidate\n");
} else {
printf("%d candidates\n", c);
}
}
void setup(list *const lst) {
int x, y;
if (lst == NULL) {
return;
}
for (x = 2; x <= 98; x++) {
for (y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
append_node(lst, x, y);
}
}
}
}
void remove_by_sum(list *const lst, const int sum) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int s = it->x + it->y;
if (s == sum) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void remove_by_prod(list *const lst, const int prod) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int p = it->x * it->y;
if (p == prod) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void statement1(list *const lst) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = lst->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = lst->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] == 1) {
remove_by_sum(lst, it->x + it->y);
it = lst->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement2(list *const candidates) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = candidates->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] > 1) {
remove_by_prod(candidates, prod);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement3(list *const candidates) {
short *unique = calloc(100, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
unique[sum]++;
}
it = candidates->head;
while (it != NULL) {
int sum = it->x + it->y;
nxt = it->next;
if (unique[sum] > 1) {
remove_by_sum(candidates, sum);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
int main() {
list candidates = make_list();
setup(&candidates);
print_count(&candidates);
statement1(&candidates);
print_count(&candidates);
statement2(&candidates);
print_count(&candidates);
statement3(&candidates);
print_count(&candidates);
print_list(&candidates);
free_list(&candidates);
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func fairshare(n, base int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
j := i
sum := 0
for j > 0 {
sum += j % base
j /= base
}
res[i] = sum % base
}
return res
}
func turns(n int, fss []int) string {
m := make(map[int]int)
for _, fs := range fss {
m[fs]++
}
m2 := make(map[int]int)
for _, v := range m {
m2[v]++
}
res := []int{}
sum := 0
for k, v := range m2 {
sum += v
res = append(res, k)
}
if sum != n {
return fmt.Sprintf("only %d have a turn", sum)
}
sort.Ints(res)
res2 := make([]string, len(res))
for i := range res {
res2[i] = strconv.Itoa(res[i])
}
return strings.Join(res2, " or ")
}
func main() {
for _, base := range []int{2, 3, 5, 11} {
fmt.Printf("%2d : %2d\n", base, fairshare(25, base))
}
fmt.Println("\nHow many times does each get a turn in 50000 iterations?")
for _, base := range []int{191, 1377, 49999, 50000, 50001} {
t := turns(base, fairshare(50000, base))
fmt.Printf(" With %d people: %s\n", base, t)
}
}
| #include <stdio.h>
#include <stdlib.h>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
int i;
printf("Base %2d:", base);
for (i = 0; i < count; i++) {
int t = turn(base, i);
printf(" %2d", t);
}
printf("\n");
}
void turnCount(int base, int count) {
int *cnt = calloc(base, sizeof(int));
int i, minTurn, maxTurn, portion;
if (NULL == cnt) {
printf("Failed to allocate space to determine the spread of turns.\n");
return;
}
for (i = 0; i < count; i++) {
int t = turn(base, i);
cnt[t]++;
}
minTurn = INT_MAX;
maxTurn = INT_MIN;
portion = 0;
for (i = 0; i < base; i++) {
if (cnt[i] > 0) {
portion++;
}
if (cnt[i] < minTurn) {
minTurn = cnt[i];
}
if (cnt[i] > maxTurn) {
maxTurn = cnt[i];
}
}
printf(" With %d people: ", base);
if (0 == minTurn) {
printf("Only %d have a turn\n", portion);
} else if (minTurn == maxTurn) {
printf("%d\n", minTurn);
} else {
printf("%d or %d\n", minTurn, maxTurn);
}
free(cnt);
}
int main() {
fairshare(2, 25);
fairshare(3, 25);
fairshare(5, 25);
fairshare(11, 25);
printf("How many times does each get a turn in 50000 iterations?\n");
turnCount(191, 50000);
turnCount(1377, 50000);
turnCount(49999, 50000);
turnCount(50000, 50000);
turnCount(50001, 50000);
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
var cylinder = [6]bool{}
func rshift() {
t := cylinder[5]
for i := 4; i >= 0; i-- {
cylinder[i+1] = cylinder[i]
}
cylinder[0] = t
}
func unload() {
for i := 0; i < 6; i++ {
cylinder[i] = false
}
}
func load() {
for cylinder[0] {
rshift()
}
cylinder[0] = true
rshift()
}
func spin() {
var lim = 1 + rand.Intn(6)
for i := 1; i < lim; i++ {
rshift()
}
}
func fire() bool {
shot := cylinder[0]
rshift()
return shot
}
func method(s string) int {
unload()
for _, c := range s {
switch c {
case 'L':
load()
case 'S':
spin()
case 'F':
if fire() {
return 1
}
}
}
return 0
}
func mstring(s string) string {
var l []string
for _, c := range s {
switch c {
case 'L':
l = append(l, "load")
case 'S':
l = append(l, "spin")
case 'F':
l = append(l, "fire")
}
}
return strings.Join(l, ", ")
}
func main() {
rand.Seed(time.Now().UnixNano())
tests := 100000
for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} {
sum := 0
for t := 1; t <= tests; t++ {
sum += method(m)
}
pc := float64(sum) * 100 / float64(tests)
fmt.Printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc)
}
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static int nextInt(int size) {
return rand() % size;
}
static bool cylinder[6];
static void rshift() {
bool t = cylinder[5];
int i;
for (i = 4; i >= 0; i--) {
cylinder[i + 1] = cylinder[i];
}
cylinder[0] = t;
}
static void unload() {
int i;
for (i = 0; i < 6; i++) {
cylinder[i] = false;
}
}
static void load() {
while (cylinder[0]) {
rshift();
}
cylinder[0] = true;
rshift();
}
static void spin() {
int lim = nextInt(6) + 1;
int i;
for (i = 1; i < lim; i++) {
rshift();
}
}
static bool fire() {
bool shot = cylinder[0];
rshift();
return shot;
}
static int method(const char *s) {
unload();
for (; *s != '\0'; s++) {
switch (*s) {
case 'L':
load();
break;
case 'S':
spin();
break;
case 'F':
if (fire()) {
return 1;
}
break;
}
}
return 0;
}
static void append(char *out, const char *txt) {
if (*out != '\0') {
strcat(out, ", ");
}
strcat(out, txt);
}
static void mstring(const char *s, char *out) {
for (; *s != '\0'; s++) {
switch (*s) {
case 'L':
append(out, "load");
break;
case 'S':
append(out, "spin");
break;
case 'F':
append(out, "fire");
break;
}
}
}
static void test(char *src) {
char buffer[41] = "";
const int tests = 100000;
int sum = 0;
int t;
double pc;
for (t = 0; t < tests; t++) {
sum += method(src);
}
mstring(src, buffer);
pc = 100.0 * sum / tests;
printf("%-40s produces %6.3f%% deaths.\n", buffer, pc);
}
int main() {
srand(time(0));
test("LSLSFSF");
test("LSLSFF");
test("LLSFSF");
test("LLSFF");
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
fmt.Println("postfix:", parseInfix(input))
}
func parseInfix(e string) (rpn string) {
var stack []string
for _, tok := range strings.Fields(e) {
switch tok {
case "(":
stack = append(stack, tok)
case ")":
var op string
for {
op, stack = stack[len(stack)-1], stack[:len(stack)-1]
if op == "(" {
break
}
rpn += " " + op
}
default:
if o1, isOp := opa[tok]; isOp {
for len(stack) > 0 {
op := stack[len(stack)-1]
if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||
o1.prec == o2.prec && o1.rAssoc {
break
}
stack = stack[:len(stack)-1]
rpn += " " + op
}
stack = append(stack, tok)
} else {
if rpn > "" {
rpn += " "
}
rpn += tok
}
}
}
for len(stack) > 0 {
rpn += " " + stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
return
}
| #include <sys/types.h>
#include <regex.h>
#include <stdio.h>
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};
pat_t pat_ops[] = {
{"^\\)", A_NONE, -1},
{"^\\*\\*", A_R, 3},
{"^\\^", A_R, 3},
{"^\\*", A_L, 2},
{"^/", A_L, 2},
{"^\\+", A_L, 1},
{"^-", A_L, 1},
{0}
};
pat_t pat_arg[] = {
{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
{"^[a-zA-Z_][a-zA-Z_0-9]*"},
{"^\\(", A_L, -1},
{0}
};
str_tok_t stack[256];
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop() stack[--l_stack]
void display(const char *s)
{
int i;
printf("\033[1;1H\033[JText | %s", s);
printf("\nStack| ");
for (i = 0; i < l_stack; i++)
printf("%.*s ", stack[i].len, stack[i].s);
printf("\nQueue| ");
for (i = 0; i < l_queue; i++)
printf("%.*s ", queue[i].len, queue[i].s);
puts("\n\n<press enter>");
getchar();
}
int prec_booster;
#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}
int init(void)
{
int i;
pat_t *p;
for (i = 0, p = pat_ops; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
for (i = 0, p = pat_arg; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
return 1;
}
pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
int i;
regmatch_t m;
while (*s == ' ') s++;
*e = s;
if (!*s) return &pat_eos;
for (i = 0; p[i].str; i++) {
if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
continue;
t->s = s;
*e = s + (t->len = m.rm_eo - m.rm_so);
return p + i;
}
return 0;
}
int parse(const char *s) {
pat_t *p;
str_tok_t *t, tok;
prec_booster = l_queue = l_stack = 0;
display(s);
while (*s) {
p = match(s, pat_arg, &tok, &s);
if (!p || p == &pat_eos) fail("parse arg", s);
if (p->prec == -1) {
prec_booster += 100;
continue;
}
qpush(tok);
display(s);
re_op: p = match(s, pat_ops, &tok, &s);
if (!p) fail("parse op", s);
tok.assoc = p->assoc;
tok.prec = p->prec;
if (p->prec > 0)
tok.prec = p->prec + prec_booster;
else if (p->prec == -1) {
if (prec_booster < 100)
fail("unmatched )", s);
tok.prec = prec_booster;
}
while (l_stack) {
t = stack + l_stack - 1;
if (!(t->prec == tok.prec && t->assoc == A_L)
&& t->prec <= tok.prec)
break;
qpush(spop());
display(s);
}
if (p->prec == -1) {
prec_booster -= 100;
goto re_op;
}
if (!p->prec) {
display(s);
if (prec_booster)
fail("unmatched (", s);
return 1;
}
spush(tok);
display(s);
}
if (p->prec > 0)
fail("unexpected eol", s);
return 1;
}
int main()
{
int i;
const char *tests[] = {
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"123",
"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14",
"(((((((1+2+3**(4 + 5))))))",
"a^(b + c/d * .1e5)!",
"(1**2)**3",
"2 + 2 *",
0
};
if (!init()) return 1;
for (i = 0; tests[i]; i++) {
printf("Testing string `%s' <enter>\n", tests[i]);
getchar();
printf("string `%s': %s\n\n", tests[i],
parse(tests[i]) ? "Ok" : "Error");
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
fmt.Println("postfix:", parseInfix(input))
}
func parseInfix(e string) (rpn string) {
var stack []string
for _, tok := range strings.Fields(e) {
switch tok {
case "(":
stack = append(stack, tok)
case ")":
var op string
for {
op, stack = stack[len(stack)-1], stack[:len(stack)-1]
if op == "(" {
break
}
rpn += " " + op
}
default:
if o1, isOp := opa[tok]; isOp {
for len(stack) > 0 {
op := stack[len(stack)-1]
if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||
o1.prec == o2.prec && o1.rAssoc {
break
}
stack = stack[:len(stack)-1]
rpn += " " + op
}
stack = append(stack, tok)
} else {
if rpn > "" {
rpn += " "
}
rpn += tok
}
}
}
for len(stack) > 0 {
rpn += " " + stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
return
}
| #include <sys/types.h>
#include <regex.h>
#include <stdio.h>
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};
pat_t pat_ops[] = {
{"^\\)", A_NONE, -1},
{"^\\*\\*", A_R, 3},
{"^\\^", A_R, 3},
{"^\\*", A_L, 2},
{"^/", A_L, 2},
{"^\\+", A_L, 1},
{"^-", A_L, 1},
{0}
};
pat_t pat_arg[] = {
{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
{"^[a-zA-Z_][a-zA-Z_0-9]*"},
{"^\\(", A_L, -1},
{0}
};
str_tok_t stack[256];
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop() stack[--l_stack]
void display(const char *s)
{
int i;
printf("\033[1;1H\033[JText | %s", s);
printf("\nStack| ");
for (i = 0; i < l_stack; i++)
printf("%.*s ", stack[i].len, stack[i].s);
printf("\nQueue| ");
for (i = 0; i < l_queue; i++)
printf("%.*s ", queue[i].len, queue[i].s);
puts("\n\n<press enter>");
getchar();
}
int prec_booster;
#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}
int init(void)
{
int i;
pat_t *p;
for (i = 0, p = pat_ops; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
for (i = 0, p = pat_arg; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
return 1;
}
pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
int i;
regmatch_t m;
while (*s == ' ') s++;
*e = s;
if (!*s) return &pat_eos;
for (i = 0; p[i].str; i++) {
if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
continue;
t->s = s;
*e = s + (t->len = m.rm_eo - m.rm_so);
return p + i;
}
return 0;
}
int parse(const char *s) {
pat_t *p;
str_tok_t *t, tok;
prec_booster = l_queue = l_stack = 0;
display(s);
while (*s) {
p = match(s, pat_arg, &tok, &s);
if (!p || p == &pat_eos) fail("parse arg", s);
if (p->prec == -1) {
prec_booster += 100;
continue;
}
qpush(tok);
display(s);
re_op: p = match(s, pat_ops, &tok, &s);
if (!p) fail("parse op", s);
tok.assoc = p->assoc;
tok.prec = p->prec;
if (p->prec > 0)
tok.prec = p->prec + prec_booster;
else if (p->prec == -1) {
if (prec_booster < 100)
fail("unmatched )", s);
tok.prec = prec_booster;
}
while (l_stack) {
t = stack + l_stack - 1;
if (!(t->prec == tok.prec && t->assoc == A_L)
&& t->prec <= tok.prec)
break;
qpush(spop());
display(s);
}
if (p->prec == -1) {
prec_booster -= 100;
goto re_op;
}
if (!p->prec) {
display(s);
if (prec_booster)
fail("unmatched (", s);
return 1;
}
spush(tok);
display(s);
}
if (p->prec > 0)
fail("unexpected eol", s);
return 1;
}
int main()
{
int i;
const char *tests[] = {
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"123",
"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14",
"(((((((1+2+3**(4 + 5))))))",
"a^(b + c/d * .1e5)!",
"(1**2)**3",
"2 + 2 *",
0
};
if (!init()) return 1;
for (i = 0; tests[i]; i++) {
printf("Testing string `%s' <enter>\n", tests[i]);
getchar();
printf("string `%s': %s\n\n", tests[i],
parse(tests[i]) ? "Ok" : "Error");
}
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
var canFollow [][]bool
var arrang []int
var bFirst = true
var pmap = make(map[int]bool)
func init() {
for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {
pmap[i] = true
}
}
func ptrs(res, n, done int) int {
ad := arrang[done-1]
if n-done <= 1 {
if canFollow[ad-1][n-1] {
if bFirst {
for _, e := range arrang {
fmt.Printf("%2d ", e)
}
fmt.Println()
bFirst = false
}
res++
}
} else {
done++
for i := done - 1; i <= n-2; i += 2 {
ai := arrang[i]
if canFollow[ad-1][ai-1] {
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
res = ptrs(res, n, done)
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
}
}
}
return res
}
func primeTriangle(n int) int {
canFollow = make([][]bool, n)
for i := 0; i < n; i++ {
canFollow[i] = make([]bool, n)
for j := 0; j < n; j++ {
_, ok := pmap[i+j+2]
canFollow[i][j] = ok
}
}
bFirst = true
arrang = make([]int, n)
for i := 0; i < n; i++ {
arrang[i] = i + 1
}
return ptrs(0, n, 1)
}
func main() {
counts := make([]int, 19)
for i := 2; i <= 20; i++ {
counts[i-2] = primeTriangle(i)
}
fmt.Println()
for i := 0; i < 19; i++ {
fmt.Printf("%d ", counts[i])
}
fmt.Println()
}
| #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool is_prime(unsigned int n) {
assert(n < 64);
static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};
return isprime[n];
}
void swap(unsigned int* a, size_t i, size_t j) {
unsigned int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
bool prime_triangle_row(unsigned int* a, size_t length) {
if (length == 2)
return is_prime(a[0] + a[1]);
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
if (prime_triangle_row(a + 1, length - 1))
return true;
swap(a, i, 1);
}
}
return false;
}
int prime_triangle_count(unsigned int* a, size_t length) {
int count = 0;
if (length == 2) {
if (is_prime(a[0] + a[1]))
++count;
} else {
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
count += prime_triangle_count(a + 1, length - 1);
swap(a, i, 1);
}
}
}
return count;
}
void print(unsigned int* a, size_t length) {
if (length == 0)
return;
printf("%2u", a[0]);
for (size_t i = 1; i < length; ++i)
printf(" %2u", a[i]);
printf("\n");
}
int main() {
clock_t start = clock();
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (prime_triangle_row(a, n))
print(a, n);
}
printf("\n");
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (n > 2)
printf(" ");
printf("%d", prime_triangle_count(a, n));
}
printf("\n");
clock_t end = clock();
double duration = (end - start + 0.0) / CLOCKS_PER_SEC;
printf("\nElapsed time: %f seconds\n", duration);
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"log"
"math"
)
func main() {
fmt.Print("Enter 11 numbers: ")
var s [11]float64
for i := 0; i < 11; {
if n, _ := fmt.Scan(&s[i]); n > 0 {
i++
}
}
for i, item := range s[:5] {
s[i], s[10-i] = s[10-i], item
}
for _, item := range s {
if result, overflow := f(item); overflow {
log.Printf("f(%g) overflow", item)
} else {
fmt.Printf("f(%g) = %g\n", item, result)
}
}
}
func f(x float64) (float64, bool) {
result := math.Sqrt(math.Abs(x)) + 5*x*x*x
return result, result > 400
}
| #include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i--)
{
result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);
printf ("\nf(%lf) = ");
if (result > check)
{
printf ("Overflow!");
}
else
{
printf ("%lf", result);
}
}
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package m3
import (
"errors"
"strconv"
)
var (
ErrorLT3 = errors.New("N of at least three digits required.")
ErrorEven = errors.New("N with odd number of digits required.")
)
func Digits(i int) (string, error) {
if i < 0 {
i = -i
}
if i < 100 {
return "", ErrorLT3
}
s := strconv.Itoa(i)
if len(s)%2 == 0 {
return "", ErrorEven
}
m := len(s) / 2
return s[m-1 : m+2], nil
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * mid3(int n)
{
static char buf[32];
int l;
sprintf(buf, "%d", n > 0 ? n : -n);
l = strlen(buf);
if (l < 3 || !(l & 1)) return 0;
l = l / 2 - 1;
buf[l + 3] = 0;
return buf + l;
}
int main(void)
{
int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
1234567890};
int i;
char *m;
for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
if (!(m = mid3(x[i])))
m = "error";
printf("%d: %s\n", x[i], m);
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"math"
"math/big"
)
var bi = new(big.Int)
func isPrime(n int) bool {
bi.SetUint64(uint64(n))
return bi.ProbablyPrime(0)
}
func generateSmallPrimes(n int) []int {
primes := make([]int, n)
primes[0] = 2
for i, count := 3, 1; count < n; i += 2 {
if isPrime(i) {
primes[count] = i
count++
}
}
return primes
}
func countDivisors(n int) int {
count := 1
for n%2 == 0 {
n >>= 1
count++
}
for d := 3; d*d <= n; d += 2 {
q, r := n/d, n%d
if r == 0 {
dc := 0
for r == 0 {
dc += count
n = q
q, r = n/d, n%d
}
count += dc
}
}
if n != 1 {
count *= 2
}
return count
}
func main() {
const max = 33
primes := generateSmallPrimes(max)
z := new(big.Int)
p := new(big.Int)
fmt.Println("The first", max, "terms in the sequence are:")
for i := 1; i <= max; i++ {
if isPrime(i) {
z.SetUint64(uint64(primes[i-1]))
p.SetUint64(uint64(i - 1))
z.Exp(z, p, nil)
fmt.Printf("%2d : %d\n", i, z)
} else {
count := 0
for j := 1; ; j++ {
if i%2 == 1 {
sq := int(math.Sqrt(float64(j)))
if sq*sq != j {
continue
}
}
if countDivisors(j) == i {
count++
if count == i {
fmt.Printf("%2d : %d\n", i, j)
break
}
}
}
}
}
}
| #include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#define LIMIT 15
int smallPrimes[LIMIT];
static void sieve() {
int i = 2, j;
int p = 5;
smallPrimes[0] = 2;
smallPrimes[1] = 3;
while (i < LIMIT) {
for (j = 0; j < i; j++) {
if (smallPrimes[j] * smallPrimes[j] <= p) {
if (p % smallPrimes[j] == 0) {
p += 2;
break;
}
} else {
smallPrimes[i++] = p;
p += 2;
break;
}
}
}
}
static bool is_prime(uint64_t n) {
uint64_t i;
for (i = 0; i < LIMIT; i++) {
if (n % smallPrimes[i] == 0) {
return n == smallPrimes[i];
}
}
i = smallPrimes[LIMIT - 1] + 2;
for (; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
static uint64_t divisor_count(uint64_t n) {
uint64_t count = 1;
uint64_t d;
while (n % 2 == 0) {
n /= 2;
count++;
}
for (d = 3; d * d <= n; d += 2) {
uint64_t q = n / d;
uint64_t r = n % d;
uint64_t dc = 0;
while (r == 0) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if (n != 1) {
return count *= 2;
}
return count;
}
static uint64_t OEISA073916(size_t n) {
uint64_t count = 0;
uint64_t result = 0;
size_t i;
if (is_prime(n)) {
return (uint64_t)pow(smallPrimes[n - 1], n - 1);
}
for (i = 1; count < n; i++) {
if (n % 2 == 1) {
uint64_t root = (uint64_t)sqrt(i);
if (root * root != i) {
continue;
}
}
if (divisor_count(i) == n) {
count++;
result = i;
}
}
return result;
}
int main() {
size_t n;
sieve();
for (n = 1; n <= LIMIT; n++) {
if (n == 13) {
printf("A073916(%lu) = One more bit needed to represent result.\n", n);
} else {
printf("A073916(%lu) = %llu\n", n, OEISA073916(n));
}
}
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
seq := make([]int, max)
fmt.Println("The first", max, "terms of the sequence are:")
for i, n := 1, 0; n < max; i++ {
if k := countDivisors(i); k <= max && seq[k-1] == 0 {
seq[k-1] = i
n++
}
}
fmt.Println(seq)
}
| #include <stdio.h>
#define MAX 15
int count_divisors(int n) {
int i, count = 0;
for (i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
int i, k, n, seq[MAX];
for (i = 0; i < MAX; ++i) seq[i] = 0;
printf("The first %d terms of the sequence are:\n", MAX);
for (i = 1, n = 0; n < MAX; ++i) {
k = count_divisors(i);
if (k <= MAX && seq[k - 1] == 0) {
seq[k - 1] = i;
++n;
}
}
for (i = 0; i < MAX; ++i) printf("%d ", seq[i]);
printf("\n");
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import "fmt"
func pancake(n int) int {
gap, sum, adj := 2, 2, -1
for sum < n {
adj++
gap = gap*2 - 1
sum += gap
}
return n + adj
}
func main() {
for i := 0; i < 4; i++ {
for j := 1; j < 6; j++ {
n := i*5 + j
fmt.Printf("p(%2d) = %2d ", n, pancake(n))
}
fmt.Println()
}
}
| #include <stdio.h>
int pancake(int n) {
int gap = 2, sum = 2, adj = -1;
while (sum < n) {
adj++;
gap = gap * 2 - 1;
sum += gap;
}
return n + adj;
}
int main() {
int i, j;
for (i = 0; i < 4; i++) {
for (j = 1; j < 6; j++) {
int n = i * 5 + j;
printf("p(%2d) = %2d ", n, pancake(n));
}
printf("\n");
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import "fmt"
func pancake(n int) int {
gap, sum, adj := 2, 2, -1
for sum < n {
adj++
gap = gap*2 - 1
sum += gap
}
return n + adj
}
func main() {
for i := 0; i < 4; i++ {
for j := 1; j < 6; j++ {
n := i*5 + j
fmt.Printf("p(%2d) = %2d ", n, pancake(n))
}
fmt.Println()
}
}
| #include <stdio.h>
int pancake(int n) {
int gap = 2, sum = 2, adj = -1;
while (sum < n) {
adj++;
gap = gap * 2 - 1;
sum += gap;
}
return n + adj;
}
int main() {
int i, j;
for (i = 0; i < 4; i++) {
for (j = 1; j < 6; j++) {
int n = i * 5 + j;
printf("p(%2d) = %2d ", n, pancake(n));
}
printf("\n");
}
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var grid [8][8]byte
func abs(i int) int {
if i >= 0 {
return i
} else {
return -i
}
}
func createFen() string {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
return toFen()
}
func placeKings() {
for {
r1 := rand.Intn(8)
c1 := rand.Intn(8)
r2 := rand.Intn(8)
c2 := rand.Intn(8)
if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {
grid[r1][c1] = 'K'
grid[r2][c2] = 'k'
return
}
}
}
func placePieces(pieces string, isPawn bool) {
numToPlace := rand.Intn(len(pieces))
for n := 0; n < numToPlace; n++ {
var r, c int
for {
r = rand.Intn(8)
c = rand.Intn(8)
if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) {
break
}
}
grid[r][c] = pieces[n]
}
}
func toFen() string {
var fen strings.Builder
countEmpty := 0
for r := 0; r < 8; r++ {
for c := 0; c < 8; c++ {
ch := grid[r][c]
if ch == '\000' {
ch = '.'
}
fmt.Printf("%2c ", ch)
if ch == '.' {
countEmpty++
} else {
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteByte(ch)
}
}
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteString("/")
fmt.Println()
}
fen.WriteString(" w - - 0 1")
return fen.String()
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(createFen())
}
| #include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
char grid[8][8];
void placeKings() {
int r1, r2, c1, c2;
for (;;) {
r1 = rand() % 8;
c1 = rand() % 8;
r2 = rand() % 8;
c2 = rand() % 8;
if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
grid[r1][c1] = 'K';
grid[r2][c2] = 'k';
return;
}
}
}
void placePieces(const char *pieces, bool isPawn) {
int n, r, c;
int numToPlace = rand() % strlen(pieces);
for (n = 0; n < numToPlace; ++n) {
do {
r = rand() % 8;
c = rand() % 8;
}
while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
grid[r][c] = pieces[n];
}
}
void toFen() {
char fen[80], ch;
int r, c, countEmpty = 0, index = 0;
for (r = 0; r < 8; ++r) {
for (c = 0; c < 8; ++c) {
ch = grid[r][c];
printf("%2c ", ch == 0 ? '.' : ch);
if (ch == 0) {
countEmpty++;
}
else {
if (countEmpty > 0) {
fen[index++] = countEmpty + 48;
countEmpty = 0;
}
fen[index++] = ch;
}
}
if (countEmpty > 0) {
fen[index++] = countEmpty + 48;
countEmpty = 0;
}
fen[index++]= '/';
printf("\n");
}
strcpy(fen + index, " w - - 0 1");
printf("%s\n", fen);
}
char *createFen() {
placeKings();
placePieces("PPPPPPPP", TRUE);
placePieces("pppppppp", TRUE);
placePieces("RNBQBNR", FALSE);
placePieces("rnbqbnr", FALSE);
toFen();
}
int main() {
srand(time(NULL));
createFen();
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
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() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
}
| #include <stdio.h>
#include <string.h>
#include <locale.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
char as_digit(int d) {
return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';
}
void revstr(char *str) {
int i, len = strlen(str);
char t;
for (i = 0; i < len/2; ++i) {
t = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = t;
}
}
char* to_base(char s[], ull n, int b) {
int i = 0;
while (n) {
s[i++] = as_digit(n % b);
n /= b;
}
s[i] = '\0';
revstr(s);
return s;
}
ull uabs(ull a, ull b) {
return a > b ? a - b : b - a;
}
bool is_esthetic(ull n, int b) {
int i, j;
if (!n) return FALSE;
i = n % b;
n /= b;
while (n) {
j = n % b;
if (uabs(i, j) != 1) return FALSE;
n /= b;
i = j;
}
return TRUE;
}
ull esths[45000];
int le = 0;
void dfs(ull n, ull m, ull i) {
ull d, i1, i2;
if (i >= n && i <= m) esths[le++] = i;
if (i == 0 || i > m) return;
d = i % 10;
i1 = i * 10 + d - 1;
i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {
int i;
le = 0;
for (i = 0; i < 10; ++i) {
dfs(n2, m2, i);
}
printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m);
if (all) {
for (i = 0; i < le; ++i) {
printf("%llu ", esths[i]);
if (!(i+1)%per_line) printf("\n");
}
} else {
for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]);
printf("\n............\n");
for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]);
}
printf("\n\n");
}
int main() {
ull n;
int b, c;
char ch[15] = {0};
for (b = 2; b <= 16; ++b) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b);
for (n = 1, c = 0; c < 6 * b; ++n) {
if (is_esthetic(n, b)) {
if (++c >= 4 * b) printf("%s ", to_base(ch, n, b));
}
}
printf("\n\n");
}
char *oldLocale = setlocale(LC_NUMERIC, NULL);
setlocale(LC_NUMERIC, "");
list_esths(1000, 1010, 9999, 9898, 16, TRUE);
list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);
list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);
list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);
list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);
setlocale(LC_NUMERIC, oldLocale);
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
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() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
}
| #include <stdio.h>
#include <string.h>
#include <locale.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
char as_digit(int d) {
return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';
}
void revstr(char *str) {
int i, len = strlen(str);
char t;
for (i = 0; i < len/2; ++i) {
t = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = t;
}
}
char* to_base(char s[], ull n, int b) {
int i = 0;
while (n) {
s[i++] = as_digit(n % b);
n /= b;
}
s[i] = '\0';
revstr(s);
return s;
}
ull uabs(ull a, ull b) {
return a > b ? a - b : b - a;
}
bool is_esthetic(ull n, int b) {
int i, j;
if (!n) return FALSE;
i = n % b;
n /= b;
while (n) {
j = n % b;
if (uabs(i, j) != 1) return FALSE;
n /= b;
i = j;
}
return TRUE;
}
ull esths[45000];
int le = 0;
void dfs(ull n, ull m, ull i) {
ull d, i1, i2;
if (i >= n && i <= m) esths[le++] = i;
if (i == 0 || i > m) return;
d = i % 10;
i1 = i * 10 + d - 1;
i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {
int i;
le = 0;
for (i = 0; i < 10; ++i) {
dfs(n2, m2, i);
}
printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m);
if (all) {
for (i = 0; i < le; ++i) {
printf("%llu ", esths[i]);
if (!(i+1)%per_line) printf("\n");
}
} else {
for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]);
printf("\n............\n");
for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]);
}
printf("\n\n");
}
int main() {
ull n;
int b, c;
char ch[15] = {0};
for (b = 2; b <= 16; ++b) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b);
for (n = 1, c = 0; c < 6 * b; ++n) {
if (is_esthetic(n, b)) {
if (++c >= 4 * b) printf("%s ", to_base(ch, n, b));
}
}
printf("\n\n");
}
char *oldLocale = setlocale(LC_NUMERIC, NULL);
setlocale(LC_NUMERIC, "");
list_esths(1000, 1010, 9999, 9898, 16, TRUE);
list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);
list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);
list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);
list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);
setlocale(LC_NUMERIC, oldLocale);
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. |
package main
import "fmt"
const (
maxn = 10
maxl = 50
)
func main() {
for i := 1; i <= maxn; i++ {
fmt.Printf("%d: %d\n", i, steps(i))
}
}
func steps(n int) int {
var a, b [maxl][maxn + 1]int
var x [maxl]int
a[0][0] = 1
var m int
for l := 0; ; {
x[l]++
k := int(x[l])
if k >= n {
if l <= 0 {
break
}
l--
continue
}
if a[l][k] == 0 {
if b[l][k+1] != 0 {
continue
}
} else if a[l][k] != k+1 {
continue
}
a[l+1] = a[l]
for j := 1; j <= k; j++ {
a[l+1][j] = a[l][k-j]
}
b[l+1] = b[l]
a[l+1][0] = k + 1
b[l+1][k+1] = 1
if l > m-1 {
m = l + 1
}
l++
x[l] = 0
}
return m
}
| #include <stdio.h>
#include <string.h>
typedef struct { char v[16]; } deck;
typedef unsigned int uint;
uint n, d, best[16];
void tryswaps(deck *a, uint f, uint s) {
# define A a->v
# define B b.v
if (d > best[n]) best[n] = d;
while (1) {
if ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))
&& (d + best[s] >= best[n] || A[s] == -1))
break;
if (d + best[s] <= best[n]) return;
if (!--s) return;
}
d++;
deck b = *a;
for (uint i = 1, k = 2; i <= s; k <<= 1, i++) {
if (A[i] != i && (A[i] != -1 || (f & k)))
continue;
for (uint j = B[0] = i; j--;) B[i - j] = A[j];
tryswaps(&b, f | k, s);
}
d--;
}
int main(void) {
deck x;
memset(&x, -1, sizeof(x));
x.v[0] = 0;
for (n = 1; n < 13; n++) {
tryswaps(&x, 1, n - 1);
printf("%2d: %d\n", n, best[n]);
}
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
units := []string{
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer",
}
convs := []float32{
0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668, 74676,
1, 100, 10000,
}
scanner := bufio.NewScanner(os.Stdin)
for {
for i, u := range units {
fmt.Printf("%2d %s\n", i+1, u)
}
fmt.Println()
var unit int
var err error
for {
fmt.Print("Please choose a unit 1 to 13 : ")
scanner.Scan()
unit, err = strconv.Atoi(scanner.Text())
if err == nil && unit >= 1 && unit <= 13 {
break
}
}
unit--
var value float64
for {
fmt.Print("Now enter a value in that unit : ")
scanner.Scan()
value, err = strconv.ParseFloat(scanner.Text(), 32)
if err == nil && value >= 0 {
break
}
}
fmt.Println("\nThe equivalent in the remaining units is:\n")
for i, u := range units {
if i == unit {
continue
}
fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i])
}
fmt.Println()
yn := ""
for yn != "y" && yn != "n" {
fmt.Print("Do another one y/n : ")
scanner.Scan()
yn = strings.ToLower(scanner.Text())
}
if yn == "n" {
return
}
}
}
| #include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
#define UNITS_LENGTH 13
int main(int argC,char* argV[])
{
int i,reference;
char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};
if(argC!=3)
printf("Usage : %s followed by length as <value> <unit>");
else{
for(i=0;argV[2][i]!=00;i++)
argV[2][i] = tolower(argV[2][i]);
for(i=0;i<UNITS_LENGTH;i++){
if(strstr(argV[2],units[i])!=NULL){
reference = i;
factor = atof(argV[1])*values[i];
break;
}
}
printf("%s %s is equal in length to : \n",argV[1],argV[2]);
for(i=0;i<UNITS_LENGTH;i++){
if(i!=reference)
printf("\n%lf %s",factor/values[i],units[i]);
}
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"math/rand"
"time"
)
type rateStateS struct {
lastFlush time.Time
period time.Duration
tickCount int
}
func ticRate(pRate *rateStateS) {
pRate.tickCount++
now := time.Now()
if now.Sub(pRate.lastFlush) >= pRate.period {
tps := 0.
if pRate.tickCount > 0 {
tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()
}
fmt.Println(tps, "tics per second.")
pRate.tickCount = 0
pRate.lastFlush = now
}
}
func somethingWeDo() {
time.Sleep(time.Duration(9e7 + rand.Int63n(2e7)))
}
func main() {
start := time.Now()
rateWatch := rateStateS{
lastFlush: start,
period: 5 * time.Second,
}
latest := start
for latest.Sub(start) < 20*time.Second {
somethingWeDo()
ticRate(&rateWatch)
latest = time.Now()
}
}
| #include <stdio.h>
#include <time.h>
struct rate_state_s
{
time_t lastFlush;
time_t period;
size_t tickCount;
};
void tic_rate(struct rate_state_s* pRate)
{
pRate->tickCount += 1;
time_t now = time(NULL);
if((now - pRate->lastFlush) >= pRate->period)
{
size_t tps = 0.0;
if(pRate->tickCount > 0)
tps = pRate->tickCount / (now - pRate->lastFlush);
printf("%u tics per second.\n", tps);
pRate->tickCount = 0;
pRate->lastFlush = now;
}
}
void something_we_do()
{
volatile size_t anchor = 0;
size_t x = 0;
for(x = 0; x < 0xffff; ++x)
{
anchor = x;
}
}
int main()
{
time_t start = time(NULL);
struct rate_state_s rateWatch;
rateWatch.lastFlush = start;
rateWatch.tickCount = 0;
rateWatch.period = 5;
time_t latest = start;
for(latest = start; (latest - start) < 20; latest = time(NULL))
{
something_we_do();
tic_rate(&rateWatch);
}
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
fmt.Println("The first", max, "terms of the sequence are:")
for i, next := 1, 1; next <= max; i++ {
if next == countDivisors(i) {
fmt.Printf("%d ", i)
next++
}
}
fmt.Println()
}
| #include <stdio.h>
#define MAX 15
int count_divisors(int n) {
int i, count = 0;
for (i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
int i, next = 1;
printf("The first %d terms of the sequence are:\n", MAX);
for (i = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
printf("%d ", i);
next++;
}
}
printf("\n");
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)
p, _ = p.SetString("1.324717957244746025960908854")
s, _ = s.SetString("1.0453567932525329623")
f := make([]int, n)
pow := new(big.Rat).SetInt64(1)
u = u.SetFrac64(1, 2)
t.Quo(pow, p)
t.Quo(t, s)
t.Add(t, u)
v, _ := t.Float64()
f[0] = int(math.Floor(v))
for i := 1; i < n; i++ {
t.Quo(pow, s)
t.Add(t, u)
v, _ = t.Float64()
f[i] = int(math.Floor(v))
pow.Mul(pow, p)
}
return f
}
type LSystem struct {
rules map[string]string
init, current string
}
func step(lsys *LSystem) string {
var sb strings.Builder
if lsys.current == "" {
lsys.current = lsys.init
} else {
for _, c := range lsys.current {
sb.WriteString(lsys.rules[string(c)])
}
lsys.current = sb.String()
}
return lsys.current
}
func padovanLSys(n int) []string {
rules := map[string]string{"A": "B", "B": "C", "C": "AB"}
lsys := &LSystem{rules, "A", ""}
p := make([]string, n)
for i := 0; i < n; i++ {
p[i] = step(lsys)
}
return p
}
func areSame(l1, l2 []int) bool {
for i := 0; i < len(l1); i++ {
if l1[i] != l2[i] {
return false
}
}
return true
}
func main() {
fmt.Println("First 20 members of the Padovan sequence:")
fmt.Println(padovanRecur(20))
recur := padovanRecur(64)
floor := padovanFloor(64)
same := areSame(recur, floor)
s := "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.")
p := padovanLSys(32)
lsyst := make([]int, 32)
for i := 0; i < 32; i++ {
lsyst[i] = len(p[i])
}
fmt.Println("\nFirst 10 members of the Padovan L-System:")
fmt.Println(p[:10])
fmt.Println("\nand their lengths:")
fmt.Println(lsyst[:10])
same = areSame(recur[:32], lsyst)
s = "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int pRec(int n) {
static int *memo = NULL;
static size_t curSize = 0;
if (curSize <= (size_t) n) {
size_t lastSize = curSize;
while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
memo = realloc(memo, curSize * sizeof(int));
memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
}
if (memo[n] == 0) {
if (n<=2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
}
return memo[n];
}
int pFloor(int n) {
long double p = 1.324717957244746025960908854;
long double s = 1.0453567932525329623;
return powl(p, n-1)/s + 0.5;
}
void nextLSystem(const char *prev, char *buf) {
while (*prev) {
switch (*prev++) {
case 'A': *buf++ = 'B'; break;
case 'B': *buf++ = 'C'; break;
case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
}
}
*buf = '\0';
}
int main() {
#define BUFSZ 8192
char buf1[BUFSZ], buf2[BUFSZ];
int i;
printf("P_0 .. P_19: ");
for (i=0; i<20; i++) printf("%d ", pRec(i));
printf("\n");
printf("The floor- and recurrence-based functions ");
for (i=0; i<64; i++) {
if (pRec(i) != pFloor(i)) {
printf("do not match at %d: %d != %d.\n",
i, pRec(i), pFloor(i));
break;
}
}
if (i == 64) {
printf("match from P_0 to P_63.\n");
}
printf("\nThe first 10 L-system strings are:\n");
for (strcpy(buf1, "A"), i=0; i<10; i++) {
printf("%s\n", buf1);
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
printf("\nThe floor- and L-system-based functions ");
for (strcpy(buf1, "A"), i=0; i<32; i++) {
if ((int)strlen(buf1) != pFloor(i)) {
printf("do not match at %d: %d != %d\n",
i, (int)strlen(buf1), pFloor(i));
break;
}
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
if (i == 32) {
printf("match from P_0 to P_31.\n");
}
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)
p, _ = p.SetString("1.324717957244746025960908854")
s, _ = s.SetString("1.0453567932525329623")
f := make([]int, n)
pow := new(big.Rat).SetInt64(1)
u = u.SetFrac64(1, 2)
t.Quo(pow, p)
t.Quo(t, s)
t.Add(t, u)
v, _ := t.Float64()
f[0] = int(math.Floor(v))
for i := 1; i < n; i++ {
t.Quo(pow, s)
t.Add(t, u)
v, _ = t.Float64()
f[i] = int(math.Floor(v))
pow.Mul(pow, p)
}
return f
}
type LSystem struct {
rules map[string]string
init, current string
}
func step(lsys *LSystem) string {
var sb strings.Builder
if lsys.current == "" {
lsys.current = lsys.init
} else {
for _, c := range lsys.current {
sb.WriteString(lsys.rules[string(c)])
}
lsys.current = sb.String()
}
return lsys.current
}
func padovanLSys(n int) []string {
rules := map[string]string{"A": "B", "B": "C", "C": "AB"}
lsys := &LSystem{rules, "A", ""}
p := make([]string, n)
for i := 0; i < n; i++ {
p[i] = step(lsys)
}
return p
}
func areSame(l1, l2 []int) bool {
for i := 0; i < len(l1); i++ {
if l1[i] != l2[i] {
return false
}
}
return true
}
func main() {
fmt.Println("First 20 members of the Padovan sequence:")
fmt.Println(padovanRecur(20))
recur := padovanRecur(64)
floor := padovanFloor(64)
same := areSame(recur, floor)
s := "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.")
p := padovanLSys(32)
lsyst := make([]int, 32)
for i := 0; i < 32; i++ {
lsyst[i] = len(p[i])
}
fmt.Println("\nFirst 10 members of the Padovan L-System:")
fmt.Println(p[:10])
fmt.Println("\nand their lengths:")
fmt.Println(lsyst[:10])
same = areSame(recur[:32], lsyst)
s = "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int pRec(int n) {
static int *memo = NULL;
static size_t curSize = 0;
if (curSize <= (size_t) n) {
size_t lastSize = curSize;
while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
memo = realloc(memo, curSize * sizeof(int));
memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
}
if (memo[n] == 0) {
if (n<=2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
}
return memo[n];
}
int pFloor(int n) {
long double p = 1.324717957244746025960908854;
long double s = 1.0453567932525329623;
return powl(p, n-1)/s + 0.5;
}
void nextLSystem(const char *prev, char *buf) {
while (*prev) {
switch (*prev++) {
case 'A': *buf++ = 'B'; break;
case 'B': *buf++ = 'C'; break;
case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
}
}
*buf = '\0';
}
int main() {
#define BUFSZ 8192
char buf1[BUFSZ], buf2[BUFSZ];
int i;
printf("P_0 .. P_19: ");
for (i=0; i<20; i++) printf("%d ", pRec(i));
printf("\n");
printf("The floor- and recurrence-based functions ");
for (i=0; i<64; i++) {
if (pRec(i) != pFloor(i)) {
printf("do not match at %d: %d != %d.\n",
i, pRec(i), pFloor(i));
break;
}
}
if (i == 64) {
printf("match from P_0 to P_63.\n");
}
printf("\nThe first 10 L-system strings are:\n");
for (strcpy(buf1, "A"), i=0; i<10; i++) {
printf("%s\n", buf1);
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
printf("\nThe floor- and L-system-based functions ");
for (strcpy(buf1, "A"), i=0; i<32; i++) {
if ((int)strlen(buf1) != pFloor(i)) {
printf("do not match at %d: %d != %d\n",
i, (int)strlen(buf1), pFloor(i));
break;
}
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
if (i == 32) {
printf("match from P_0 to P_31.\n");
}
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"log"
"os"
)
const (
width, height = 800, 600
maxDepth = 11
colFactor = uint8(255 / maxDepth)
fileName = "pythagorasTree.png"
)
func main() {
img := image.NewNRGBA(image.Rect(0, 0, width, height))
bg := image.NewUniform(color.RGBA{255, 255, 255, 255})
draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)
drawSquares(340, 550, 460, 550, img, 0)
imgFile, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer imgFile.Close()
if err := png.Encode(imgFile, img); err != nil {
imgFile.Close()
log.Fatal(err)
}
}
func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {
if depth > maxDepth {
return
}
dx, dy := bx-ax, ay-by
x3, y3 := bx-dy, by-dx
x4, y4 := ax-dy, ay-dx
x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2
col := color.RGBA{0, uint8(depth) * colFactor, 0, 255}
drawLine(ax, ay, bx, by, img, col)
drawLine(bx, by, x3, y3, img, col)
drawLine(x3, y3, x4, y4, img, col)
drawLine(x4, y4, ax, ay, img, col)
drawSquares(x4, y4, x5, y5, img, depth+1)
drawSquares(x5, y5, x3, y3, img, depth+1)
}
func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) {
dx := abs(x1 - x0)
dy := abs(y1 - y0)
var sx, sy int = -1, -1
if x0 < x1 {
sx = 1
}
if y0 < y1 {
sy = 1
}
err := dx - dy
for {
img.Set(x0, y0, col)
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 > -dy {
err -= dy
x0 += sx
}
if e2 < dx {
err += dx
y0 += sy
}
}
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct{
double x,y;
}point;
void pythagorasTree(point a,point b,int times){
point c,d,e;
c.x = b.x - (a.y - b.y);
c.y = b.y - (b.x - a.x);
d.x = a.x - (a.y - b.y);
d.y = a.y - (b.x - a.x);
e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2;
e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2;
if(times>0){
setcolor(rand()%15 + 1);
line(a.x,a.y,b.x,b.y);
line(c.x,c.y,b.x,b.y);
line(c.x,c.y,d.x,d.y);
line(a.x,a.y,d.x,d.y);
pythagorasTree(d,e,times-1);
pythagorasTree(e,c,times-1);
}
}
int main(){
point a,b;
double side;
int iter;
time_t t;
printf("Enter initial side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
a.x = 6*side/2 - side/2;
a.y = 4*side;
b.x = 6*side/2 + side/2;
b.y = 4*side;
initwindow(6*side,4*side,"Pythagoras Tree ?");
srand((unsigned)time(&t));
pythagorasTree(a,b,iter);
getch();
closegraph();
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader) {
byte_in := func () byte {
bs := make([]byte, 1)
src.Read(bs)
return bs[0]
}
byte_out := func (b byte) { dst.Write([]byte{b}) }
var odd func() byte
odd = func() byte {
s := byte_in()
if unicode.IsPunct(rune(s)) {
return s
}
b := odd()
byte_out(s)
return b
}
for {
for {
b := byte_in()
byte_out(b)
if b == '.' {
return
}
if unicode.IsPunct(rune(b)) {
break
}
}
b := odd()
byte_out(b)
if b == '.' {
return
}
}
}
| #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
int ch = 1;
while ((ch = owp(!ch)) != EOF) {
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"log"
"math"
)
var a1 = []int64{0, 1403580, -810728}
var a2 = []int64{527612, 0, -1370589}
const m1 = int64((1 << 32) - 209)
const m2 = int64((1 << 32) - 22853)
const d = m1 + 1
func mod(x, y int64) int64 {
m := x % y
if m < 0 {
if y < 0 {
return m - y
} else {
return m + y
}
}
return m
}
type MRG32k3a struct{ x1, x2 [3]int64 }
func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }
func (mrg *MRG32k3a) seed(seedState int64) {
if seedState <= 0 || seedState >= d {
log.Fatalf("Argument must be in the range [0, %d].\n", d)
}
mrg.x1 = [3]int64{seedState, 0, 0}
mrg.x2 = [3]int64{seedState, 0, 0}
}
func (mrg *MRG32k3a) nextInt() int64 {
x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)
x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)
mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]}
mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]}
return mod(x1i-x2i, m1) + 1
}
func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }
func main() {
randomGen := MRG32k3aNew()
randomGen.seed(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
| #include <math.h>
#include <stdio.h>
#include <stdint.h>
int64_t mod(int64_t x, int64_t y) {
int64_t m = x % y;
if (m < 0) {
if (y < 0) {
return m - y;
} else {
return m + y;
}
}
return m;
}
const static int64_t a1[3] = { 0, 1403580, -810728 };
const static int64_t m1 = (1LL << 32) - 209;
const static int64_t a2[3] = { 527612, 0, -1370589 };
const static int64_t m2 = (1LL << 32) - 22853;
const static int64_t d = (1LL << 32) - 209 + 1;
static int64_t x1[3];
static int64_t x2[3];
void seed(int64_t seed_state) {
x1[0] = seed_state;
x1[1] = 0;
x1[2] = 0;
x2[0] = seed_state;
x2[1] = 0;
x2[2] = 0;
}
int64_t next_int() {
int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);
int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);
int64_t z = mod(x1i - x2i, m1);
x1[2] = x1[1];
x1[1] = x1[0];
x1[0] = x1i;
x2[2] = x2[1];
x2[1] = x2[0];
x2[0] = x2i;
return z + 1;
}
double next_float() {
return (double)next_int() / d;
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("\n");
seed(987654321);
for (i = 0; i < 100000; i++) {
int64_t value = floor(next_float() * 5);
counts[value]++;
}
for (i = 0; i < 5; i++) {
printf("%d: %d\n", i, counts[i]);
}
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
| #include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool colorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[10] = {};
int digits[8] = {};
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[36] = {};
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
static int count[8];
static bool used[10];
static int largest = 0;
void count_colorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
count_colorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (colorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
count_colorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
int main() {
setlocale(LC_ALL, "");
clock_t start = clock();
printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (colorful(n))
printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
count_colorful(0, 0, 0);
printf("\n\nLargest colorful number: %'d\n", largest);
printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
printf("%d %'d\n", d + 1, count[d]);
total += count[d];
}
printf("\nTotal: %'d\n", total);
clock_t end = clock();
printf("\nElapsed time: %f seconds\n",
(end - start + 0.0) / CLOCKS_PER_SEC);
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
| #include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool colorful(int n) {
if (n < 0 || n > 98765432)
return false;
int digit_count[10] = {};
int digits[8] = {};
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
int products[36] = {};
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
static int count[8];
static bool used[10];
static int largest = 0;
void count_colorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
count_colorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (colorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
count_colorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
int main() {
setlocale(LC_ALL, "");
clock_t start = clock();
printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (colorful(n))
printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
count_colorful(0, 0, 0);
printf("\n\nLargest colorful number: %'d\n", largest);
printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
printf("%d %'d\n", d + 1, count[d]);
total += count[d];
}
printf("\nTotal: %'d\n", total);
clock_t end = clock();
printf("\nElapsed time: %f seconds\n",
(end - start + 0.0) / CLOCKS_PER_SEC);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"html"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
)
func main() {
ex := `<li><a href="/wiki/(.*?)"`
re := regexp.MustCompile(ex)
page := "http:
resp, _ := http.Get(page)
body, _ := ioutil.ReadAll(resp.Body)
matches := re.FindAllStringSubmatch(string(body), -1)
resp.Body.Close()
tasks := make([]string, len(matches))
for i, match := range matches {
tasks[i] = match[1]
}
const base = "http:
const limit = 3
ex = `(?s)using any language you may know.</div>(.*?)<div id="toc"`
ex2 := `</?[^>]*>`
re = regexp.MustCompile(ex)
re2 := regexp.MustCompile(ex2)
for i, task := range tasks {
page = base + task
resp, _ = http.Get(page)
body, _ = ioutil.ReadAll(resp.Body)
match := re.FindStringSubmatch(string(body))
resp.Body.Close()
text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], ""))
fmt.Println(strings.Replace(task, "_", " ", -1), "\n", text)
if i == limit-1 {
break
}
time.Sleep(5 * time.Second)
}
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_tasks_without_examples.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;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"log"
"math"
"time"
)
const layout = "2006-01-02"
var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "}
var lengths = [3]int{23, 28, 33}
var quadrants = [4][2]string{
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func biorhythms(birthDate, targetDate string) {
bd, err := time.Parse(layout, birthDate)
check(err)
td, err := time.Parse(layout, targetDate)
check(err)
days := int(td.Sub(bd).Hours() / 24)
fmt.Printf("Born %s, Target %s\n", birthDate, targetDate)
fmt.Println("Day", days)
for i := 0; i < 3; i++ {
length := lengths[i]
cycle := cycles[i]
position := days % length
quadrant := position * 4 / length
percent := math.Sin(2 * math.Pi * float64(position) / float64(length))
percent = math.Floor(percent*1000) / 10
descript := ""
if percent > 95 {
descript = " peak"
} else if percent < -95 {
descript = " valley"
} else if math.Abs(percent) < 5 {
descript = " critical transition"
} else {
daysToAdd := (quadrant+1)*length/4 - position
transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))
trend := quadrants[quadrant][0]
next := quadrants[quadrant][1]
transStr := transition.Format(layout)
descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr)
}
fmt.Printf("%s %2d : %s\n", cycle, position, descript)
}
fmt.Println()
}
func main() {
datePairs := [][2]string{
{"1943-03-09", "1972-07-11"},
{"1809-01-12", "1863-11-19"},
{"1809-02-12", "1863-11-19"},
}
for _, datePair := range datePairs {
biorhythms(datePair[0], datePair[1])
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
printf(" (critical day)");
printf("\n");
}
int main(int argc, char *argv[]) {
int diff;
if (argc < 7) {
printf("Usage:\n");
printf("cbio y1 m1 d1 y2 m2 d2\n");
exit(1);
}
diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
- day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
printf("Age: %u days\n", diff);
cycle(diff, 23, "Physical");
cycle(diff, 28, "Emotional");
cycle(diff, 33, "Intellectual");
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"log"
"math"
"time"
)
const layout = "2006-01-02"
var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "}
var lengths = [3]int{23, 28, 33}
var quadrants = [4][2]string{
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func biorhythms(birthDate, targetDate string) {
bd, err := time.Parse(layout, birthDate)
check(err)
td, err := time.Parse(layout, targetDate)
check(err)
days := int(td.Sub(bd).Hours() / 24)
fmt.Printf("Born %s, Target %s\n", birthDate, targetDate)
fmt.Println("Day", days)
for i := 0; i < 3; i++ {
length := lengths[i]
cycle := cycles[i]
position := days % length
quadrant := position * 4 / length
percent := math.Sin(2 * math.Pi * float64(position) / float64(length))
percent = math.Floor(percent*1000) / 10
descript := ""
if percent > 95 {
descript = " peak"
} else if percent < -95 {
descript = " valley"
} else if math.Abs(percent) < 5 {
descript = " critical transition"
} else {
daysToAdd := (quadrant+1)*length/4 - position
transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))
trend := quadrants[quadrant][0]
next := quadrants[quadrant][1]
transStr := transition.Format(layout)
descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr)
}
fmt.Printf("%s %2d : %s\n", cycle, position, descript)
}
fmt.Println()
}
func main() {
datePairs := [][2]string{
{"1943-03-09", "1972-07-11"},
{"1809-01-12", "1863-11-19"},
{"1809-02-12", "1863-11-19"},
}
for _, datePair := range datePairs {
biorhythms(datePair[0], datePair[1])
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int day(int y, int m, int d) {
return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}
void cycle(int diff, int l, char *t) {
int p = round(100 * sin(2 * M_PI * diff / l));
printf("%12s cycle: %3i%%", t, p);
if (abs(p) < 15)
printf(" (critical day)");
printf("\n");
}
int main(int argc, char *argv[]) {
int diff;
if (argc < 7) {
printf("Usage:\n");
printf("cbio y1 m1 d1 y2 m2 d2\n");
exit(1);
}
diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
- day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
printf("Age: %u days\n", diff);
cycle(diff, 23, "Physical");
cycle(diff, 28, "Emotional");
cycle(diff, 33, "Intellectual");
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "rc.db")
if err != nil {
log.Print(err)
return
}
defer db.Close()
_, err = db.Exec(`create table addr (
id int unique,
street text,
city text,
state text,
zip text
)`)
if err != nil {
log.Print(err)
return
}
rows, err := db.Query(`pragma table_info(addr)`)
if err != nil {
log.Print(err)
return
}
var field, storage string
var ignore sql.RawBytes
for rows.Next() {
err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)
if err != nil {
log.Print(err)
return
}
fmt.Println(field, storage)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
const char *code =
"CREATE TABLE address (\n"
" addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" addrStreet TEXT NOT NULL,\n"
" addrCity TEXT NOT NULL,\n"
" addrState TEXT NOT NULL,\n"
" addrZIP TEXT NOT NULL)\n" ;
int main()
{
sqlite3 *db = NULL;
char *errmsg;
if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) {
fprintf(stderr, errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
exit(EXIT_FAILURE);
}
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"os/exec"
)
func main() {
synthType := "sine"
duration := "5"
frequency := "440"
cmd := exec.Command("play", "-n", "synth", duration, synthType, frequency)
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <math.h>
#include <stdlib.h>
int header[] = {46, 115, 110, 100, 0, 0, 0, 24,
255, 255, 255, 255, 0, 0, 0, 3,
0, 0, 172, 68, 0, 0, 0, 1};
int main(int argc, char *argv[]){
float freq, dur;
long i, v;
if (argc < 3) {
printf("Usage:\n");
printf(" csine <frequency> <duration>\n");
exit(1);
}
freq = atof(argv[1]);
dur = atof(argv[2]);
for (i = 0; i < 24; i++)
putchar(header[i]);
for (i = 0; i < dur * 44100; i++) {
v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));
v = v % 65536;
putchar(v >> 8);
putchar(v % 256);
}
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
jz
prtc
prts
prti
halt
)
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
}
type atr struct {
enumText string
nodeType NodeType
opcode code
}
var atrs = []atr{
{"Identifier", ndIdent, 255},
{"String", ndString, 255},
{"Integer", ndInteger, 255},
{"Sequence", ndSequence, 255},
{"If", ndIf, 255},
{"Prtc", ndPrtc, 255},
{"Prts", ndPrts, 255},
{"Prti", ndPrti, 255},
{"While", ndWhile, 255},
{"Assign", ndAssign, 255},
{"Negate", ndNegate, neg},
{"Not", ndNot, not},
{"Multiply", ndMul, mul},
{"Divide", ndDiv, div},
{"Mod", ndMod, mod},
{"Add", ndAdd, add},
{"Subtract", ndSub, sub},
{"Less", ndLss, lt},
{"LessEqual", ndLeq, le},
{"Greater", ndGtr, gt},
{"GreaterEqual", ndGeq, ge},
{"Equal", ndEql, eq},
{"NotEqual", ndNeq, ne},
{"And", ndAnd, and},
{"Or", ndOr, or},
}
var (
stringPool []string
globals []string
object []code
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func nodeType2Op(nodeType NodeType) code {
return atrs[nodeType].opcode
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, ""}
}
func makeLeaf(nodeType NodeType, value string) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func emitWordAt(at, n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for i := at; i < at+4; i++ {
object[i] = code(bs[i-at])
}
}
func hole() int {
t := len(object)
emitWord(0)
return t
}
func fetchVarOffset(id string) int {
for i := 0; i < len(globals); i++ {
if globals[i] == id {
return i
}
}
globals = append(globals, id)
return len(globals) - 1
}
func fetchStringOffset(st string) int {
for i := 0; i < len(stringPool); i++ {
if stringPool[i] == st {
return i
}
}
stringPool = append(stringPool, st)
return len(stringPool) - 1
}
func codeGen(x *Tree) {
if x == nil {
return
}
var n, p1, p2 int
switch x.nodeType {
case ndIdent:
emitByte(fetch)
n = fetchVarOffset(x.value)
emitWord(n)
case ndInteger:
emitByte(push)
n, err = strconv.Atoi(x.value)
check(err)
emitWord(n)
case ndString:
emitByte(push)
n = fetchStringOffset(x.value)
emitWord(n)
case ndAssign:
n = fetchVarOffset(x.left.value)
codeGen(x.right)
emitByte(store)
emitWord(n)
case ndIf:
codeGen(x.left)
emitByte(jz)
p1 = hole()
codeGen(x.right.left)
if x.right.right != nil {
emitByte(jmp)
p2 = hole()
}
emitWordAt(p1, len(object)-p1)
if x.right.right != nil {
codeGen(x.right.right)
emitWordAt(p2, len(object)-p2)
}
case ndWhile:
p1 = len(object)
codeGen(x.left)
emitByte(jz)
p2 = hole()
codeGen(x.right)
emitByte(jmp)
emitWord(p1 - len(object))
emitWordAt(p2, len(object)-p2)
case ndSequence:
codeGen(x.left)
codeGen(x.right)
case ndPrtc:
codeGen(x.left)
emitByte(prtc)
case ndPrti:
codeGen(x.left)
emitByte(prti)
case ndPrts:
codeGen(x.left)
emitByte(prts)
case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,
ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:
codeGen(x.left)
codeGen(x.right)
emitByte(nodeType2Op(x.nodeType))
case ndNegate, ndNot:
codeGen(x.left)
emitByte(nodeType2Op(x.nodeType))
default:
msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType)
reportError(msg)
}
}
func codeFinish() {
emitByte(halt)
}
func listCode() {
fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool))
for _, s := range stringPool {
fmt.Println(s)
}
pc := 0
for pc < len(object) {
fmt.Printf("%5d ", pc)
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("fetch [%d]\n", x)
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("store [%d]\n", x)
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("push %d\n", x)
pc += 4
case add:
fmt.Println("add")
case sub:
fmt.Println("sub")
case mul:
fmt.Println("mul")
case div:
fmt.Println("div")
case mod:
fmt.Println("mod")
case lt:
fmt.Println("lt")
case gt:
fmt.Println("gt")
case le:
fmt.Println("le")
case ge:
fmt.Println("ge")
case eq:
fmt.Println("eq")
case ne:
fmt.Println("ne")
case and:
fmt.Println("and")
case or:
fmt.Println("or")
case neg:
fmt.Println("neg")
case not:
fmt.Println("not")
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x)
pc += 4
case jz:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jz (%d) %d\n", x, int32(pc)+x)
pc += 4
case prtc:
fmt.Println("prtc")
case prti:
fmt.Println("prti")
case prts:
fmt.Println("prts")
case halt:
fmt.Println("halt")
default:
reportError(fmt.Sprintf("listCode: Unknown opcode %d", op))
}
}
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
return makeLeaf(nodeType, s)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
codeGen(loadAst())
codeFinish()
listCode()
}
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
jz
prtc
prts
prti
halt
)
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
}
type atr struct {
enumText string
nodeType NodeType
opcode code
}
var atrs = []atr{
{"Identifier", ndIdent, 255},
{"String", ndString, 255},
{"Integer", ndInteger, 255},
{"Sequence", ndSequence, 255},
{"If", ndIf, 255},
{"Prtc", ndPrtc, 255},
{"Prts", ndPrts, 255},
{"Prti", ndPrti, 255},
{"While", ndWhile, 255},
{"Assign", ndAssign, 255},
{"Negate", ndNegate, neg},
{"Not", ndNot, not},
{"Multiply", ndMul, mul},
{"Divide", ndDiv, div},
{"Mod", ndMod, mod},
{"Add", ndAdd, add},
{"Subtract", ndSub, sub},
{"Less", ndLss, lt},
{"LessEqual", ndLeq, le},
{"Greater", ndGtr, gt},
{"GreaterEqual", ndGeq, ge},
{"Equal", ndEql, eq},
{"NotEqual", ndNeq, ne},
{"And", ndAnd, and},
{"Or", ndOr, or},
}
var (
stringPool []string
globals []string
object []code
)
var (
err error
scanner *bufio.Scanner
)
func reportError(msg string) {
log.Fatalf("error : %s\n", msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func nodeType2Op(nodeType NodeType) code {
return atrs[nodeType].opcode
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, ""}
}
func makeLeaf(nodeType NodeType, value string) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func emitByte(c code) {
object = append(object, c)
}
func emitWord(n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for _, b := range bs {
emitByte(code(b))
}
}
func emitWordAt(at, n int) {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, uint32(n))
for i := at; i < at+4; i++ {
object[i] = code(bs[i-at])
}
}
func hole() int {
t := len(object)
emitWord(0)
return t
}
func fetchVarOffset(id string) int {
for i := 0; i < len(globals); i++ {
if globals[i] == id {
return i
}
}
globals = append(globals, id)
return len(globals) - 1
}
func fetchStringOffset(st string) int {
for i := 0; i < len(stringPool); i++ {
if stringPool[i] == st {
return i
}
}
stringPool = append(stringPool, st)
return len(stringPool) - 1
}
func codeGen(x *Tree) {
if x == nil {
return
}
var n, p1, p2 int
switch x.nodeType {
case ndIdent:
emitByte(fetch)
n = fetchVarOffset(x.value)
emitWord(n)
case ndInteger:
emitByte(push)
n, err = strconv.Atoi(x.value)
check(err)
emitWord(n)
case ndString:
emitByte(push)
n = fetchStringOffset(x.value)
emitWord(n)
case ndAssign:
n = fetchVarOffset(x.left.value)
codeGen(x.right)
emitByte(store)
emitWord(n)
case ndIf:
codeGen(x.left)
emitByte(jz)
p1 = hole()
codeGen(x.right.left)
if x.right.right != nil {
emitByte(jmp)
p2 = hole()
}
emitWordAt(p1, len(object)-p1)
if x.right.right != nil {
codeGen(x.right.right)
emitWordAt(p2, len(object)-p2)
}
case ndWhile:
p1 = len(object)
codeGen(x.left)
emitByte(jz)
p2 = hole()
codeGen(x.right)
emitByte(jmp)
emitWord(p1 - len(object))
emitWordAt(p2, len(object)-p2)
case ndSequence:
codeGen(x.left)
codeGen(x.right)
case ndPrtc:
codeGen(x.left)
emitByte(prtc)
case ndPrti:
codeGen(x.left)
emitByte(prti)
case ndPrts:
codeGen(x.left)
emitByte(prts)
case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq,
ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod:
codeGen(x.left)
codeGen(x.right)
emitByte(nodeType2Op(x.nodeType))
case ndNegate, ndNot:
codeGen(x.left)
emitByte(nodeType2Op(x.nodeType))
default:
msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType)
reportError(msg)
}
}
func codeFinish() {
emitByte(halt)
}
func listCode() {
fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool))
for _, s := range stringPool {
fmt.Println(s)
}
pc := 0
for pc < len(object) {
fmt.Printf("%5d ", pc)
op := object[pc]
pc++
switch op {
case fetch:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("fetch [%d]\n", x)
pc += 4
case store:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("store [%d]\n", x)
pc += 4
case push:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("push %d\n", x)
pc += 4
case add:
fmt.Println("add")
case sub:
fmt.Println("sub")
case mul:
fmt.Println("mul")
case div:
fmt.Println("div")
case mod:
fmt.Println("mod")
case lt:
fmt.Println("lt")
case gt:
fmt.Println("gt")
case le:
fmt.Println("le")
case ge:
fmt.Println("ge")
case eq:
fmt.Println("eq")
case ne:
fmt.Println("ne")
case and:
fmt.Println("and")
case or:
fmt.Println("or")
case neg:
fmt.Println("neg")
case not:
fmt.Println("not")
case jmp:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x)
pc += 4
case jz:
x := int32(binary.LittleEndian.Uint32(object[pc : pc+4]))
fmt.Printf("jz (%d) %d\n", x, int32(pc)+x)
pc += 4
case prtc:
fmt.Println("prtc")
case prti:
fmt.Println("prti")
case prts:
fmt.Println("prts")
case halt:
fmt.Println("halt")
default:
reportError(fmt.Sprintf("listCode: Unknown opcode %d", op))
}
}
}
func getEnumValue(name string) NodeType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.nodeType
}
}
reportError(fmt.Sprintf("Unknown token %s\n", name))
return -1
}
func loadAst() *Tree {
var nodeType NodeType
var s string
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
tokens := strings.Fields(line)
first := tokens[0]
if first[0] == ';' {
return nil
}
nodeType = getEnumValue(first)
le := len(tokens)
if le == 2 {
s = tokens[1]
} else if le > 2 {
idx := strings.Index(line, `"`)
s = line[idx:]
}
}
check(scanner.Err())
if s != "" {
return makeLeaf(nodeType, s)
}
left := loadAst()
right := loadAst()
return makeNode(nodeType, left, right)
}
func main() {
ast, err := os.Open("ast.txt")
check(err)
defer ast.Close()
scanner = bufio.NewScanner(ast)
codeGen(loadAst())
codeFinish()
listCode()
}
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. |
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
#include <stdlib.h>
#include "myutil.h"
|
Translate this program into C but keep the logic exactly as in Go. |
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
|
#include <stdlib.h>
#include "myutil.h"
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import "fmt"
type vList struct {
base *vSeg
offset int
}
type vSeg struct {
next *vSeg
ele []vEle
}
type vEle string
func (v vList) index(i int) (r vEle) {
if i >= 0 {
i += v.offset
for sg := v.base; sg != nil; sg = sg.next {
if i < len(sg.ele) {
return sg.ele[i]
}
i -= len(sg.ele)
}
}
panic("index out of range")
}
func (v vList) cons(a vEle) vList {
if v.base == nil {
return vList{base: &vSeg{ele: []vEle{a}}}
}
if v.offset == 0 {
l2 := len(v.base.ele) * 2
ele := make([]vEle, l2)
ele[l2-1] = a
return vList{&vSeg{v.base, ele}, l2 - 1}
}
v.offset--
v.base.ele[v.offset] = a
return v
}
func (v vList) cdr() vList {
if v.base == nil {
panic("cdr on empty vList")
}
v.offset++
if v.offset < len(v.base.ele) {
return v
}
return vList{v.base.next, 0}
}
func (v vList) length() int {
if v.base == nil {
return 0
}
return len(v.base.ele)*2 - v.offset - 1
}
func (v vList) String() string {
if v.base == nil {
return "[]"
}
r := fmt.Sprintf("[%v", v.base.ele[v.offset])
for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {
for _, e := range sl {
r = fmt.Sprintf("%s %v", r, e)
}
sg = sg.next
if sg == nil {
break
}
sl = sg.ele
}
return r + "]"
}
func (v vList) printStructure() {
fmt.Println("offset:", v.offset)
for sg := v.base; sg != nil; sg = sg.next {
fmt.Printf(" %q\n", sg.ele)
}
fmt.Println()
}
func main() {
var v vList
fmt.Println("zero value for type. empty vList:", v)
v.printStructure()
for a := '6'; a >= '1'; a-- {
v = v.cons(vEle(a))
}
fmt.Println("demonstrate cons. 6 elements added:", v)
v.printStructure()
v = v.cdr()
fmt.Println("demonstrate cdr. 1 element removed:", v)
v.printStructure()
fmt.Println("demonstrate length. length =", v.length())
fmt.Println()
fmt.Println("demonstrate element access. v[3] =", v.index(3))
fmt.Println()
v = v.cdr().cdr()
fmt.Println("show cdr releasing segment. 2 elements removed:", v)
v.printStructure()
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct sublist{
struct sublist* next;
int *buf;
} sublist_t;
sublist_t* sublist_new(size_t s)
{
sublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);
sub->buf = (int*)(sub + 1);
sub->next = 0;
return sub;
}
typedef struct vlist_t {
sublist_t* head;
size_t last_size, ofs;
} vlist_t, *vlist;
vlist v_new()
{
vlist v = malloc(sizeof(vlist_t));
v->head = sublist_new(1);
v->last_size = 1;
v->ofs = 0;
return v;
}
void v_del(vlist v)
{
sublist_t *s;
while (v->head) {
s = v->head->next;
free(v->head);
v->head = s;
}
free(v);
}
inline size_t v_size(vlist v)
{
return v->last_size * 2 - v->ofs - 2;
}
int* v_addr(vlist v, size_t idx)
{
sublist_t *s = v->head;
size_t top = v->last_size, i = idx + v->ofs;
if (i + 2 >= (top << 1)) {
fprintf(stderr, "!: idx %d out of range\n", (int)idx);
abort();
}
while (s && i >= top) {
s = s->next, i ^= top;
top >>= 1;
}
return s->buf + i;
}
inline int v_elem(vlist v, size_t idx)
{
return *v_addr(v, idx);
}
int* v_unshift(vlist v, int x)
{
sublist_t* s;
int *p;
if (!v->ofs) {
if (!(s = sublist_new(v->last_size << 1))) {
fprintf(stderr, "?: alloc failure\n");
return 0;
}
v->ofs = (v->last_size <<= 1);
s->next = v->head;
v->head = s;
}
*(p = v->head->buf + --v->ofs) = x;
return p;
}
int v_shift(vlist v)
{
sublist_t* s;
int x;
if (v->last_size == 1 && v->ofs == 1) {
fprintf(stderr, "!: empty list\n");
abort();
}
x = v->head->buf[v->ofs++];
if (v->ofs == v->last_size) {
v->ofs = 0;
if (v->last_size > 1) {
s = v->head, v->head = s->next;
v->last_size >>= 1;
free(s);
}
}
return x;
}
int main()
{
int i;
vlist v = v_new();
for (i = 0; i < 10; i++) v_unshift(v, i);
printf("size: %d\n", v_size(v));
for (i = 0; i < 10; i++) printf("v[%d] = %d\n", i, v_elem(v, i));
for (i = 0; i < 10; i++) printf("shift: %d\n", v_shift(v));
v_del(v);
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import "fmt"
type vList struct {
base *vSeg
offset int
}
type vSeg struct {
next *vSeg
ele []vEle
}
type vEle string
func (v vList) index(i int) (r vEle) {
if i >= 0 {
i += v.offset
for sg := v.base; sg != nil; sg = sg.next {
if i < len(sg.ele) {
return sg.ele[i]
}
i -= len(sg.ele)
}
}
panic("index out of range")
}
func (v vList) cons(a vEle) vList {
if v.base == nil {
return vList{base: &vSeg{ele: []vEle{a}}}
}
if v.offset == 0 {
l2 := len(v.base.ele) * 2
ele := make([]vEle, l2)
ele[l2-1] = a
return vList{&vSeg{v.base, ele}, l2 - 1}
}
v.offset--
v.base.ele[v.offset] = a
return v
}
func (v vList) cdr() vList {
if v.base == nil {
panic("cdr on empty vList")
}
v.offset++
if v.offset < len(v.base.ele) {
return v
}
return vList{v.base.next, 0}
}
func (v vList) length() int {
if v.base == nil {
return 0
}
return len(v.base.ele)*2 - v.offset - 1
}
func (v vList) String() string {
if v.base == nil {
return "[]"
}
r := fmt.Sprintf("[%v", v.base.ele[v.offset])
for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {
for _, e := range sl {
r = fmt.Sprintf("%s %v", r, e)
}
sg = sg.next
if sg == nil {
break
}
sl = sg.ele
}
return r + "]"
}
func (v vList) printStructure() {
fmt.Println("offset:", v.offset)
for sg := v.base; sg != nil; sg = sg.next {
fmt.Printf(" %q\n", sg.ele)
}
fmt.Println()
}
func main() {
var v vList
fmt.Println("zero value for type. empty vList:", v)
v.printStructure()
for a := '6'; a >= '1'; a-- {
v = v.cons(vEle(a))
}
fmt.Println("demonstrate cons. 6 elements added:", v)
v.printStructure()
v = v.cdr()
fmt.Println("demonstrate cdr. 1 element removed:", v)
v.printStructure()
fmt.Println("demonstrate length. length =", v.length())
fmt.Println()
fmt.Println("demonstrate element access. v[3] =", v.index(3))
fmt.Println()
v = v.cdr().cdr()
fmt.Println("show cdr releasing segment. 2 elements removed:", v)
v.printStructure()
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct sublist{
struct sublist* next;
int *buf;
} sublist_t;
sublist_t* sublist_new(size_t s)
{
sublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);
sub->buf = (int*)(sub + 1);
sub->next = 0;
return sub;
}
typedef struct vlist_t {
sublist_t* head;
size_t last_size, ofs;
} vlist_t, *vlist;
vlist v_new()
{
vlist v = malloc(sizeof(vlist_t));
v->head = sublist_new(1);
v->last_size = 1;
v->ofs = 0;
return v;
}
void v_del(vlist v)
{
sublist_t *s;
while (v->head) {
s = v->head->next;
free(v->head);
v->head = s;
}
free(v);
}
inline size_t v_size(vlist v)
{
return v->last_size * 2 - v->ofs - 2;
}
int* v_addr(vlist v, size_t idx)
{
sublist_t *s = v->head;
size_t top = v->last_size, i = idx + v->ofs;
if (i + 2 >= (top << 1)) {
fprintf(stderr, "!: idx %d out of range\n", (int)idx);
abort();
}
while (s && i >= top) {
s = s->next, i ^= top;
top >>= 1;
}
return s->buf + i;
}
inline int v_elem(vlist v, size_t idx)
{
return *v_addr(v, idx);
}
int* v_unshift(vlist v, int x)
{
sublist_t* s;
int *p;
if (!v->ofs) {
if (!(s = sublist_new(v->last_size << 1))) {
fprintf(stderr, "?: alloc failure\n");
return 0;
}
v->ofs = (v->last_size <<= 1);
s->next = v->head;
v->head = s;
}
*(p = v->head->buf + --v->ofs) = x;
return p;
}
int v_shift(vlist v)
{
sublist_t* s;
int x;
if (v->last_size == 1 && v->ofs == 1) {
fprintf(stderr, "!: empty list\n");
abort();
}
x = v->head->buf[v->ofs++];
if (v->ofs == v->last_size) {
v->ofs = 0;
if (v->last_size > 1) {
s = v->head, v->head = s->next;
v->last_size >>= 1;
free(s);
}
}
return x;
}
int main()
{
int i;
vlist v = v_new();
for (i = 0; i < 10; i++) v_unshift(v, i);
printf("size: %d\n", v_size(v));
for (i = 0; i < 10; i++) printf("v[%d] = %d\n", i, v_elem(v, i));
for (i = 0; i < 10; i++) printf("shift: %d\n", v_shift(v));
v_del(v);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import "fmt"
type vList struct {
base *vSeg
offset int
}
type vSeg struct {
next *vSeg
ele []vEle
}
type vEle string
func (v vList) index(i int) (r vEle) {
if i >= 0 {
i += v.offset
for sg := v.base; sg != nil; sg = sg.next {
if i < len(sg.ele) {
return sg.ele[i]
}
i -= len(sg.ele)
}
}
panic("index out of range")
}
func (v vList) cons(a vEle) vList {
if v.base == nil {
return vList{base: &vSeg{ele: []vEle{a}}}
}
if v.offset == 0 {
l2 := len(v.base.ele) * 2
ele := make([]vEle, l2)
ele[l2-1] = a
return vList{&vSeg{v.base, ele}, l2 - 1}
}
v.offset--
v.base.ele[v.offset] = a
return v
}
func (v vList) cdr() vList {
if v.base == nil {
panic("cdr on empty vList")
}
v.offset++
if v.offset < len(v.base.ele) {
return v
}
return vList{v.base.next, 0}
}
func (v vList) length() int {
if v.base == nil {
return 0
}
return len(v.base.ele)*2 - v.offset - 1
}
func (v vList) String() string {
if v.base == nil {
return "[]"
}
r := fmt.Sprintf("[%v", v.base.ele[v.offset])
for sg, sl := v.base, v.base.ele[v.offset+1:]; ; {
for _, e := range sl {
r = fmt.Sprintf("%s %v", r, e)
}
sg = sg.next
if sg == nil {
break
}
sl = sg.ele
}
return r + "]"
}
func (v vList) printStructure() {
fmt.Println("offset:", v.offset)
for sg := v.base; sg != nil; sg = sg.next {
fmt.Printf(" %q\n", sg.ele)
}
fmt.Println()
}
func main() {
var v vList
fmt.Println("zero value for type. empty vList:", v)
v.printStructure()
for a := '6'; a >= '1'; a-- {
v = v.cons(vEle(a))
}
fmt.Println("demonstrate cons. 6 elements added:", v)
v.printStructure()
v = v.cdr()
fmt.Println("demonstrate cdr. 1 element removed:", v)
v.printStructure()
fmt.Println("demonstrate length. length =", v.length())
fmt.Println()
fmt.Println("demonstrate element access. v[3] =", v.index(3))
fmt.Println()
v = v.cdr().cdr()
fmt.Println("show cdr releasing segment. 2 elements removed:", v)
v.printStructure()
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct sublist{
struct sublist* next;
int *buf;
} sublist_t;
sublist_t* sublist_new(size_t s)
{
sublist_t* sub = malloc(sizeof(sublist_t) + sizeof(int) * s);
sub->buf = (int*)(sub + 1);
sub->next = 0;
return sub;
}
typedef struct vlist_t {
sublist_t* head;
size_t last_size, ofs;
} vlist_t, *vlist;
vlist v_new()
{
vlist v = malloc(sizeof(vlist_t));
v->head = sublist_new(1);
v->last_size = 1;
v->ofs = 0;
return v;
}
void v_del(vlist v)
{
sublist_t *s;
while (v->head) {
s = v->head->next;
free(v->head);
v->head = s;
}
free(v);
}
inline size_t v_size(vlist v)
{
return v->last_size * 2 - v->ofs - 2;
}
int* v_addr(vlist v, size_t idx)
{
sublist_t *s = v->head;
size_t top = v->last_size, i = idx + v->ofs;
if (i + 2 >= (top << 1)) {
fprintf(stderr, "!: idx %d out of range\n", (int)idx);
abort();
}
while (s && i >= top) {
s = s->next, i ^= top;
top >>= 1;
}
return s->buf + i;
}
inline int v_elem(vlist v, size_t idx)
{
return *v_addr(v, idx);
}
int* v_unshift(vlist v, int x)
{
sublist_t* s;
int *p;
if (!v->ofs) {
if (!(s = sublist_new(v->last_size << 1))) {
fprintf(stderr, "?: alloc failure\n");
return 0;
}
v->ofs = (v->last_size <<= 1);
s->next = v->head;
v->head = s;
}
*(p = v->head->buf + --v->ofs) = x;
return p;
}
int v_shift(vlist v)
{
sublist_t* s;
int x;
if (v->last_size == 1 && v->ofs == 1) {
fprintf(stderr, "!: empty list\n");
abort();
}
x = v->head->buf[v->ofs++];
if (v->ofs == v->last_size) {
v->ofs = 0;
if (v->last_size > 1) {
s = v->head, v->head = s->next;
v->last_size >>= 1;
free(s);
}
}
return x;
}
int main()
{
int i;
vlist v = v_new();
for (i = 0; i < 10; i++) v_unshift(v, i);
printf("size: %d\n", v_size(v));
for (i = 0; i < 10; i++) printf("v[%d] = %d\n", i, v_elem(v, i));
for (i = 0; i < 10; i++) printf("shift: %d\n", v_shift(v));
v_del(v);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"sternbrocot"
)
func main() {
g := sb.Generator()
fmt.Println("First 15:")
for i := 1; i <= 15; i++ {
fmt.Printf("%2d: %d\n", i, g())
}
s := sb.New()
fmt.Println("First 15:", s.FirstN(15))
for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {
fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x))
}
fmt.Println("1-based indexes: gcd")
for n, f := range s.FirstN(1000)[:999] {
g := gcd(f, (*s)[n+1])
fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g)
if g != 1 {
panic("oh no!")
return
}
}
}
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
| k=2; i=1; j=2;
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
)
type any = interface{}
func uselessFunc(uselessParam any) {
if true {
} else {
fmt.Println("Never called")
}
for range []any{} {
fmt.Println("Never called")
}
for false {
fmt.Println("Never called")
}
fmt.Print("")
return
}
type NotCompletelyUseless struct {
}
func main() {
uselessFunc(0)
set := make(map[int]NotCompletelyUseless)
set[0] = NotCompletelyUseless{}
set[0] = NotCompletelyUseless{}
fmt.Println(set)
}
| #include <stdio.h>
#include <stdbool.h>
void uselessFunc(int uselessParam) {
auto int i;
if (true) {
} else {
printf("Never called\n");
}
for (i = 0; i < 0; ++i) {
printf("Never called\n");
}
while (false) {
printf("Never called\n");
}
printf("");
return;
}
struct UselessStruct {
};
int main() {
uselessFunc(0);
printf("Working OK.\n");
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"math"
)
type unc struct {
n float64
s float64
}
func newUnc(n, s float64) *unc {
return &unc{n, s * s}
}
func (z *unc) errorTerm() float64 {
return math.Sqrt(z.s)
}
func (z *unc) addC(a *unc, c float64) *unc {
*z = *a
z.n += c
return z
}
func (z *unc) subC(a *unc, c float64) *unc {
*z = *a
z.n -= c
return z
}
func (z *unc) addU(a, b *unc) *unc {
z.n = a.n + b.n
z.s = a.s + b.s
return z
}
func (z *unc) subU(a, b *unc) *unc {
z.n = a.n - b.n
z.s = a.s + b.s
return z
}
func (z *unc) mulC(a *unc, c float64) *unc {
z.n = a.n * c
z.s = a.s * c * c
return z
}
func (z *unc) divC(a *unc, c float64) *unc {
z.n = a.n / c
z.s = a.s / (c * c)
return z
}
func (z *unc) mulU(a, b *unc) *unc {
prod := a.n * b.n
z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
func (z *unc) divU(a, b *unc) *unc {
quot := a.n / b.n
z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
func (z *unc) expC(a *unc, c float64) *unc {
f := math.Pow(a.n, c)
g := f * c / a.n
z.n = f
z.s = a.s * g * g
return z
}
func main() {
x1 := newUnc(100, 1.1)
x2 := newUnc(200, 2.2)
y1 := newUnc(50, 1.2)
y2 := newUnc(100, 2.3)
var d, d2 unc
d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)
fmt.Println("d: ", d.n)
fmt.Println("error:", d.errorTerm())
}
| #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef struct{
double value;
double delta;
}imprecise;
#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value + b.value;
ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));
return ret;
}
imprecise imprecise_mul(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value * b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));
return ret;
}
imprecise imprecise_div(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value / b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);
return ret;
}
imprecise imprecise_pow(imprecise a, double c)
{
imprecise ret;
ret.value = pow(a.value, c);
ret.delta = fabs(ret.value * c * a.delta / a.value);
return ret;
}
char* printImprecise(imprecise val)
{
char principal[30],error[30],*string,sign[2];
sign[0] = 241;
sign[1] = 00;
sprintf(principal,"%f",val.value);
sprintf(error,"%f",val.delta);
string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));
strcpy(string,principal);
strcat(string,sign);
strcat(string,error);
return string;
}
int main(void) {
imprecise x1 = {100, 1.1};
imprecise y1 = {50, 1.2};
imprecise x2 = {-200, 2.2};
imprecise y2 = {-100, 2.3};
imprecise d;
d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);
printf("Distance, d, between the following points :");
printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1));
printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2));
printf("\nis d = %s", printImprecise(d));
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"errors"
"fmt"
"unicode"
)
var code = []byte("01230127022455012623017202")
func soundex(s string) (string, error) {
var sx [4]byte
var sxi int
var cx, lastCode byte
for i, c := range s {
switch {
case !unicode.IsLetter(c):
if c < ' ' || c == 127 {
return "", errors.New("ASCII control characters disallowed")
}
if i == 0 {
return "", errors.New("initial character must be a letter")
}
lastCode = '0'
continue
case c >= 'A' && c <= 'Z':
cx = byte(c - 'A')
case c >= 'a' && c <= 'z':
cx = byte(c - 'a')
default:
return "", errors.New("non-ASCII letters unsupported")
}
if i == 0 {
sx[0] = cx + 'A'
sxi = 1
continue
}
switch x := code[cx]; x {
case '7', lastCode:
case '0':
lastCode = '0'
default:
sx[sxi] = x
if sxi == 3 {
return string(sx[:]), nil
}
sxi++
lastCode = x
}
}
if sxi == 0 {
return "", errors.New("no letters present")
}
for ; sxi < 4; sxi++ {
sx[sxi] = '0'
}
return string(sx[:]), nil
}
func main() {
for _, s := range []string{
"Robert",
"Rupert",
"Rubin",
"ashcroft",
"ashcraft",
"moses",
"O'Mally",
"d jay",
"R2-D2",
"12p2",
"naïve",
"",
"bump\t",
} {
if x, err := soundex(s); err == nil {
fmt.Println("soundex", s, "=", x)
} else {
fmt.Printf("\"%s\" fail. %s\n", s, err)
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
static char code[128] = { 0 };
void add_code(const char *s, int c)
{
while (*s) {
code[(int)*s] = code[0x20 ^ (int)*s] = c;
s++;
}
}
void init()
{
static const char *cls[] =
{ "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0};
int i;
for (i = 0; cls[i]; i++)
add_code(cls[i], i - 1);
}
const char* soundex(const char *s)
{
static char out[5];
int c, prev, i;
out[0] = out[4] = 0;
if (!s || !*s) return out;
out[0] = *s++;
prev = code[(int)out[0]];
for (i = 1; *s && i < 4; s++) {
if ((c = code[(int)*s]) == prev) continue;
if (c == -1) prev = 0;
else if (c > 0) {
out[i++] = c + '0';
prev = c;
}
}
while (i < 4) out[i++] = '0';
return out;
}
int main()
{
int i;
const char *sdx, *names[][2] = {
{"Soundex", "S532"},
{"Example", "E251"},
{"Sownteks", "S532"},
{"Ekzampul", "E251"},
{"Euler", "E460"},
{"Gauss", "G200"},
{"Hilbert", "H416"},
{"Knuth", "K530"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"Ellery", "E460"},
{"Ghosh", "G200"},
{"Heilbronn", "H416"},
{"Kant", "K530"},
{"Ladd", "L300"},
{"Lissajous", "L222"},
{"Wheaton", "W350"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"O'Hara", "O600"},
{"Washington", "W252"},
{"Lee", "L000"},
{"Gutierrez", "G362"},
{"Pfister", "P236"},
{"Jackson", "J250"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Ashcraft", "A261"},
{0, 0}
};
init();
puts(" Test name Code Got\n----------------------");
for (i = 0; names[i][0]; i++) {
sdx = soundex(names[i][0]);
printf("%11s %s %s ", names[i][0], names[i][1], sdx);
printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok");
}
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"fmt"
"log"
"os"
"strconv"
)
type tree uint64
var (
list []tree
offset = [32]uint{1: 1}
)
func add(t tree) {
list = append(list, 1|t<<1)
}
func show(t tree, l uint) {
for ; l > 0; t >>= 1 {
l--
var paren byte
if (t & 1) != 0 {
paren = '('
} else {
paren = ')'
}
fmt.Printf("%c", paren)
}
}
func listTrees(n uint) {
for i := offset[n]; i < offset[n+1]; i++ {
show(list[i], n*2)
fmt.Println()
}
}
func assemble(n uint, t tree, sl, pos, rem uint) {
if rem == 0 {
add(t)
return
}
if sl > rem {
sl = rem
pos = offset[sl]
} else if pos >= offset[sl+1] {
sl--
if sl == 0 {
return
}
pos = offset[sl]
}
assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)
assemble(n, t, sl, pos+1, rem)
}
func mktrees(n uint) {
if offset[n+1] > 0 {
return
}
if n > 0 {
mktrees(n - 1)
}
assemble(n, 0, n-1, offset[n-1], n-1)
offset[n+1] = uint(len(list))
}
func main() {
if len(os.Args) != 2 {
log.Fatal("There must be exactly 1 command line argument")
}
n, err := strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal("Argument is not a valid number")
}
if n <= 0 || n > 19 {
n = 5
}
add(0)
mktrees(uint(n))
fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n])
listTrees(uint(n))
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))
tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};
void append(tree t)
{
if (len == cap) {
cap = cap ? cap*2 : 2;
list = realloc(list, cap*sizeof(tree));
}
list[len++] = 1 | t<<1;
}
void show(tree t, uint len)
{
for (; len--; t >>= 1)
putchar(t&1 ? '(' : ')');
}
void listtrees(uint n)
{
uint i;
for (i = offset[n]; i < offset[n+1]; i++) {
show(list[i], n*2);
putchar('\n');
}
}
void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
if (!rem) {
append(t);
return;
}
if (sl > rem)
pos = offset[sl = rem];
else if (pos >= offset[sl + 1]) {
if (!--sl) return;
pos = offset[sl];
}
assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
assemble(n, t, sl, pos + 1, rem);
}
void mktrees(uint n)
{
if (offset[n + 1]) return;
if (n) mktrees(n - 1);
assemble(n, 0, n-1, offset[n-1], n-1);
offset[n+1] = len;
}
int main(int c, char**v)
{
int n;
if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;
append(0);
mktrees((uint)n);
fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
listtrees((uint)n);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. |
package example
var (
X, Y, Z int
)
func XP() {
}
func nonXP() {}
var MEMEME int
|
int add(int a, int b) {
return a + b;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"log"
)
type StockTrans struct {
Id int
Date string
Trans string
Symbol string
Quantity int
Price float32
Settled bool
}
func (st *StockTrans) save(db *bolt.DB, bucket string) error {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
id, _ := b.NextSequence()
st.Id = int(id)
encoded, err := json.Marshal(st)
if err != nil {
return err
}
return b.Put(itob(st.Id), encoded)
})
return err
}
func itob(i int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(i))
return b
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
db, err := bolt.Open("store.db", 0600, nil)
check(err)
defer db.Close()
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("stocks"))
return err
})
check(err)
transactions := []*StockTrans{
{0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true},
{0, "2006-03-28", "BUY", "IBM", 1000, 45, true},
{0, "2006-04-06", "SELL", "IBM", 500, 53, true},
{0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false},
}
for _, trans := range transactions {
err := trans.save(db, "stocks")
check(err)
}
fmt.Println("Id Date Trans Sym Qty Price Settled")
fmt.Println("------------------------------------------------")
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("stocks"))
b.ForEach(func(k, v []byte) error {
st := new(StockTrans)
err := json.Unmarshal(v, st)
check(err)
fmt.Printf("%d %s %-4s %-5s %4d %2.2f %t\n",
st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)
return nil
})
return nil
})
}
| #include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
sqlite3 *db = NULL;
char *errmsg;
const char *code =
"CREATE TABLE employee (\n"
" empID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" firstName TEXT NOT NULL,\n"
" lastName TEXT NOT NULL,\n"
" AGE INTEGER NOT NULL,\n"
" DOB DATE NOT NULL)\n" ;
if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
sqlite3_exec(db, code, NULL, NULL, &errmsg);
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"log"
)
type StockTrans struct {
Id int
Date string
Trans string
Symbol string
Quantity int
Price float32
Settled bool
}
func (st *StockTrans) save(db *bolt.DB, bucket string) error {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
id, _ := b.NextSequence()
st.Id = int(id)
encoded, err := json.Marshal(st)
if err != nil {
return err
}
return b.Put(itob(st.Id), encoded)
})
return err
}
func itob(i int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(i))
return b
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
db, err := bolt.Open("store.db", 0600, nil)
check(err)
defer db.Close()
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("stocks"))
return err
})
check(err)
transactions := []*StockTrans{
{0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true},
{0, "2006-03-28", "BUY", "IBM", 1000, 45, true},
{0, "2006-04-06", "SELL", "IBM", 500, 53, true},
{0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false},
}
for _, trans := range transactions {
err := trans.save(db, "stocks")
check(err)
}
fmt.Println("Id Date Trans Sym Qty Price Settled")
fmt.Println("------------------------------------------------")
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("stocks"))
b.ForEach(func(k, v []byte) error {
st := new(StockTrans)
err := json.Unmarshal(v, st)
check(err)
fmt.Printf("%d %s %-4s %-5s %4d %2.2f %t\n",
st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)
return nil
})
return nil
})
}
| #include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
sqlite3 *db = NULL;
char *errmsg;
const char *code =
"CREATE TABLE employee (\n"
" empID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" firstName TEXT NOT NULL,\n"
" lastName TEXT NOT NULL,\n"
" AGE INTEGER NOT NULL,\n"
" DOB DATE NOT NULL)\n" ;
if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
sqlite3_exec(db, code, NULL, NULL, &errmsg);
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"math"
)
type circle struct {
x, y, r float64
}
func main() {
c1 := circle{0, 0, 1}
c2 := circle{4, 0, 1}
c3 := circle{2, 4, 2}
fmt.Println(ap(c1, c2, c3, true))
fmt.Println(ap(c1, c2, c3, false))
}
func ap(c1, c2, c3 circle, s bool) circle {
x1sq := c1.x * c1.x
y1sq := c1.y * c1.y
r1sq := c1.r * c1.r
x2sq := c2.x * c2.x
y2sq := c2.y * c2.y
r2sq := c2.r * c2.r
x3sq := c3.x * c3.x
y3sq := c3.y * c3.y
r3sq := c3.r * c3.r
v11 := 2 * (c2.x - c1.x)
v12 := 2 * (c2.y - c1.y)
v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq
v14 := 2 * (c2.r - c1.r)
v21 := 2 * (c3.x - c2.x)
v22 := 2 * (c3.y - c2.y)
v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq
v24 := 2 * (c3.r - c2.r)
if s {
v14 = -v14
v24 = -v24
}
w12 := v12 / v11
w13 := v13 / v11
w14 := v14 / v11
w22 := v22/v21 - w12
w23 := v23/v21 - w13
w24 := v24/v21 - w14
p := -w23 / w22
q := w24 / w22
m := -w12*p - w13
n := w14 - w12*q
a := n*n + q*q - 1
b := m*n - n*c1.x + p*q - q*c1.y
if s {
b -= c1.r
} else {
b += c1.r
}
b *= 2
c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq
d := b*b - 4*a*c
rs := (-b - math.Sqrt(d)) / (2 * a)
return circle{m + n*rs, p + q*rs, rs}
}
| #include <stdio.h>
#include <tgmath.h>
#define VERBOSE 0
#define for3 for(int i = 0; i < 3; i++)
typedef complex double vec;
typedef struct { vec c; double r; } circ;
#define re(x) creal(x)
#define im(x) cimag(x)
#define cp(x) re(x), im(x)
#define CPLX "(%6.3f,%6.3f)"
#define CPLX3 CPLX" "CPLX" "CPLX
double cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }
double abs2(vec a) { return a * conj(a); }
int apollonius_in(circ aa[], int ss[], int flip, int divert)
{
vec n[3], x[3], t[3], a, b, center;
int s[3], iter = 0, res = 0;
double diff = 1, diff_old = -1, axb, d, r;
for3 {
s[i] = ss[i] ? 1 : -1;
x[i] = aa[i].c;
}
while (diff > 1e-20) {
a = x[0] - x[2], b = x[1] - x[2];
diff = 0;
axb = -cross(a, b);
d = sqrt(abs2(a) * abs2(b) * abs2(a - b));
if (VERBOSE) {
const char *z = 1 + "-0+";
printf("%c%c%c|%c%c|",
z[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);
printf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));
}
r = fabs(d / (2 * axb));
center = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];
if (!axb && flip != -1 && !divert) {
if (!d) {
printf("Given conditions confused me.\n");
return 0;
}
if (VERBOSE) puts("\n[divert]");
divert = 1;
res = apollonius_in(aa, ss, -1, 1);
}
for3 n[i] = axb ? aa[i].c - center : a * I * flip;
for3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];
for3 diff += abs2(t[i] - x[i]), x[i] = t[i];
if (VERBOSE) printf(" %g\n", diff);
if (diff >= diff_old && diff_old >= 0)
if (iter++ > 20) return res;
diff_old = diff;
}
printf("found: ");
if (axb) printf("circle "CPLX", r = %f\n", cp(center), r);
else printf("line "CPLX3"\n", cp(x[0]), cp(x[1]), cp(x[2]));
return res + 1;
}
int apollonius(circ aa[])
{
int s[3], i, sum = 0;
for (i = 0; i < 8; i++) {
s[0] = i & 1, s[1] = i & 2, s[2] = i & 4;
if (s[0] && !aa[0].r) continue;
if (s[1] && !aa[1].r) continue;
if (s[2] && !aa[2].r) continue;
sum += apollonius_in(aa, s, 1, 0);
}
return sum;
}
int main()
{
circ a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};
circ b[3] = {{-3, 2}, {0, 1}, {3, 2}};
circ c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};
puts("set 1"); apollonius(a);
puts("set 2"); apollonius(b);
puts("set 3"); apollonius(c);
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
gc "github.com/rthornton128/goncurses"
"log"
"math/rand"
"time"
)
const (
lineLen = 5
disjoint = 0
)
var (
board [][]int
width int
height int
)
const (
blank = 0
occupied = 1 << (iota - 1)
dirNS
dirEW
dirNESW
dirNWSE
newlyAdded
current
)
var ofs = [4][3]int{
{0, 1, dirNS},
{1, 0, dirEW},
{1, -1, dirNESW},
{1, 1, dirNWSE},
}
type move struct{ m, s, seq, x, y int }
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func allocBoard(w, h int) [][]int {
buf := make([][]int, h)
for i := 0; i < h; i++ {
buf[i] = make([]int, w)
}
return buf
}
func boardSet(v, x0, y0, x1, y1 int) {
for i := y0; i <= y1; i++ {
for j := x0; j <= x1; j++ {
board[i][j] = v
}
}
}
func initBoard() {
height = 3 * (lineLen - 1)
width = height
board = allocBoard(width, height)
boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)
boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)
boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)
boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)
}
func expandBoard(dw, dh int) {
dw2, dh2 := 1, 1
if dw == 0 {
dw2 = 0
}
if dh == 0 {
dh2 = 0
}
nw, nh := width+dw2, height+dh2
nbuf := allocBoard(nw, nh)
dw, dh = -btoi(dw < 0), -btoi(dh < 0)
for i := 0; i < nh; i++ {
if i+dh < 0 || i+dh >= height {
continue
}
for j := 0; j < nw; j++ {
if j+dw < 0 || j+dw >= width {
continue
}
nbuf[i][j] = board[i+dh][j+dw]
}
}
board = nbuf
width, height = nw, nh
}
func showBoard(scr *gc.Window) {
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
var temp string
switch {
case (board[i][j] & current) != 0:
temp = "X "
case (board[i][j] & newlyAdded) != 0:
temp = "0 "
case (board[i][j] & occupied) != 0:
temp = "+ "
default:
temp = " "
}
scr.MovePrintf(i+1, j*2, temp)
}
}
scr.Refresh()
}
func testPosition(y, x int, rec *move) {
if (board[y][x] & occupied) != 0 {
return
}
for m := 0; m < 4; m++ {
dx := ofs[m][0]
dy := ofs[m][1]
dir := ofs[m][2]
var k int
for s := 1 - lineLen; s <= 0; s++ {
for k = 0; k < lineLen; k++ {
if s+k == 0 {
continue
}
xx := x + dx*(s+k)
yy := y + dy*(s+k)
if xx < 0 || xx >= width || yy < 0 || yy >= height {
break
}
if (board[yy][xx] & occupied) == 0 {
break
}
if (board[yy][xx] & dir) != 0 {
break
}
}
if k != lineLen {
continue
}
rec.seq++
if rand.Intn(rec.seq) == 0 {
rec.m, rec.s, rec.x, rec.y = m, s, x, y
}
}
}
}
func addPiece(rec *move) {
dx := ofs[rec.m][0]
dy := ofs[rec.m][1]
dir := ofs[rec.m][2]
board[rec.y][rec.x] |= current | occupied
for k := 0; k < lineLen; k++ {
xx := rec.x + dx*(k+rec.s)
yy := rec.y + dy*(k+rec.s)
board[yy][xx] |= newlyAdded
if k >= disjoint || k < lineLen-disjoint {
board[yy][xx] |= dir
}
}
}
func nextMove() bool {
var rec move
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
board[i][j] &^= newlyAdded | current
}
}
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
testPosition(i, j, &rec)
}
}
if rec.seq == 0 {
return false
}
addPiece(&rec)
if rec.x == width-1 {
rec.x = 1
} else if rec.x != 0 {
rec.x = 0
} else {
rec.x = -1
}
if rec.y == height-1 {
rec.y = 1
} else if rec.y != 0 {
rec.y = 0
} else {
rec.y = -1
}
if rec.x != 0 || rec.y != 0 {
expandBoard(rec.x, rec.y)
}
return true
}
func main() {
rand.Seed(time.Now().UnixNano())
initBoard()
scr, err := gc.Init()
if err != nil {
log.Fatal("init", err)
}
defer gc.End()
gc.Echo(false)
gc.CBreak(true)
ch := gc.Key(0)
move := 0
waitKey := true
for {
scr.MovePrintf(0, 0, "Move %d", move)
move++
showBoard(scr)
if !nextMove() {
nextMove()
showBoard(scr)
break
}
if !waitKey {
time.Sleep(100000 * time.Microsecond)
}
if ch = scr.GetChar(); ch == ' ' {
waitKey = !waitKey
if waitKey {
scr.Timeout(-1)
} else {
scr.Timeout(0)
}
}
if ch == 'q' {
break
}
}
scr.Timeout(-1)
gc.CBreak(false)
gc.Echo(true)
}
| #include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int line_len = 5;
int disjoint = 0;
int **board = 0, width, height;
#define for_i for(i = 0; i < height; i++)
#define for_j for(j = 0; j < width; j++)
enum {
s_blank = 0,
s_occupied = 1 << 0,
s_dir_ns = 1 << 1,
s_dir_ew = 1 << 2,
s_dir_ne_sw = 1 << 3,
s_dir_nw_se = 1 << 4,
s_newly_added = 1 << 5,
s_current = 1 << 6,
};
int irand(int n)
{
int r, rand_max = RAND_MAX - (RAND_MAX % n);
while ((r = rand()) >= rand_max);
return r / (rand_max / n);
}
int** alloc_board(int w, int h)
{
int i;
int **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);
buf[0] = (int*)(buf + h);
for (i = 1; i < h; i++)
buf[i] = buf[i - 1] + w;
return buf;
}
void expand_board(int dw, int dh)
{
int i, j;
int nw = width + !!dw, nh = height + !!dh;
int **nbuf = alloc_board(nw, nh);
dw = -(dw < 0), dh = -(dh < 0);
for (i = 0; i < nh; i++) {
if (i + dh < 0 || i + dh >= height) continue;
for (j = 0; j < nw; j++) {
if (j + dw < 0 || j + dw >= width) continue;
nbuf[i][j] = board[i + dh][j + dw];
}
}
free(board);
board = nbuf;
width = nw;
height = nh;
}
void array_set(int **buf, int v, int x0, int y0, int x1, int y1)
{
int i, j;
for (i = y0; i <= y1; i++)
for (j = x0; j <= x1; j++)
buf[i][j] = v;
}
void show_board()
{
int i, j;
for_i for_j mvprintw(i + 1, j * 2,
(board[i][j] & s_current) ? "X "
: (board[i][j] & s_newly_added) ? "O "
: (board[i][j] & s_occupied) ? "+ " : " ");
refresh();
}
void init_board()
{
width = height = 3 * (line_len - 1);
board = alloc_board(width, height);
array_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);
array_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);
array_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);
array_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);
}
int ofs[4][3] = {
{0, 1, s_dir_ns},
{1, 0, s_dir_ew},
{1, -1, s_dir_ne_sw},
{1, 1, s_dir_nw_se}
};
typedef struct { int m, s, seq, x, y; } move_t;
void test_postion(int y, int x, move_t * rec)
{
int m, k, s, dx, dy, xx, yy, dir;
if (board[y][x] & s_occupied) return;
for (m = 0; m < 4; m++) {
dx = ofs[m][0];
dy = ofs[m][1];
dir = ofs[m][2];
for (s = 1 - line_len; s <= 0; s++) {
for (k = 0; k < line_len; k++) {
if (s + k == 0) continue;
xx = x + dx * (s + k);
yy = y + dy * (s + k);
if (xx < 0 || xx >= width || yy < 0 || yy >= height)
break;
if (!(board[yy][xx] & s_occupied)) break;
if ((board[yy][xx] & dir)) break;
}
if (k != line_len) continue;
if (! irand(++rec->seq))
rec->m = m, rec->s = s, rec->x = x, rec->y = y;
}
}
}
void add_piece(move_t *rec) {
int dx = ofs[rec->m][0];
int dy = ofs[rec->m][1];
int dir= ofs[rec->m][2];
int xx, yy, k;
board[rec->y][rec->x] |= (s_current | s_occupied);
for (k = 0; k < line_len; k++) {
xx = rec->x + dx * (k + rec->s);
yy = rec->y + dy * (k + rec->s);
board[yy][xx] |= s_newly_added;
if (k >= disjoint || k < line_len - disjoint)
board[yy][xx] |= dir;
}
}
int next_move()
{
int i, j;
move_t rec;
rec.seq = 0;
for_i for_j board[i][j] &= ~(s_newly_added | s_current);
for_i for_j test_postion(i, j, &rec);
if (!rec.seq) return 0;
add_piece(&rec);
rec.x = (rec.x == width - 1) ? 1 : rec.x ? 0 : -1;
rec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;
if (rec.x || rec.y) expand_board(rec.x, rec.y);
return 1;
}
int main()
{
int ch = 0;
int move = 0;
int wait_key = 1;
init_board();
srand(time(0));
initscr();
noecho();
cbreak();
do {
mvprintw(0, 0, "Move %d", move++);
show_board();
if (!next_move()) {
next_move();
show_board();
break;
}
if (!wait_key) usleep(100000);
if ((ch = getch()) == ' ') {
wait_key = !wait_key;
if (wait_key) timeout(-1);
else timeout(0);
}
} while (ch != 'q');
timeout(-1);
nocbreak();
echo();
endwin();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
gc "github.com/rthornton128/goncurses"
"log"
"math/rand"
"time"
)
const (
lineLen = 5
disjoint = 0
)
var (
board [][]int
width int
height int
)
const (
blank = 0
occupied = 1 << (iota - 1)
dirNS
dirEW
dirNESW
dirNWSE
newlyAdded
current
)
var ofs = [4][3]int{
{0, 1, dirNS},
{1, 0, dirEW},
{1, -1, dirNESW},
{1, 1, dirNWSE},
}
type move struct{ m, s, seq, x, y int }
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func allocBoard(w, h int) [][]int {
buf := make([][]int, h)
for i := 0; i < h; i++ {
buf[i] = make([]int, w)
}
return buf
}
func boardSet(v, x0, y0, x1, y1 int) {
for i := y0; i <= y1; i++ {
for j := x0; j <= x1; j++ {
board[i][j] = v
}
}
}
func initBoard() {
height = 3 * (lineLen - 1)
width = height
board = allocBoard(width, height)
boardSet(occupied, lineLen-1, 1, 2*lineLen-3, height-2)
boardSet(occupied, 1, lineLen-1, width-2, 2*lineLen-3)
boardSet(blank, lineLen, 2, 2*lineLen-4, height-3)
boardSet(blank, 2, lineLen, width-3, 2*lineLen-4)
}
func expandBoard(dw, dh int) {
dw2, dh2 := 1, 1
if dw == 0 {
dw2 = 0
}
if dh == 0 {
dh2 = 0
}
nw, nh := width+dw2, height+dh2
nbuf := allocBoard(nw, nh)
dw, dh = -btoi(dw < 0), -btoi(dh < 0)
for i := 0; i < nh; i++ {
if i+dh < 0 || i+dh >= height {
continue
}
for j := 0; j < nw; j++ {
if j+dw < 0 || j+dw >= width {
continue
}
nbuf[i][j] = board[i+dh][j+dw]
}
}
board = nbuf
width, height = nw, nh
}
func showBoard(scr *gc.Window) {
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
var temp string
switch {
case (board[i][j] & current) != 0:
temp = "X "
case (board[i][j] & newlyAdded) != 0:
temp = "0 "
case (board[i][j] & occupied) != 0:
temp = "+ "
default:
temp = " "
}
scr.MovePrintf(i+1, j*2, temp)
}
}
scr.Refresh()
}
func testPosition(y, x int, rec *move) {
if (board[y][x] & occupied) != 0 {
return
}
for m := 0; m < 4; m++ {
dx := ofs[m][0]
dy := ofs[m][1]
dir := ofs[m][2]
var k int
for s := 1 - lineLen; s <= 0; s++ {
for k = 0; k < lineLen; k++ {
if s+k == 0 {
continue
}
xx := x + dx*(s+k)
yy := y + dy*(s+k)
if xx < 0 || xx >= width || yy < 0 || yy >= height {
break
}
if (board[yy][xx] & occupied) == 0 {
break
}
if (board[yy][xx] & dir) != 0 {
break
}
}
if k != lineLen {
continue
}
rec.seq++
if rand.Intn(rec.seq) == 0 {
rec.m, rec.s, rec.x, rec.y = m, s, x, y
}
}
}
}
func addPiece(rec *move) {
dx := ofs[rec.m][0]
dy := ofs[rec.m][1]
dir := ofs[rec.m][2]
board[rec.y][rec.x] |= current | occupied
for k := 0; k < lineLen; k++ {
xx := rec.x + dx*(k+rec.s)
yy := rec.y + dy*(k+rec.s)
board[yy][xx] |= newlyAdded
if k >= disjoint || k < lineLen-disjoint {
board[yy][xx] |= dir
}
}
}
func nextMove() bool {
var rec move
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
board[i][j] &^= newlyAdded | current
}
}
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
testPosition(i, j, &rec)
}
}
if rec.seq == 0 {
return false
}
addPiece(&rec)
if rec.x == width-1 {
rec.x = 1
} else if rec.x != 0 {
rec.x = 0
} else {
rec.x = -1
}
if rec.y == height-1 {
rec.y = 1
} else if rec.y != 0 {
rec.y = 0
} else {
rec.y = -1
}
if rec.x != 0 || rec.y != 0 {
expandBoard(rec.x, rec.y)
}
return true
}
func main() {
rand.Seed(time.Now().UnixNano())
initBoard()
scr, err := gc.Init()
if err != nil {
log.Fatal("init", err)
}
defer gc.End()
gc.Echo(false)
gc.CBreak(true)
ch := gc.Key(0)
move := 0
waitKey := true
for {
scr.MovePrintf(0, 0, "Move %d", move)
move++
showBoard(scr)
if !nextMove() {
nextMove()
showBoard(scr)
break
}
if !waitKey {
time.Sleep(100000 * time.Microsecond)
}
if ch = scr.GetChar(); ch == ' ' {
waitKey = !waitKey
if waitKey {
scr.Timeout(-1)
} else {
scr.Timeout(0)
}
}
if ch == 'q' {
break
}
}
scr.Timeout(-1)
gc.CBreak(false)
gc.Echo(true)
}
| #include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int line_len = 5;
int disjoint = 0;
int **board = 0, width, height;
#define for_i for(i = 0; i < height; i++)
#define for_j for(j = 0; j < width; j++)
enum {
s_blank = 0,
s_occupied = 1 << 0,
s_dir_ns = 1 << 1,
s_dir_ew = 1 << 2,
s_dir_ne_sw = 1 << 3,
s_dir_nw_se = 1 << 4,
s_newly_added = 1 << 5,
s_current = 1 << 6,
};
int irand(int n)
{
int r, rand_max = RAND_MAX - (RAND_MAX % n);
while ((r = rand()) >= rand_max);
return r / (rand_max / n);
}
int** alloc_board(int w, int h)
{
int i;
int **buf = calloc(1, sizeof(int *) * h + sizeof(int) * h * w);
buf[0] = (int*)(buf + h);
for (i = 1; i < h; i++)
buf[i] = buf[i - 1] + w;
return buf;
}
void expand_board(int dw, int dh)
{
int i, j;
int nw = width + !!dw, nh = height + !!dh;
int **nbuf = alloc_board(nw, nh);
dw = -(dw < 0), dh = -(dh < 0);
for (i = 0; i < nh; i++) {
if (i + dh < 0 || i + dh >= height) continue;
for (j = 0; j < nw; j++) {
if (j + dw < 0 || j + dw >= width) continue;
nbuf[i][j] = board[i + dh][j + dw];
}
}
free(board);
board = nbuf;
width = nw;
height = nh;
}
void array_set(int **buf, int v, int x0, int y0, int x1, int y1)
{
int i, j;
for (i = y0; i <= y1; i++)
for (j = x0; j <= x1; j++)
buf[i][j] = v;
}
void show_board()
{
int i, j;
for_i for_j mvprintw(i + 1, j * 2,
(board[i][j] & s_current) ? "X "
: (board[i][j] & s_newly_added) ? "O "
: (board[i][j] & s_occupied) ? "+ " : " ");
refresh();
}
void init_board()
{
width = height = 3 * (line_len - 1);
board = alloc_board(width, height);
array_set(board, s_occupied, line_len - 1, 1, 2 * line_len - 3, height - 2);
array_set(board, s_occupied, 1, line_len - 1, width - 2, 2 * line_len - 3);
array_set(board, s_blank, line_len, 2, 2 * line_len - 4, height - 3);
array_set(board, s_blank, 2, line_len, width - 3, 2 * line_len - 4);
}
int ofs[4][3] = {
{0, 1, s_dir_ns},
{1, 0, s_dir_ew},
{1, -1, s_dir_ne_sw},
{1, 1, s_dir_nw_se}
};
typedef struct { int m, s, seq, x, y; } move_t;
void test_postion(int y, int x, move_t * rec)
{
int m, k, s, dx, dy, xx, yy, dir;
if (board[y][x] & s_occupied) return;
for (m = 0; m < 4; m++) {
dx = ofs[m][0];
dy = ofs[m][1];
dir = ofs[m][2];
for (s = 1 - line_len; s <= 0; s++) {
for (k = 0; k < line_len; k++) {
if (s + k == 0) continue;
xx = x + dx * (s + k);
yy = y + dy * (s + k);
if (xx < 0 || xx >= width || yy < 0 || yy >= height)
break;
if (!(board[yy][xx] & s_occupied)) break;
if ((board[yy][xx] & dir)) break;
}
if (k != line_len) continue;
if (! irand(++rec->seq))
rec->m = m, rec->s = s, rec->x = x, rec->y = y;
}
}
}
void add_piece(move_t *rec) {
int dx = ofs[rec->m][0];
int dy = ofs[rec->m][1];
int dir= ofs[rec->m][2];
int xx, yy, k;
board[rec->y][rec->x] |= (s_current | s_occupied);
for (k = 0; k < line_len; k++) {
xx = rec->x + dx * (k + rec->s);
yy = rec->y + dy * (k + rec->s);
board[yy][xx] |= s_newly_added;
if (k >= disjoint || k < line_len - disjoint)
board[yy][xx] |= dir;
}
}
int next_move()
{
int i, j;
move_t rec;
rec.seq = 0;
for_i for_j board[i][j] &= ~(s_newly_added | s_current);
for_i for_j test_postion(i, j, &rec);
if (!rec.seq) return 0;
add_piece(&rec);
rec.x = (rec.x == width - 1) ? 1 : rec.x ? 0 : -1;
rec.y = (rec.y == height - 1) ? 1 : rec.y ? 0 : -1;
if (rec.x || rec.y) expand_board(rec.x, rec.y);
return 1;
}
int main()
{
int ch = 0;
int move = 0;
int wait_key = 1;
init_board();
srand(time(0));
initscr();
noecho();
cbreak();
do {
mvprintw(0, 0, "Move %d", move++);
show_board();
if (!next_move()) {
next_move();
show_board();
break;
}
if (!wait_key) usleep(100000);
if ((ch = getch()) == ' ') {
wait_key = !wait_key;
if (wait_key) timeout(-1);
else timeout(0);
}
} while (ch != 'q');
timeout(-1);
nocbreak();
echo();
endwin();
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import "fmt"
func main() {
list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}
list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}
var list [9]int
for i := 0; i < 9; i++ {
list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]
}
fmt.Println(list)
}
| #include<stdio.h>
#include<stdlib.h>
int main(void) {
int list[3][9], i;
for(i=0;i<27;i++) list[i/9][i%9]=1+i;
for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] );
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import "fmt"
func main() {
list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}
list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}
var list [9]int
for i := 0; i < 9; i++ {
list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]
}
fmt.Println(list)
}
| #include<stdio.h>
#include<stdlib.h>
int main(void) {
int list[3][9], i;
for(i=0;i<27;i++) list[i/9][i%9]=1+i;
for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] );
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"strings"
)
func lcs(a []string) string {
le := len(a)
if le == 0 {
return ""
}
if le == 1 {
return a[0]
}
le0 := len(a[0])
minLen := le0
for i := 1; i < le; i++ {
if len(a[i]) < minLen {
minLen = len(a[i])
}
}
if minLen == 0 {
return ""
}
res := ""
a1 := a[1:]
for i := 1; i <= minLen; i++ {
suffix := a[0][le0-i:]
for _, e := range a1 {
if !strings.HasSuffix(e, suffix) {
return res
}
}
res = suffix
}
return res
}
func main() {
tests := [][]string{
{"baabababc", "baabc", "bbbabc"},
{"baabababc", "baabc", "bbbazc"},
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
{"longest", "common", "suffix"},
{"suffix"},
{""},
}
for _, test := range tests {
fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node_t {
char *elem;
int length;
struct node_t *next;
} node;
node *make_node(char *s) {
node *t = malloc(sizeof(node));
t->elem = s;
t->length = strlen(s);
t->next = NULL;
return t;
}
void append_node(node *head, node *elem) {
while (head->next != NULL) {
head = head->next;
}
head->next = elem;
}
void print_node(node *n) {
putc('[', stdout);
while (n != NULL) {
printf("`%s` ", n->elem);
n = n->next;
}
putc(']', stdout);
}
char *lcs(node *list) {
int minLen = INT_MAX;
int i;
char *res;
node *ptr;
if (list == NULL) {
return "";
}
if (list->next == NULL) {
return list->elem;
}
for (ptr = list; ptr != NULL; ptr = ptr->next) {
minLen = min(minLen, ptr->length);
}
if (minLen == 0) {
return "";
}
res = "";
for (i = 1; i < minLen; i++) {
char *suffix = &list->elem[list->length - i];
for (ptr = list->next; ptr != NULL; ptr = ptr->next) {
char *e = &ptr->elem[ptr->length - i];
if (strcmp(suffix, e) != 0) {
return res;
}
}
res = suffix;
}
return res;
}
void test(node *n) {
print_node(n);
printf(" -> `%s`\n", lcs(n));
}
void case1() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbabc"));
test(n);
}
void case2() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbazc"));
test(n);
}
void case3() {
node *n = make_node("Sunday");
append_node(n, make_node("Monday"));
append_node(n, make_node("Tuesday"));
append_node(n, make_node("Wednesday"));
append_node(n, make_node("Thursday"));
append_node(n, make_node("Friday"));
append_node(n, make_node("Saturday"));
test(n);
}
void case4() {
node *n = make_node("longest");
append_node(n, make_node("common"));
append_node(n, make_node("suffix"));
test(n);
}
void case5() {
node *n = make_node("suffix");
test(n);
}
void case6() {
node *n = make_node("");
test(n);
}
int main() {
case1();
case2();
case3();
case4();
case5();
case6();
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
}
type Server struct {
add chan *conn
rem chan string
msg chan string
stop chan bool
}
func ListenAndServe(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
rwc, err := ln.Accept()
if err != nil {
close(s.stop)
return err
}
log.Println("New connection from", rwc.RemoteAddr())
go newConn(s, rwc).welcome()
}
}
func (s *Server) handleConns() {
conns := make(map[string]*conn)
var dropConn func(string)
writeAll := func(str string) {
log.Printf("Broadcast: %q", str)
for name, c := range conns {
c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))
_, err := c.Write([]byte(str))
if err != nil {
log.Printf("Error writing to %q: %v", name, err)
c.Close()
delete(conns, name)
defer dropConn(name)
}
}
}
dropConn = func(name string) {
if c, ok := conns[name]; ok {
log.Printf("Closing connection with %q from %v",
name, c.RemoteAddr())
c.Close()
delete(conns, name)
} else {
log.Printf("Dropped connection with %q", name)
}
str := fmt.Sprintf("--- %q disconnected ---\n", name)
writeAll(str)
}
defer func() {
writeAll("Server stopping!\n")
for _, c := range conns {
c.Close()
}
}()
for {
select {
case c := <-s.add:
if _, exists := conns[c.name]; exists {
fmt.Fprintf(c, "Name %q is not available\n", c.name)
go c.welcome()
continue
}
str := fmt.Sprintf("+++ %q connected +++\n", c.name)
writeAll(str)
conns[c.name] = c
go c.readloop()
case str := <-s.msg:
writeAll(str)
case name := <-s.rem:
dropConn(name)
case <-s.stop:
return
}
}
}
type conn struct {
*bufio.Reader
net.Conn
server *Server
name string
}
func newConn(s *Server, rwc net.Conn) *conn {
return &conn{
Reader: bufio.NewReader(rwc),
Conn: rwc,
server: s,
}
}
func (c *conn) welcome() {
var err error
for c.name = ""; c.name == ""; {
fmt.Fprint(c, "Enter your name: ")
c.name, err = c.ReadString('\n')
if err != nil {
log.Printf("Reading name from %v: %v", c.RemoteAddr(), err)
c.Close()
return
}
c.name = strings.TrimSpace(c.name)
}
c.server.add <- c
}
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')
if err != nil {
break
}
c.server.msg <- c.name + "> " + msg
}
c.server.rem <- c.name
}
| #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h>
int tsocket;
struct sockaddr_in tsockinfo;
fd_set status, current;
void ClientText(int handle, char *buf, int buf_len);
struct client
{
char buffer[4096];
int pos;
char name[32];
} *connections[FD_SETSIZE];
void AddConnection(int handle)
{
connections[handle] = malloc(sizeof(struct client));
connections[handle]->buffer[0] = '\0';
connections[handle]->pos = 0;
connections[handle]->name[0] = '\0';
}
void CloseConnection(int handle)
{
char buf[512];
int j;
FD_CLR(handle, &status);
if (connections[handle]->name[0])
{
sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name);
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, buf, strlen(buf)) < 0)
{
CloseConnection(j);
}
}
}
} else
{
printf ("-- Connection %d disconnected\n", handle);
}
if (connections[handle])
{
free(connections[handle]);
}
close(handle);
}
void strip(char *buf)
{
char *x;
x = strchr(buf, '\n');
if (x) { *x='\0'; }
x = strchr(buf, '\r');
if (x) { *x='\0'; }
}
int RelayText(int handle)
{
char *begin, *end;
int ret = 0;
begin = connections[handle]->buffer;
if (connections[handle]->pos == 4000)
{
if (begin[3999] != '\n')
begin[4000] = '\0';
else {
begin[4000] = '\n';
begin[4001] = '\0';
}
} else {
begin[connections[handle]->pos] = '\0';
}
end = strchr(begin, '\n');
while (end != NULL)
{
char output[8000];
output[0] = '\0';
if (!connections[handle]->name[0])
{
strncpy(connections[handle]->name, begin, 31);
connections[handle]->name[31] = '\0';
strip(connections[handle]->name);
sprintf(output, "* Connected: %s\r\n", connections[handle]->name);
ret = 1;
} else
{
sprintf(output, "%s: %.*s\r\n", connections[handle]->name,
end-begin, begin);
ret = 1;
}
if (output[0])
{
int j;
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, output, strlen(output)) < 0)
{
CloseConnection(j);
}
}
}
}
begin = end+1;
end = strchr(begin, '\n');
}
strcpy(connections[handle]->buffer, begin);
connections[handle]->pos -= begin - connections[handle]->buffer;
return ret;
}
void ClientText(int handle, char *buf, int buf_len)
{
int i, j;
if (!connections[handle])
return;
j = connections[handle]->pos;
for (i = 0; i < buf_len; ++i, ++j)
{
connections[handle]->buffer[j] = buf[i];
if (j == 4000)
{
while (RelayText(handle));
j = connections[handle]->pos;
}
}
connections[handle]->pos = j;
while (RelayText(handle));
}
int ChatLoop()
{
int i, j;
FD_ZERO(&status);
FD_SET(tsocket, &status);
FD_SET(0, &status);
while(1)
{
current = status;
if (select(FD_SETSIZE, ¤t, NULL, NULL, NULL)==-1)
{
perror("Select");
return 0;
}
for (i = 0; i < FD_SETSIZE; ++i)
{
if (FD_ISSET(i, ¤t))
{
if (i == tsocket)
{
struct sockaddr_in cliinfo;
socklen_t addrlen = sizeof(cliinfo);
int handle;
handle = accept(tsocket, &cliinfo, &addrlen);
if (handle == -1)
{
perror ("Couldn't accept connection");
} else if (handle > FD_SETSIZE)
{
printf ("Unable to accept new connection.\n");
close(handle);
}
else
{
if (write(handle, "Enter name: ", 12) >= 0)
{
printf("-- New connection %d from %s:%hu\n",
handle,
inet_ntoa (cliinfo.sin_addr),
ntohs(cliinfo.sin_port));
FD_SET(handle, &status);
AddConnection(handle);
}
}
}
else
{
char buf[512];
int b;
b = read(i, buf, 500);
if (b <= 0)
{
CloseConnection(i);
}
else
{
ClientText(i, buf, b);
}
}
}
}
}
}
int main (int argc, char*argv[])
{
tsocket = socket(PF_INET, SOCK_STREAM, 0);
tsockinfo.sin_family = AF_INET;
tsockinfo.sin_port = htons(7070);
if (argc > 1)
{
tsockinfo.sin_port = htons(atoi(argv[1]));
}
tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);
printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));
if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)
{
perror("Couldn't bind socket");
return -1;
}
if (listen(tsocket, 10) == -1)
{
perror("Couldn't listen to port");
}
ChatLoop();
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
p := sync.Pool{New: func() interface{} {
fmt.Println("pool empty")
return new(int)
}}
i := new(int)
j := new(int)
*i = 1
*j = 2
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
i = p.Get().(*int)
j = p.Get().(*int)
*i = 4
*j = 5
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
runtime.GC()
i = p.Get().(*int)
j = p.Get().(*int)
*i = 7
*j = 8
fmt.Println(*i + *j)
}
| #include <stdlib.h>
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
p := sync.Pool{New: func() interface{} {
fmt.Println("pool empty")
return new(int)
}}
i := new(int)
j := new(int)
*i = 1
*j = 2
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
i = p.Get().(*int)
j = p.Get().(*int)
*i = 4
*j = 5
fmt.Println(*i + *j)
p.Put(i)
p.Put(j)
i = nil
j = nil
runtime.GC()
i = p.Get().(*int)
j = p.Get().(*int)
*i = 7
*j = 8
fmt.Println(*i + *j)
}
| #include <stdlib.h>
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"unicode"
)
const (
lcASCII = "abcdefghijklmnopqrstuvwxyz"
ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func main() {
fmt.Println("ASCII lower case:")
fmt.Println(lcASCII)
for l := 'a'; l <= 'z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nASCII upper case:")
fmt.Println(ucASCII)
for l := 'A'; l <= 'Z'; l++ {
fmt.Print(string(l))
}
fmt.Println()
fmt.Println("\nUnicode version " + unicode.Version)
showRange16("Lower case 16-bit code points:", unicode.Lower.R16)
showRange32("Lower case 32-bit code points:", unicode.Lower.R32)
showRange16("Upper case 16-bit code points:", unicode.Upper.R16)
showRange32("Upper case 32-bit code points:", unicode.Upper.R32)
}
func showRange16(hdr string, rList []unicode.Range16) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
func showRange32(hdr string, rList []unicode.Range32) {
fmt.Print("\n", hdr, "\n")
fmt.Printf("%d ranges:\n", len(rList))
for _, rng := range rList {
fmt.Printf("%U: ", rng.Lo)
for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
fmt.Printf("%c", r)
}
fmt.Println()
}
}
| #include <stdio.h>
int main(int argc, char const *argv[]) {
for (char c = 0x41; c < 0x5b; c ++) putchar(c);
putchar('\n');
for (char c = 0x61; c < 0x7b; c ++) putchar(c);
putchar('\n');
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"log"
)
func main() {
m := [][]int{
{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5},
}
if len(m) != len(m[0]) {
log.Fatal("Matrix must be square.")
}
sum := 0
for i := 1; i < len(m); i++ {
for j := 0; j < i; j++ {
sum = sum + m[i][j]
}
}
fmt.Println("Sum of elements below main diagonal is", sum)
}
| #include<stdlib.h>
#include<stdio.h>
typedef struct{
int rows,cols;
int** dataSet;
}matrix;
matrix readMatrix(char* dataFile){
FILE* fp = fopen(dataFile,"r");
matrix rosetta;
int i,j;
fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);
rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
for(i=0;i<rosetta.rows;i++){
rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
for(j=0;j<rosetta.cols;j++)
fscanf(fp,"%d",&rosetta.dataSet[i][j]);
}
fclose(fp);
return rosetta;
}
void printMatrix(matrix rosetta){
int i,j;
for(i=0;i<rosetta.rows;i++){
printf("\n");
for(j=0;j<rosetta.cols;j++)
printf("%3d",rosetta.dataSet[i][j]);
}
}
int findSum(matrix rosetta){
int i,j,sum = 0;
for(i=1;i<rosetta.rows;i++){
for(j=0;j<i;j++){
sum += rosetta.dataSet[i][j];
}
}
return sum;
}
int main(int argC,char* argV[])
{
if(argC!=2)
return printf("Usage : %s <filename>",argV[0]);
matrix data = readMatrix(argV[1]);
printf("\n\nMatrix is : \n\n");
printMatrix(data);
printf("\n\nSum below main diagonal : %d",findSum(data));
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func get(url string) (res string, err error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(buf), nil
}
func grep(needle string, haystack string) (res []string) {
for _, line := range strings.Split(haystack, "\n") {
if strings.Contains(line, needle) {
res = append(res, line)
}
}
return res
}
func genUrl(i int, loc *time.Location) string {
date := time.Now().In(loc).AddDate(0, 0, i)
return date.Format("http:
}
func main() {
needle := os.Args[1]
back := -10
serverLoc, err := time.LoadLocation("Europe/Berlin")
if err != nil {
log.Fatal(err)
}
for i := back; i <= 0; i++ {
url := genUrl(i, serverLoc)
contents, err := get(url)
if err != nil {
log.Fatal(err)
}
found := grep(needle, contents)
if len(found) > 0 {
fmt.Printf("%v\n------\n", url)
for _, line := range found {
fmt.Printf("%v\n", line)
}
fmt.Printf("------\n\n")
}
}
}
| #include<curl/curl.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
void searchChatLogs(char* searchString){
char* baseURL = "http:
time_t t;
struct tm* currentDate;
char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];
int i,flag;
FILE *fp;
CURL *curl;
CURLcode res;
time(&t);
currentDate = localtime(&t);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
printf("Today is : %s",dateString);
if((curl = curl_easy_init())!=NULL){
for(i=0;i<=10;i++){
flag = 0;
sprintf(targetURL,"%s%s.tcl",baseURL,dateString);
strcpy(dateStringFile,dateString);
printf("\nRetrieving chat logs from %s\n",targetURL);
if((fp = fopen("nul","w"))==0){
printf("Cant's read from %s",targetURL);
}
else{
curl_easy_setopt(curl, CURLOPT_URL, targetURL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
if(res == CURLE_OK){
while(fgets(lineData,MAX_LEN,fp)!=NULL){
if(strstr(lineData,searchString)!=NULL){
flag = 1;
fputs(lineData,stdout);
}
}
if(flag==0)
printf("\nNo matching lines found.");
}
fflush(fp);
fclose(fp);
}
currentDate->tm_mday--;
mktime(currentDate);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
}
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <followed by search string, enclosed by \" if it contains spaces>",argV[0]);
else
searchChatLogs(argV[1]);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
)
const (
esc = "\033"
test = true
)
var scanner = bufio.NewScanner(os.Stdin)
func indexOf(s []int, el int) int {
for i, v := range s {
if v == el {
return i
}
}
return -1
}
func getNumber(prompt string, min, max int, showMinMax bool) (int, error) {
for {
fmt.Print(prompt)
if showMinMax {
fmt.Printf(" from %d to %d : ", min, max)
} else {
fmt.Printf(" : ")
}
scanner.Scan()
if scerr := scanner.Err(); scerr != nil {
return 0, scerr
}
input, err := strconv.Atoi(scanner.Text())
if err == nil && input >= min && input <= max {
fmt.Println()
return input, nil
}
}
}
func check(err error, text string) {
if err != nil {
log.Fatalln(err, text)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
players, err := getNumber("Number of players", 2, 9, true)
check(err, "when getting players")
coins, err2 := getNumber("Number of coins per player", 3, 6, true)
check(err2, "when getting coins")
remaining := make([]int, players)
for i := range remaining {
remaining[i] = i + 1
}
first := 1 + rand.Intn(players)
fmt.Println("The number of coins in your hand will be randomly determined for")
fmt.Println("each round and displayed to you. However, when you press ENTER")
fmt.Println("it will be erased so that the other players, who should look")
fmt.Println("away until it's their turn, won't see it. When asked to guess")
fmt.Println("the total, the computer won't allow a 'bum guess'.")
for round := 1; ; round++ {
fmt.Printf("\nROUND %d:\n\n", round)
n := first
hands := make([]int, players+1)
guesses := make([]int, players+1)
for i := range guesses {
guesses[i] = -1
}
for {
fmt.Printf(" PLAYER %d:\n", n)
fmt.Println(" Please come to the computer and press ENTER")
hands[n] = rand.Intn(coins + 1)
fmt.Print(" <There are ", hands[n], " coin(s) in your hand>")
scanner.Scan()
check(scanner.Err(), "when pressing ENTER")
if !test {
fmt.Print(esc, "[1A")
fmt.Print(esc, "[2K")
fmt.Println("\r")
} else {
fmt.Println()
}
for {
min := hands[n]
max := (len(remaining)-1)*coins + hands[n]
guess, err3 := getNumber(" Guess the total", min, max, false)
check(err3, "when guessing the total")
if indexOf(guesses, guess) == -1 {
guesses[n] = guess
break
}
fmt.Println(" Already guessed by another player, try again")
}
index := indexOf(remaining, n)
if index < len(remaining)-1 {
n = remaining[index+1]
} else {
n = remaining[0]
}
if n == first {
break
}
}
total := 0
for _, hand := range hands {
total += hand
}
fmt.Println(" Total coins held =", total)
eliminated := false
for _, v := range remaining {
if guesses[v] == total {
fmt.Println(" PLAYER", v, "guessed correctly and is eliminated")
r := indexOf(remaining, v)
remaining = append(remaining[:r], remaining[r+1:]...)
eliminated = true
break
}
}
if !eliminated {
fmt.Println(" No players guessed correctly in this round")
} else if len(remaining) == 1 {
fmt.Println("\nPLAYER", remaining[0], "buys the drinks!")
return
}
index2 := indexOf(remaining, n)
if index2 < len(remaining)-1 {
first = remaining[index2+1]
} else {
first = remaining[0]
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
#define ESC 27
#define TEST TRUE
typedef int bool;
int get_number(const char *prompt, int min, int max, bool show_mm) {
int n;
char *line = NULL;
size_t len = 0;
ssize_t read;
fflush(stdin);
do {
printf("%s", prompt);
if (show_mm)
printf(" from %d to %d : ", min, max);
else
printf(" : ");
read = getline(&line, &len, stdin);
if (read < 2) continue;
n = atoi(line);
}
while (n < min || n > max);
printf("\n");
return n;
}
int compare_int(const void *a, const void* b) {
int i = *(int *)a;
int j = *(int *)b;
return i - j;
}
int main() {
int i, j, n, players, coins, first, round = 1, rem_size;
int min, max, guess, index, index2, total;
int remaining[9], hands[10], guesses[10];
bool found, eliminated;
char c;
players = get_number("Number of players", 2, 9, TRUE);
coins = get_number("Number of coins per player", 3, 6, TRUE);
for (i = 0; i < 9; ++i) remaining[i] = i + 1;
rem_size = players;
srand(time(NULL));
first = 1 + rand() % players;
printf("The number of coins in your hand will be randomly determined for");
printf("\neach round and displayed to you. However, when you press ENTER");
printf("\nit will be erased so that the other players, who should look");
printf("\naway until it's their turn, won't see it. When asked to guess");
printf("\nthe total, the computer won't allow a 'bum guess'.\n");
while(TRUE) {
printf("\nROUND %d:\n", round);
n = first;
for (i = 0; i < 10; ++i) {
hands[i] = 0; guesses[i] = -1;
}
do {
printf(" PLAYER %d:\n", n);
printf(" Please come to the computer and press ENTER\n");
hands[n] = rand() % (coins + 1);
printf(" <There are %d coin(s) in your hand>", hands[n]);
while (getchar() != '\n');
if (!TEST) {
printf("%c[1A", ESC);
printf("%c[2K", ESC);
printf("\r\n");
}
else printf("\n");
while (TRUE) {
min = hands[n];
max = (rem_size - 1) * coins + hands[n];
guess = get_number(" Guess the total", min, max, FALSE);
found = FALSE;
for (i = 1; i < 10; ++i) {
if (guess == guesses[i]) {
found = TRUE;
break;
}
}
if (!found) {
guesses[n] = guess;
break;
}
printf(" Already guessed by another player, try again\n");
}
index = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == n) {
index = i;
break;
}
}
if (index < rem_size - 1)
n = remaining[index + 1];
else
n = remaining[0];
}
while (n != first);
total = 0;
for (i = 1; i < 10; ++i) total += hands[i];
printf(" Total coins held = %d\n", total);
eliminated = FALSE;
for (i = 0; i < rem_size; ++i) {
j = remaining[i];
if (guesses[j] == total) {
printf(" PLAYER %d guessed correctly and is eliminated\n", j);
remaining[i] = 10;
rem_size--;
qsort(remaining, players, sizeof(int), compare_int);
eliminated = TRUE;
break;
}
}
if (!eliminated)
printf(" No players guessed correctly in this round\n");
else if (rem_size == 1) {
printf("\nPLAYER %d buys the drinks!\n", remaining[0]);
break;
}
index2 = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == first) {
index2 = i;
break;
}
}
if (index2 < rem_size - 1)
first = remaining[index2 + 1];
else
first = remaining[0];
round++;
}
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
)
const (
esc = "\033"
test = true
)
var scanner = bufio.NewScanner(os.Stdin)
func indexOf(s []int, el int) int {
for i, v := range s {
if v == el {
return i
}
}
return -1
}
func getNumber(prompt string, min, max int, showMinMax bool) (int, error) {
for {
fmt.Print(prompt)
if showMinMax {
fmt.Printf(" from %d to %d : ", min, max)
} else {
fmt.Printf(" : ")
}
scanner.Scan()
if scerr := scanner.Err(); scerr != nil {
return 0, scerr
}
input, err := strconv.Atoi(scanner.Text())
if err == nil && input >= min && input <= max {
fmt.Println()
return input, nil
}
}
}
func check(err error, text string) {
if err != nil {
log.Fatalln(err, text)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
players, err := getNumber("Number of players", 2, 9, true)
check(err, "when getting players")
coins, err2 := getNumber("Number of coins per player", 3, 6, true)
check(err2, "when getting coins")
remaining := make([]int, players)
for i := range remaining {
remaining[i] = i + 1
}
first := 1 + rand.Intn(players)
fmt.Println("The number of coins in your hand will be randomly determined for")
fmt.Println("each round and displayed to you. However, when you press ENTER")
fmt.Println("it will be erased so that the other players, who should look")
fmt.Println("away until it's their turn, won't see it. When asked to guess")
fmt.Println("the total, the computer won't allow a 'bum guess'.")
for round := 1; ; round++ {
fmt.Printf("\nROUND %d:\n\n", round)
n := first
hands := make([]int, players+1)
guesses := make([]int, players+1)
for i := range guesses {
guesses[i] = -1
}
for {
fmt.Printf(" PLAYER %d:\n", n)
fmt.Println(" Please come to the computer and press ENTER")
hands[n] = rand.Intn(coins + 1)
fmt.Print(" <There are ", hands[n], " coin(s) in your hand>")
scanner.Scan()
check(scanner.Err(), "when pressing ENTER")
if !test {
fmt.Print(esc, "[1A")
fmt.Print(esc, "[2K")
fmt.Println("\r")
} else {
fmt.Println()
}
for {
min := hands[n]
max := (len(remaining)-1)*coins + hands[n]
guess, err3 := getNumber(" Guess the total", min, max, false)
check(err3, "when guessing the total")
if indexOf(guesses, guess) == -1 {
guesses[n] = guess
break
}
fmt.Println(" Already guessed by another player, try again")
}
index := indexOf(remaining, n)
if index < len(remaining)-1 {
n = remaining[index+1]
} else {
n = remaining[0]
}
if n == first {
break
}
}
total := 0
for _, hand := range hands {
total += hand
}
fmt.Println(" Total coins held =", total)
eliminated := false
for _, v := range remaining {
if guesses[v] == total {
fmt.Println(" PLAYER", v, "guessed correctly and is eliminated")
r := indexOf(remaining, v)
remaining = append(remaining[:r], remaining[r+1:]...)
eliminated = true
break
}
}
if !eliminated {
fmt.Println(" No players guessed correctly in this round")
} else if len(remaining) == 1 {
fmt.Println("\nPLAYER", remaining[0], "buys the drinks!")
return
}
index2 := indexOf(remaining, n)
if index2 < len(remaining)-1 {
first = remaining[index2+1]
} else {
first = remaining[0]
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
#define ESC 27
#define TEST TRUE
typedef int bool;
int get_number(const char *prompt, int min, int max, bool show_mm) {
int n;
char *line = NULL;
size_t len = 0;
ssize_t read;
fflush(stdin);
do {
printf("%s", prompt);
if (show_mm)
printf(" from %d to %d : ", min, max);
else
printf(" : ");
read = getline(&line, &len, stdin);
if (read < 2) continue;
n = atoi(line);
}
while (n < min || n > max);
printf("\n");
return n;
}
int compare_int(const void *a, const void* b) {
int i = *(int *)a;
int j = *(int *)b;
return i - j;
}
int main() {
int i, j, n, players, coins, first, round = 1, rem_size;
int min, max, guess, index, index2, total;
int remaining[9], hands[10], guesses[10];
bool found, eliminated;
char c;
players = get_number("Number of players", 2, 9, TRUE);
coins = get_number("Number of coins per player", 3, 6, TRUE);
for (i = 0; i < 9; ++i) remaining[i] = i + 1;
rem_size = players;
srand(time(NULL));
first = 1 + rand() % players;
printf("The number of coins in your hand will be randomly determined for");
printf("\neach round and displayed to you. However, when you press ENTER");
printf("\nit will be erased so that the other players, who should look");
printf("\naway until it's their turn, won't see it. When asked to guess");
printf("\nthe total, the computer won't allow a 'bum guess'.\n");
while(TRUE) {
printf("\nROUND %d:\n", round);
n = first;
for (i = 0; i < 10; ++i) {
hands[i] = 0; guesses[i] = -1;
}
do {
printf(" PLAYER %d:\n", n);
printf(" Please come to the computer and press ENTER\n");
hands[n] = rand() % (coins + 1);
printf(" <There are %d coin(s) in your hand>", hands[n]);
while (getchar() != '\n');
if (!TEST) {
printf("%c[1A", ESC);
printf("%c[2K", ESC);
printf("\r\n");
}
else printf("\n");
while (TRUE) {
min = hands[n];
max = (rem_size - 1) * coins + hands[n];
guess = get_number(" Guess the total", min, max, FALSE);
found = FALSE;
for (i = 1; i < 10; ++i) {
if (guess == guesses[i]) {
found = TRUE;
break;
}
}
if (!found) {
guesses[n] = guess;
break;
}
printf(" Already guessed by another player, try again\n");
}
index = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == n) {
index = i;
break;
}
}
if (index < rem_size - 1)
n = remaining[index + 1];
else
n = remaining[0];
}
while (n != first);
total = 0;
for (i = 1; i < 10; ++i) total += hands[i];
printf(" Total coins held = %d\n", total);
eliminated = FALSE;
for (i = 0; i < rem_size; ++i) {
j = remaining[i];
if (guesses[j] == total) {
printf(" PLAYER %d guessed correctly and is eliminated\n", j);
remaining[i] = 10;
rem_size--;
qsort(remaining, players, sizeof(int), compare_int);
eliminated = TRUE;
break;
}
}
if (!eliminated)
printf(" No players guessed correctly in this round\n");
else if (rem_size == 1) {
printf("\nPLAYER %d buys the drinks!\n", remaining[0]);
break;
}
index2 = -1;
for (i = 0; i < rem_size; ++i) {
if (remaining[i] == first) {
index2 = i;
break;
}
}
if (index2 < rem_size - 1)
first = remaining[index2 + 1];
else
first = remaining[0];
round++;
}
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"sort"
"strconv"
)
type Result struct {
lang string
users int
}
func main() {
const minimum = 25
ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)`
re := regexp.MustCompile(ex)
page := "http:
action := "action=query"
format := "format=json"
fversion := "formatversion=2"
generator := "generator=categorymembers"
gcmTitle := "gcmtitle=Category:Language%20users"
gcmLimit := "gcmlimit=500"
prop := "prop=categoryinfo"
rawContinue := "rawcontinue="
page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion,
generator, gcmTitle, gcmLimit, prop, rawContinue)
resp, _ := http.Get(page)
body, _ := ioutil.ReadAll(resp.Body)
matches := re.FindAllStringSubmatch(string(body), -1)
resp.Body.Close()
var results []Result
for _, match := range matches {
if len(match) == 5 {
users, _ := strconv.Atoi(match[4])
if users >= minimum {
result := Result{match[1], users}
results = append(results, result)
}
}
}
sort.Slice(results, func(i, j int) bool {
return results[j].users < results[i].users
})
fmt.Println("Rank Users Language")
fmt.Println("---- ----- --------")
rank := 0
lastUsers := 0
lastRank := 0
for i, result := range results {
eq := " "
rank = i + 1
if lastUsers == result.users {
eq = "="
rank = lastRank
} else {
lastUsers = result.users
lastRank = rank
}
fmt.Printf(" %-2d%s %3d %s\n", rank, eq, result.users, result.lang)
}
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_rank_languages_by_number_of_users.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;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"sort"
"strconv"
)
type Result struct {
lang string
users int
}
func main() {
const minimum = 25
ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)`
re := regexp.MustCompile(ex)
page := "http:
action := "action=query"
format := "format=json"
fversion := "formatversion=2"
generator := "generator=categorymembers"
gcmTitle := "gcmtitle=Category:Language%20users"
gcmLimit := "gcmlimit=500"
prop := "prop=categoryinfo"
rawContinue := "rawcontinue="
page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion,
generator, gcmTitle, gcmLimit, prop, rawContinue)
resp, _ := http.Get(page)
body, _ := ioutil.ReadAll(resp.Body)
matches := re.FindAllStringSubmatch(string(body), -1)
resp.Body.Close()
var results []Result
for _, match := range matches {
if len(match) == 5 {
users, _ := strconv.Atoi(match[4])
if users >= minimum {
result := Result{match[1], users}
results = append(results, result)
}
}
}
sort.Slice(results, func(i, j int) bool {
return results[j].users < results[i].users
})
fmt.Println("Rank Users Language")
fmt.Println("---- ----- --------")
rank := 0
lastUsers := 0
lastRank := 0
for i, result := range results {
eq := " "
rank = i + 1
if lastUsers == result.users {
eq = "="
rank = lastRank
} else {
lastUsers = result.users
lastRank = rank
}
fmt.Printf(" %-2d%s %3d %s\n", rank, eq, result.users, result.lang)
}
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_rank_languages_by_number_of_users.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;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"math"
)
const (
N = 32
NMAX = 40000
)
var (
u = [N]int{0: 1, 1: 2}
l = [N]int{0: 1, 1: 2}
out = [N]int{}
sum = [N]int{}
tail = [N]int{}
cache = [NMAX + 1]int{2: 1}
known = 2
stack = 0
undo = [N * N]save{}
)
type save struct {
p *int
v int
}
func replace(x *[N]int, i, n int) {
undo[stack].p = &x[i]
undo[stack].v = x[i]
x[i] = n
stack++
}
func restore(n int) {
for stack > n {
stack--
*undo[stack].p = undo[stack].v
}
}
func lower(n int, up *int) int {
if n <= 2 || (n <= NMAX && cache[n] != 0) {
if up != nil {
*up = cache[n]
}
return cache[n]
}
i, o := -1, 0
for ; n != 0; n, i = n>>1, i+1 {
if n&1 != 0 {
o++
}
}
if up != nil {
i--
*up = o + i
}
for {
i++
o >>= 1
if o == 0 {
break
}
}
if up == nil {
return i
}
for o = 2; o*o < n; o++ {
if n%o != 0 {
continue
}
q := cache[o] + cache[n/o]
if q < *up {
*up = q
if q == i {
break
}
}
}
if n > 2 {
if *up > cache[n-2]+1 {
*up = cache[n-1] + 1
}
if *up > cache[n-2]+1 {
*up = cache[n-2] + 1
}
}
return i
}
func insert(x, pos int) bool {
save := stack
if l[pos] > x || u[pos] < x {
return false
}
if l[pos] == x {
goto replU
}
replace(&l, pos, x)
for i := pos - 1; u[i]*2 < u[i+1]; i-- {
t := l[i+1] + 1
if t*2 > u[i] {
goto bail
}
replace(&l, i, t)
}
for i := pos + 1; l[i] <= l[i-1]; i++ {
t := l[i-1] + 1
if t > u[i] {
goto bail
}
replace(&l, i, t)
}
replU:
if u[pos] == x {
return true
}
replace(&u, pos, x)
for i := pos - 1; u[i] >= u[i+1]; i-- {
t := u[i+1] - 1
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
for i := pos + 1; u[i] > u[i-1]*2; i++ {
t := u[i-1] * 2
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
return true
bail:
restore(save)
return false
}
func try(p, q, le int) bool {
pl := cache[p]
if pl >= le {
return false
}
ql := cache[q]
if ql >= le {
return false
}
var pu, qu int
for pl < le && u[pl] < p {
pl++
}
for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {
}
for ql < le && u[ql] < q {
ql++
}
for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {
}
if p != q && pl <= ql {
pl = ql + 1
}
if pl > pu || ql > qu || ql > pu {
return false
}
if out[le] == 0 {
pu = le - 1
pl = pu
}
ps := stack
for ; pu >= pl; pu-- {
if !insert(p, pu) {
continue
}
out[pu]++
sum[pu] += le
if p != q {
qs := stack
j := qu
if j >= pu {
j = pu - 1
}
for ; j >= ql; j-- {
if !insert(q, j) {
continue
}
out[j]++
sum[j] += le
tail[le] = q
if seqRecur(le - 1) {
return true
}
restore(qs)
out[j]--
sum[j] -= le
}
} else {
out[pu]++
sum[pu] += le
tail[le] = p
if seqRecur(le - 1) {
return true
}
out[pu]--
sum[pu] -= le
}
out[pu]--
sum[pu] -= le
restore(ps)
}
return false
}
func seqRecur(le int) bool {
n := l[le]
if le < 2 {
return true
}
limit := n - 1
if out[le] == 1 {
limit = n - tail[sum[le]]
}
if limit > u[le-1] {
limit = u[le-1]
}
p := limit
for q := n - p; q <= p; q, p = q+1, p-1 {
if try(p, q, le) {
return true
}
}
return false
}
func seq(n, le int, buf []int) int {
if le == 0 {
le = seqLen(n)
}
stack = 0
l[le], u[le] = n, n
for i := 0; i <= le; i++ {
out[i], sum[i] = 0, 0
}
for i := 2; i < le; i++ {
l[i] = l[i-1] + 1
u[i] = u[i-1] * 2
}
for i := le - 1; i > 2; i-- {
if l[i]*2 < l[i+1] {
l[i] = (1 + l[i+1]) / 2
}
if u[i] >= u[i+1] {
u[i] = u[i+1] - 1
}
}
if !seqRecur(le) {
return 0
}
if buf != nil {
for i := 0; i <= le; i++ {
buf[i] = u[i]
}
}
return le
}
func seqLen(n int) int {
if n <= known {
return cache[n]
}
for known+1 < n {
seqLen(known + 1)
}
var ub int
lb := lower(n, &ub)
for lb < ub && seq(n, lb, nil) == 0 {
lb++
}
known = n
if n&1023 == 0 {
fmt.Printf("Cached %d\n", known)
}
cache[n] = lb
return lb
}
func binLen(n int) int {
r, o := -1, -1
for ; n != 0; n, r = n>>1, r+1 {
if n&1 != 0 {
o++
}
}
return r + o
}
type(
vector = []float64
matrix []vector
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func (m matrix) pow(n int, printout bool) matrix {
e := make([]int, N)
var v [N]matrix
le := seq(n, 0, e)
if printout {
fmt.Println("Addition chain:")
for i := 0; i <= le; i++ {
c := ' '
if i == le {
c = '\n'
}
fmt.Printf("%d%c", e[i], c)
}
}
v[0] = m
v[1] = m.mul(m)
for i := 2; i <= le; i++ {
for j := i - 1; j != 0; j-- {
for k := j; k >= 0; k-- {
if e[k]+e[j] < e[i] {
break
}
if e[k]+e[j] > e[i] {
continue
}
v[i] = v[j].mul(v[k])
j = 1
break
}
}
}
return v[le]
}
func (m matrix) print() {
for _, v := range m {
fmt.Printf("% f\n", v)
}
fmt.Println()
}
func main() {
m := 27182
n := 31415
fmt.Println("Precompute chain lengths:")
seqLen(n)
rh := math.Sqrt(0.5)
mx := matrix{
{rh, 0, rh, 0, 0, 0},
{0, rh, 0, rh, 0, 0},
{0, rh, 0, -rh, 0, 0},
{-rh, 0, rh, 0, 0, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 1, 0},
}
fmt.Println("\nThe first 100 terms of A003313 are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%d ", seqLen(i))
if i%10 == 0 {
fmt.Println()
}
}
exs := [2]int{m, n}
mxs := [2]matrix{}
for i, ex := range exs {
fmt.Println("\nExponent:", ex)
mxs[i] = mx.pow(ex, true)
fmt.Printf("A ^ %d:-\n\n", ex)
mxs[i].print()
fmt.Println("Number of A/C multiplies:", seqLen(ex))
fmt.Println(" c.f. Binary multiplies:", binLen(ex))
}
fmt.Printf("\nExponent: %d x %d = %d\n", m, n, m*n)
fmt.Printf("A ^ %d = (A ^ %d) ^ %d:-\n\n", m*n, m, n)
mx2 := mxs[0].pow(n, false)
mx2.print()
}
| #include <stdio.h>
#include "achain.c"
typedef struct {double u, v;} cplx;
inline cplx c_mul(cplx a, cplx b)
{
cplx c;
c.u = a.u * b.u - a.v * b.v;
c.v = a.u * b.v + a.v * b.u;
return c;
}
cplx chain_expo(cplx x, int n)
{
int i, j, k, l, e[32];
cplx v[32];
l = seq(n, 0, e);
puts("Exponents:");
for (i = 0; i <= l; i++)
printf("%d%c", e[i], i == l ? '\n' : ' ');
v[0] = x; v[1] = c_mul(x, x);
for (i = 2; i <= l; i++) {
for (j = i - 1; j; j--) {
for (k = j; k >= 0; k--) {
if (e[k] + e[j] < e[i]) break;
if (e[k] + e[j] > e[i]) continue;
v[i] = c_mul(v[j], v[k]);
j = 1;
break;
}
}
}
printf("(%f + i%f)^%d = %f + i%f\n",
x.u, x.v, n, v[l].u, v[l].v);
return x;
}
int bin_len(int n)
{
int r, o;
for (r = o = -1; n; n >>= 1, r++)
if (n & 1) o++;
return r + o;
}
int main()
{
cplx r1 = {1.0000254989, 0.0000577896},
r2 = {1.0000220632, 0.0000500026};
int n1 = 27182, n2 = 31415, i;
init();
puts("Precompute chain lengths");
seq_len(n2);
chain_expo(r1, n1);
chain_expo(r2, n2);
puts("\nchain lengths: shortest binary");
printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1));
printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2));
for (i = 1; i < 100; i++)
printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i));
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math"
)
const (
N = 32
NMAX = 40000
)
var (
u = [N]int{0: 1, 1: 2}
l = [N]int{0: 1, 1: 2}
out = [N]int{}
sum = [N]int{}
tail = [N]int{}
cache = [NMAX + 1]int{2: 1}
known = 2
stack = 0
undo = [N * N]save{}
)
type save struct {
p *int
v int
}
func replace(x *[N]int, i, n int) {
undo[stack].p = &x[i]
undo[stack].v = x[i]
x[i] = n
stack++
}
func restore(n int) {
for stack > n {
stack--
*undo[stack].p = undo[stack].v
}
}
func lower(n int, up *int) int {
if n <= 2 || (n <= NMAX && cache[n] != 0) {
if up != nil {
*up = cache[n]
}
return cache[n]
}
i, o := -1, 0
for ; n != 0; n, i = n>>1, i+1 {
if n&1 != 0 {
o++
}
}
if up != nil {
i--
*up = o + i
}
for {
i++
o >>= 1
if o == 0 {
break
}
}
if up == nil {
return i
}
for o = 2; o*o < n; o++ {
if n%o != 0 {
continue
}
q := cache[o] + cache[n/o]
if q < *up {
*up = q
if q == i {
break
}
}
}
if n > 2 {
if *up > cache[n-2]+1 {
*up = cache[n-1] + 1
}
if *up > cache[n-2]+1 {
*up = cache[n-2] + 1
}
}
return i
}
func insert(x, pos int) bool {
save := stack
if l[pos] > x || u[pos] < x {
return false
}
if l[pos] == x {
goto replU
}
replace(&l, pos, x)
for i := pos - 1; u[i]*2 < u[i+1]; i-- {
t := l[i+1] + 1
if t*2 > u[i] {
goto bail
}
replace(&l, i, t)
}
for i := pos + 1; l[i] <= l[i-1]; i++ {
t := l[i-1] + 1
if t > u[i] {
goto bail
}
replace(&l, i, t)
}
replU:
if u[pos] == x {
return true
}
replace(&u, pos, x)
for i := pos - 1; u[i] >= u[i+1]; i-- {
t := u[i+1] - 1
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
for i := pos + 1; u[i] > u[i-1]*2; i++ {
t := u[i-1] * 2
if t < l[i] {
goto bail
}
replace(&u, i, t)
}
return true
bail:
restore(save)
return false
}
func try(p, q, le int) bool {
pl := cache[p]
if pl >= le {
return false
}
ql := cache[q]
if ql >= le {
return false
}
var pu, qu int
for pl < le && u[pl] < p {
pl++
}
for pu = pl - 1; pu < le-1 && u[pu+1] >= p; pu++ {
}
for ql < le && u[ql] < q {
ql++
}
for qu = ql - 1; qu < le-1 && u[qu+1] >= q; qu++ {
}
if p != q && pl <= ql {
pl = ql + 1
}
if pl > pu || ql > qu || ql > pu {
return false
}
if out[le] == 0 {
pu = le - 1
pl = pu
}
ps := stack
for ; pu >= pl; pu-- {
if !insert(p, pu) {
continue
}
out[pu]++
sum[pu] += le
if p != q {
qs := stack
j := qu
if j >= pu {
j = pu - 1
}
for ; j >= ql; j-- {
if !insert(q, j) {
continue
}
out[j]++
sum[j] += le
tail[le] = q
if seqRecur(le - 1) {
return true
}
restore(qs)
out[j]--
sum[j] -= le
}
} else {
out[pu]++
sum[pu] += le
tail[le] = p
if seqRecur(le - 1) {
return true
}
out[pu]--
sum[pu] -= le
}
out[pu]--
sum[pu] -= le
restore(ps)
}
return false
}
func seqRecur(le int) bool {
n := l[le]
if le < 2 {
return true
}
limit := n - 1
if out[le] == 1 {
limit = n - tail[sum[le]]
}
if limit > u[le-1] {
limit = u[le-1]
}
p := limit
for q := n - p; q <= p; q, p = q+1, p-1 {
if try(p, q, le) {
return true
}
}
return false
}
func seq(n, le int, buf []int) int {
if le == 0 {
le = seqLen(n)
}
stack = 0
l[le], u[le] = n, n
for i := 0; i <= le; i++ {
out[i], sum[i] = 0, 0
}
for i := 2; i < le; i++ {
l[i] = l[i-1] + 1
u[i] = u[i-1] * 2
}
for i := le - 1; i > 2; i-- {
if l[i]*2 < l[i+1] {
l[i] = (1 + l[i+1]) / 2
}
if u[i] >= u[i+1] {
u[i] = u[i+1] - 1
}
}
if !seqRecur(le) {
return 0
}
if buf != nil {
for i := 0; i <= le; i++ {
buf[i] = u[i]
}
}
return le
}
func seqLen(n int) int {
if n <= known {
return cache[n]
}
for known+1 < n {
seqLen(known + 1)
}
var ub int
lb := lower(n, &ub)
for lb < ub && seq(n, lb, nil) == 0 {
lb++
}
known = n
if n&1023 == 0 {
fmt.Printf("Cached %d\n", known)
}
cache[n] = lb
return lb
}
func binLen(n int) int {
r, o := -1, -1
for ; n != 0; n, r = n>>1, r+1 {
if n&1 != 0 {
o++
}
}
return r + o
}
type(
vector = []float64
matrix []vector
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func (m matrix) pow(n int, printout bool) matrix {
e := make([]int, N)
var v [N]matrix
le := seq(n, 0, e)
if printout {
fmt.Println("Addition chain:")
for i := 0; i <= le; i++ {
c := ' '
if i == le {
c = '\n'
}
fmt.Printf("%d%c", e[i], c)
}
}
v[0] = m
v[1] = m.mul(m)
for i := 2; i <= le; i++ {
for j := i - 1; j != 0; j-- {
for k := j; k >= 0; k-- {
if e[k]+e[j] < e[i] {
break
}
if e[k]+e[j] > e[i] {
continue
}
v[i] = v[j].mul(v[k])
j = 1
break
}
}
}
return v[le]
}
func (m matrix) print() {
for _, v := range m {
fmt.Printf("% f\n", v)
}
fmt.Println()
}
func main() {
m := 27182
n := 31415
fmt.Println("Precompute chain lengths:")
seqLen(n)
rh := math.Sqrt(0.5)
mx := matrix{
{rh, 0, rh, 0, 0, 0},
{0, rh, 0, rh, 0, 0},
{0, rh, 0, -rh, 0, 0},
{-rh, 0, rh, 0, 0, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 1, 0},
}
fmt.Println("\nThe first 100 terms of A003313 are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%d ", seqLen(i))
if i%10 == 0 {
fmt.Println()
}
}
exs := [2]int{m, n}
mxs := [2]matrix{}
for i, ex := range exs {
fmt.Println("\nExponent:", ex)
mxs[i] = mx.pow(ex, true)
fmt.Printf("A ^ %d:-\n\n", ex)
mxs[i].print()
fmt.Println("Number of A/C multiplies:", seqLen(ex))
fmt.Println(" c.f. Binary multiplies:", binLen(ex))
}
fmt.Printf("\nExponent: %d x %d = %d\n", m, n, m*n)
fmt.Printf("A ^ %d = (A ^ %d) ^ %d:-\n\n", m*n, m, n)
mx2 := mxs[0].pow(n, false)
mx2.print()
}
| #include <stdio.h>
#include "achain.c"
typedef struct {double u, v;} cplx;
inline cplx c_mul(cplx a, cplx b)
{
cplx c;
c.u = a.u * b.u - a.v * b.v;
c.v = a.u * b.v + a.v * b.u;
return c;
}
cplx chain_expo(cplx x, int n)
{
int i, j, k, l, e[32];
cplx v[32];
l = seq(n, 0, e);
puts("Exponents:");
for (i = 0; i <= l; i++)
printf("%d%c", e[i], i == l ? '\n' : ' ');
v[0] = x; v[1] = c_mul(x, x);
for (i = 2; i <= l; i++) {
for (j = i - 1; j; j--) {
for (k = j; k >= 0; k--) {
if (e[k] + e[j] < e[i]) break;
if (e[k] + e[j] > e[i]) continue;
v[i] = c_mul(v[j], v[k]);
j = 1;
break;
}
}
}
printf("(%f + i%f)^%d = %f + i%f\n",
x.u, x.v, n, v[l].u, v[l].v);
return x;
}
int bin_len(int n)
{
int r, o;
for (r = o = -1; n; n >>= 1, r++)
if (n & 1) o++;
return r + o;
}
int main()
{
cplx r1 = {1.0000254989, 0.0000577896},
r2 = {1.0000220632, 0.0000500026};
int n1 = 27182, n2 = 31415, i;
init();
puts("Precompute chain lengths");
seq_len(n2);
chain_expo(r1, n1);
chain_expo(r2, n2);
puts("\nchain lengths: shortest binary");
printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1));
printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2));
for (i = 1; i < 100; i++)
printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i));
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | #!/bin/bash
sed -n -e '12,$p' < "$0" > ttmmpp.go
go build ttmmpp.go
rm ttmmpp.go
binfile="${0%.*}"
mv ttmmpp $binfile
$binfile "$@"
STATUS=$?
rm $binfile
exit $STATUS
######## Go Code start on line 12
package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args {
if i == 0 {
fmt.Printf("This program is named %s.\n", x)
} else {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
}
| |
Keep all operations the same but rewrite the snippet in C. | #!/bin/bash
sed -n -e '12,$p' < "$0" > ttmmpp.go
go build ttmmpp.go
rm ttmmpp.go
binfile="${0%.*}"
mv ttmmpp $binfile
$binfile "$@"
STATUS=$?
rm $binfile
exit $STATUS
######## Go Code start on line 12
package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args {
if i == 0 {
fmt.Printf("This program is named %s.\n", x)
} else {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
}
| |
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"fmt"
"os"
"strings"
)
func main() {
lang := strings.ToUpper(os.Getenv("LANG"))
if strings.Contains(lang, "UTF") {
fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
} else {
fmt.Println("This terminal does not support unicode")
}
}
| #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Unicode is supported on this terminal and U+25B3 is : \u25b3");
i = -1;
break;
}
}
if (i != -1)
printf ("Unicode is not supported on this terminal.");
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"os"
"strings"
)
func main() {
lang := strings.ToUpper(os.Getenv("LANG"))
if strings.Contains(lang, "UTF") {
fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
} else {
fmt.Println("This terminal does not support unicode")
}
}
| #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Unicode is supported on this terminal and U+25B3 is : \u25b3");
i = -1;
break;
}
}
if (i != -1)
printf ("Unicode is not supported on this terminal.");
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | 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;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.