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 "fmt"
func main() { fmt.Println("Hello world!") }
| const hello = "Hello world!\n"
print(hello)
|
Write a version of this Go function in C with identical behavior. | package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func printHelper(cat string, le, lim, max int) (int, int, string) {
cle, clim := commatize(le), commatize(lim)
if cat != "unsexy primes" {
cat = "sexy prime " + cat
}
fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle)
last := max
if le < last {
last = le
}
verb := "are"
if last == 1 {
verb = "is"
}
return le, last, verb
}
func main() {
lim := 1000035
sv := sieve(lim - 1)
var pairs [][2]int
var trips [][3]int
var quads [][4]int
var quins [][5]int
var unsexy = []int{2, 3}
for i := 3; i < lim; i += 2 {
if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] {
unsexy = append(unsexy, i)
continue
}
if i < lim-6 && !sv[i] && !sv[i+6] {
pair := [2]int{i, i + 6}
pairs = append(pairs, pair)
} else {
continue
}
if i < lim-12 && !sv[i+12] {
trip := [3]int{i, i + 6, i + 12}
trips = append(trips, trip)
} else {
continue
}
if i < lim-18 && !sv[i+18] {
quad := [4]int{i, i + 6, i + 12, i + 18}
quads = append(quads, quad)
} else {
continue
}
if i < lim-24 && !sv[i+24] {
quin := [5]int{i, i + 6, i + 12, i + 18, i + 24}
quins = append(quins, quin)
}
}
le, n, verb := printHelper("pairs", len(pairs), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, pairs[le-n:])
le, n, verb = printHelper("triplets", len(trips), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, trips[le-n:])
le, n, verb = printHelper("quadruplets", len(quads), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quads[le-n:])
le, n, verb = printHelper("quintuplets", len(quins), lim, 5)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quins[le-n:])
le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10)
fmt.Printf("The last %d %s:\n %v\n\n", n, verb, unsexy[le-n:])
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define TRUE 1
#define FALSE 0
typedef unsigned char bool;
void sieve(bool *c, int limit) {
int i, p = 3, p2;
c[0] = TRUE;
c[1] = TRUE;
for (;;) {
p2 = p * p;
if (p2 >= limit) {
break;
}
for (i = p2; i < limit; i += 2*p) {
c[i] = TRUE;
}
for (;;) {
p += 2;
if (!c[p]) {
break;
}
}
}
}
void printHelper(const char *cat, int len, int lim, int n) {
const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : "";
const char *verb = (len == 1) ? "is" : "are";
printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len);
printf("The last %d %s:\n", n, verb);
}
void printArray(int *a, int len) {
int i;
printf("[");
for (i = 0; i < len; ++i) printf("%d ", a[i]);
printf("\b]");
}
int main() {
int i, ix, n, lim = 1000035;
int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;
int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;
int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;
int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];
int last_un[10];
bool *sv = calloc(lim - 1, sizeof(bool));
setlocale(LC_NUMERIC, "");
sieve(sv, lim);
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
unsexy++;
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pairs++;
} else continue;
if (i < lim-12 && !sv[i+12]) {
trips++;
} else continue;
if (i < lim-18 && !sv[i+18]) {
quads++;
} else continue;
if (i < lim-24 && !sv[i+24]) {
quins++;
}
}
if (pairs < lpr) lpr = pairs;
if (trips < ltr) ltr = trips;
if (quads < lqd) lqd = quads;
if (quins < lqn) lqn = quins;
if (unsexy < lun) lun = unsexy;
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
un++;
if (un > unsexy - lun) {
last_un[un + lun - 1 - unsexy] = i;
}
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pr++;
if (pr > pairs - lpr) {
ix = pr + lpr - 1 - pairs;
last_pr[ix][0] = i; last_pr[ix][1] = i + 6;
}
} else continue;
if (i < lim-12 && !sv[i+12]) {
tr++;
if (tr > trips - ltr) {
ix = tr + ltr - 1 - trips;
last_tr[ix][0] = i; last_tr[ix][1] = i + 6;
last_tr[ix][2] = i + 12;
}
} else continue;
if (i < lim-18 && !sv[i+18]) {
qd++;
if (qd > quads - lqd) {
ix = qd + lqd - 1 - quads;
last_qd[ix][0] = i; last_qd[ix][1] = i + 6;
last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;
}
} else continue;
if (i < lim-24 && !sv[i+24]) {
qn++;
if (qn > quins - lqn) {
ix = qn + lqn - 1 - quins;
last_qn[ix][0] = i; last_qn[ix][1] = i + 6;
last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;
last_qn[ix][4] = i + 24;
}
}
}
printHelper("pairs", pairs, lim, lpr);
printf(" [");
for (i = 0; i < lpr; ++i) {
printArray(last_pr[i], 2);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("triplets", trips, lim, ltr);
printf(" [");
for (i = 0; i < ltr; ++i) {
printArray(last_tr[i], 3);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("quadruplets", quads, lim, lqd);
printf(" [");
for (i = 0; i < lqd; ++i) {
printArray(last_qd[i], 4);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("quintuplets", quins, lim, lqn);
printf(" [");
for (i = 0; i < lqn; ++i) {
printArray(last_qn[i], 5);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("unsexy primes", unsexy, lim, lun);
printf(" [");
printArray(last_un, lun);
printf("\b]\n");
free(sv);
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import "fmt"
func main() {
a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
fmt.Println(a)
fmt.Println(fd(a, 9))
}
func fd(a []int, ord int) []int {
for i := 0; i < ord; i++ {
for j := 0; j < len(a)-i-1; j++ {
a[j] = a[j+1] - a[j]
}
}
return a[:len(a)-ord]
}
| #include <stdlib.h>
#include <string.h>
#include <stdio.h>
double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
unsigned int i, j;
double* y;
if (order >= len) return 0;
y = malloc(sizeof(double) * len);
if (!order) {
memcpy(y, x, sizeof(double) * len);
return y;
}
for (j = 0; j < order; j++, x = y)
for (i = 0, len--; i < len; i++)
y[i] = x[i + 1] - x[i];
y = realloc(y, sizeof(double) * len);
return y;
}
int main(void)
{
double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
int i, len = sizeof(x) / sizeof(x[0]);
y = fwd_diff(x, len, 1);
for (i = 0; i < len - 1; i++)
printf("%g ", y[i]);
putchar('\n');
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | func IsPrime(n int) bool {
if n < 0 { n = -n }
switch {
case n == 2:
return true
case n < 2 || n % 2 == 0:
return false
default:
for i = 3; i*i <= n; i += 2 {
if n % i == 0 { return false }
}
}
return true
}
| int is_prime(unsigned int n)
{
unsigned int p;
if (!(n & 1) || n < 2 ) return n == 2;
for (p = 3; p <= n/p; p += 2)
if (!(n % p)) return 0;
return 1;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import "fmt"
import "math/big"
func main() {
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
}
| #include <stdio.h>
#include <limits.h>
static unsigned long gcd_ui(unsigned long x, unsigned long y) {
unsigned long t;
if (y < x) { t = x; x = y; y = t; }
while (y > 0) {
t = y; y = x % y; x = t;
}
return x;
}
unsigned long binomial(unsigned long n, unsigned long k) {
unsigned long d, g, r = 1;
if (k == 0) return 1;
if (k == 1) return n;
if (k >= n) return (k == n);
if (k > n/2) k = n-k;
for (d = 1; d <= k; d++) {
if (r >= ULONG_MAX/n) {
unsigned long nr, dr;
g = gcd_ui(n, d); nr = n/g; dr = d/g;
g = gcd_ui(r, dr); r = r/g; dr = dr/g;
if (r >= ULONG_MAX/nr) return 0;
r *= nr;
r /= dr;
n--;
} else {
r *= n--;
r /= d;
}
}
return r;
}
int main() {
printf("%lu\n", binomial(5, 3));
printf("%lu\n", binomial(40, 19));
printf("%lu\n", binomial(67, 31));
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import "fmt"
func main() {
var a []interface{}
a = append(a, 3)
a = append(a, "apples", "oranges")
fmt.Println(a)
}
| #define cSize( a ) ( sizeof(a)/sizeof(a[0]) )
int ar[10];
ar[0] = 1;
ar[1] = 2;
int* p;
for (p=ar;
p<(ar+cSize(ar));
p++) {
printf("%d\n",*p);
}
|
Port the provided Go code into C while preserving the original functionality. | start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
}
| struct link *first;
struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package raster
import (
"fmt"
"io"
"os"
)
func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
if _, err = fmt.Fprintln(w, "P6"); err != nil {
return
}
for _, c := range b.Comments {
if _, err = fmt.Fprintln(w, c); err != nil {
return
}
}
_, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
if err != nil {
return
}
b3 := make([]byte, 3*len(b.px))
n1 := 0
for _, px := range b.px {
b3[n1] = px.R
b3[n1+1] = px.G
b3[n1+2] = px.B
n1 += 3
}
if _, err = w.Write(b3); err != nil {
return
}
return
}
func (b *Bitmap) WritePpmFile(fn string) (err error) {
var f *os.File
if f, err = os.Create(fn); err != nil {
return
}
if err = b.WritePpmTo(f); err != nil {
return
}
return f.Close()
}
| #include <stdlib.h>
#include <stdio.h>
int main(void)
{
const int dimx = 800, dimy = 800;
int i, j;
FILE *fp = fopen("first.ppm", "wb");
(void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
for (j = 0; j < dimy; ++j)
{
for (i = 0; i < dimx; ++i)
{
static unsigned char color[3];
color[0] = i % 256;
color[1] = j % 256;
color[2] = (i * j) % 256;
(void) fwrite(color, 1, 3, fp);
}
}
(void) fclose(fp);
return EXIT_SUCCESS;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package raster
import (
"fmt"
"io"
"os"
)
func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
if _, err = fmt.Fprintln(w, "P6"); err != nil {
return
}
for _, c := range b.Comments {
if _, err = fmt.Fprintln(w, c); err != nil {
return
}
}
_, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
if err != nil {
return
}
b3 := make([]byte, 3*len(b.px))
n1 := 0
for _, px := range b.px {
b3[n1] = px.R
b3[n1+1] = px.G
b3[n1+2] = px.B
n1 += 3
}
if _, err = w.Write(b3); err != nil {
return
}
return
}
func (b *Bitmap) WritePpmFile(fn string) (err error) {
var f *os.File
if f, err = os.Create(fn); err != nil {
return
}
if err = b.WritePpmTo(f); err != nil {
return
}
return f.Close()
}
| #include <stdlib.h>
#include <stdio.h>
int main(void)
{
const int dimx = 800, dimy = 800;
int i, j;
FILE *fp = fopen("first.ppm", "wb");
(void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
for (j = 0; j < dimy; ++j)
{
for (i = 0; i < dimx; ++i)
{
static unsigned char color[3];
color[0] = i % 256;
color[1] = j % 256;
color[2] = (i * j) % 256;
(void) fwrite(color, 1, 3, fp);
}
}
(void) fclose(fp);
return EXIT_SUCCESS;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import "os"
func main() {
os.Remove("input.txt")
os.Remove("/input.txt")
os.Remove("docs")
os.Remove("/docs")
os.RemoveAll("docs")
os.RemoveAll("/docs")
}
| #include <stdio.h>
int main() {
remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs");
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package ddate
import (
"strconv"
"strings"
"time"
)
const (
DefaultFmt = "Pungenday, Discord 5, 3131 YOLD"
OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131
Celebrate Mojoday`
)
const (
protoLongSeason = "Discord"
protoShortSeason = "Dsc"
protoLongDay = "Pungenday"
protoShortDay = "PD"
protoOrdDay = "5"
protoCardDay = "5th"
protoHolyday = "Mojoday"
protoYear = "3131"
)
var (
longDay = []string{"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"}
shortDay = []string{"SM", "BT", "PD", "PP", "SO"}
longSeason = []string{
"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}
shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"}
holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"},
{"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}}
)
type DiscDate struct {
StTibs bool
Dayy int
Year int
}
func New(eris time.Time) DiscDate {
t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(),
eris.Second(), eris.Nanosecond(), eris.Location())
bob := int(eris.Sub(t).Hours()) / 24
raw := eris.Year()
hastur := DiscDate{Year: raw + 1166}
if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) {
if bob > 59 {
bob--
} else if bob == 59 {
hastur.StTibs = true
return hastur
}
}
hastur.Dayy = bob
return hastur
}
func (dd DiscDate) Format(f string) (r string) {
var st, snarf string
var dateElement bool
f6 := func(proto, wibble string) {
if !dateElement {
snarf = r
dateElement = true
}
if st > "" {
r = ""
} else {
r += wibble
}
f = f[len(proto):]
}
f4 := func(proto, wibble string) {
if dd.StTibs {
st = "St. Tib's Day"
}
f6(proto, wibble)
}
season, day := dd.Dayy/73, dd.Dayy%73
for f > "" {
switch {
case strings.HasPrefix(f, protoLongDay):
f4(protoLongDay, longDay[dd.Dayy%5])
case strings.HasPrefix(f, protoShortDay):
f4(protoShortDay, shortDay[dd.Dayy%5])
case strings.HasPrefix(f, protoCardDay):
funkychickens := "th"
if day/10 != 1 {
switch day % 10 {
case 0:
funkychickens = "st"
case 1:
funkychickens = "nd"
case 2:
funkychickens = "rd"
}
}
f4(protoCardDay, strconv.Itoa(day+1)+funkychickens)
case strings.HasPrefix(f, protoOrdDay):
f4(protoOrdDay, strconv.Itoa(day+1))
case strings.HasPrefix(f, protoLongSeason):
f6(protoLongSeason, longSeason[season])
case strings.HasPrefix(f, protoShortSeason):
f6(protoShortSeason, shortSeason[season])
case strings.HasPrefix(f, protoHolyday):
if day == 4 {
r += holyday[season][0]
} else if day == 49 {
r += holyday[season][1]
}
f = f[len(protoHolyday):]
case strings.HasPrefix(f, protoYear):
r += strconv.Itoa(dd.Year)
f = f[4:]
default:
r += f[:1]
f = f[1:]
}
}
if st > "" {
r = snarf + st + r
}
return
}
| #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\
(x) == 2 ? "Boomtime" :\
(x) == 3 ? "Pungenday" :\
(x) == 4 ? "Prickle-Prickle" :\
"Setting Orange")
#define season( x ) ((x) == 0 ? "Chaos" :\
(x) == 1 ? "Discord" :\
(x) == 2 ? "Confusion" :\
(x) == 3 ? "Bureaucracy" :\
"The Aftermath")
#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)
#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))
char * ddate( int y, int d ){
int dyear = 1166 + y;
char * result = malloc( 100 * sizeof( char ) );
if( leap_year( y ) ){
if( d == 60 ){
sprintf( result, "St. Tib's Day, YOLD %d", dyear );
return result;
} else if( d >= 60 ){
-- d;
}
}
sprintf( result, "%s, %s %d, YOLD %d",
day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );
return result;
}
int day_of_year( int y, int m, int d ){
int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for( ; m > 1; m -- ){
d += month_lengths[ m - 2 ];
if( m == 3 && leap_year( y ) ){
++ d;
}
}
return d;
}
int main( int argc, char * argv[] ){
time_t now;
struct tm * now_time;
int year, doy;
if( argc == 1 ){
now = time( NULL );
now_time = localtime( &now );
year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;
} else if( argc == 4 ){
year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );
}
char * result = ddate( year, doy );
puts( result );
free( result );
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var n int = 3
var moves int = 0
a := make([][]int, n)
for i := range a {
a[i] = make([]int, n)
for j := range a {
a[i][j] = rand.Intn(2)
}
}
b := make([][]int, len(a))
for i := range a {
b[i] = make([]int, len(a[i]))
copy(b[i], a[i])
}
for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {
b = flipCol(b, rand.Intn(n) + 1)
b = flipRow(b, rand.Intn(n) + 1)
}
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
var rc rune
var num int
for {
for{
fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n)
_, err := fmt.Scanf("%c%d", &rc, &num)
if err != nil {
fmt.Println(err)
continue
}
if num < 1 || num > n {
fmt.Println("Wrong command!")
continue
}
break
}
switch rc {
case 'c':
fmt.Printf("Column %v will be flipped\n", num)
flipCol(b, num)
case 'r':
fmt.Printf("Row %v will be flipped\n", num)
flipRow(b, num)
default:
fmt.Println("Wrong command!")
continue
}
moves++
fmt.Println("\nMoves taken: ", moves)
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
if compareSlices(a, b) {
fmt.Printf("Finished. You win with %d moves!\n", moves)
break
}
}
}
func drawBoard (m [][]int) {
fmt.Print(" ")
for i := range m {
fmt.Printf("%d ", i+1)
}
for i := range m {
fmt.Println()
fmt.Printf("%d ", i+1)
for _, val := range m[i] {
fmt.Printf(" %d", val)
}
}
fmt.Print("\n")
}
func flipRow(m [][]int, row int) ([][]int) {
for j := range m {
m[row-1][j] ^= 1
}
return m
}
func flipCol(m [][]int, col int) ([][]int) {
for j := range m {
m[j][col-1] ^= 1
}
return m
}
func compareSlices(m [][]int, n[][]int) bool {
o := true
for i := range m {
for j := range m {
if m[i][j] != n[i][j] { o = false }
}
}
return o
}
| #include <stdio.h>
#include <stdlib.h>
int i, j;
void fliprow(int **b, int sz, int n)
{
for(i = 0; i < sz; i++)
b[n+1][i] = !b[n+1][i];
}
void flipcol(int **b, int sz, int n)
{
for(i = 1; i <= sz; i++)
b[i][n] = !b[i][n];
}
void initt(int **t, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
t[i][j] = rand()%2;
}
void initb(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
b[i][j] = t[i][j];
for(i = 1; i <= sz; i++)
fliprow(b, sz, rand()%sz+1);
for(i = 0; i < sz; i++)
flipcol(b, sz, rand()%sz);
}
void printb(int **b, int sz)
{
printf(" ");
for(i = 0; i < sz; i++)
printf(" %d", i);
printf("\n");
for(i = 1; i <= sz; i++)
{
printf("%d", i-1);
for(j = 0; j < sz; j++)
printf(" %d", b[i][j]);
printf("\n");
}
printf("\n");
}
int eq(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
if(b[i][j] != t[i][j])
return 0;
return 1;
}
void main()
{
int sz = 3;
int eql = 0;
int mov = 0;
int **t = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
t[i] = malloc(sz*sizeof(int));
int **b = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
b[i] = malloc(sz*sizeof(int));
char roc;
int n;
initt(t, sz);
initb(t, b, sz);
while(eq(t, b, sz))
initb(t, b, sz);
while(!eql)
{
printf("Target: \n");
printb(t, sz);
printf("Board: \n");
printb(b, sz);
printf("What to flip: ");
scanf(" %c", &roc);
scanf(" %d", &n);
switch(roc)
{
case 'r':
fliprow(b, sz, n);
break;
case 'c':
flipcol(b, sz, n);
break;
default:
perror("Please specify r or c and an number");
break;
}
printf("Moves Taken: %d\n", ++mov);
if(eq(t, b, sz))
{
printf("You win!\n");
eql = 1;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var n int = 3
var moves int = 0
a := make([][]int, n)
for i := range a {
a[i] = make([]int, n)
for j := range a {
a[i][j] = rand.Intn(2)
}
}
b := make([][]int, len(a))
for i := range a {
b[i] = make([]int, len(a[i]))
copy(b[i], a[i])
}
for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {
b = flipCol(b, rand.Intn(n) + 1)
b = flipRow(b, rand.Intn(n) + 1)
}
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
var rc rune
var num int
for {
for{
fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n)
_, err := fmt.Scanf("%c%d", &rc, &num)
if err != nil {
fmt.Println(err)
continue
}
if num < 1 || num > n {
fmt.Println("Wrong command!")
continue
}
break
}
switch rc {
case 'c':
fmt.Printf("Column %v will be flipped\n", num)
flipCol(b, num)
case 'r':
fmt.Printf("Row %v will be flipped\n", num)
flipRow(b, num)
default:
fmt.Println("Wrong command!")
continue
}
moves++
fmt.Println("\nMoves taken: ", moves)
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
if compareSlices(a, b) {
fmt.Printf("Finished. You win with %d moves!\n", moves)
break
}
}
}
func drawBoard (m [][]int) {
fmt.Print(" ")
for i := range m {
fmt.Printf("%d ", i+1)
}
for i := range m {
fmt.Println()
fmt.Printf("%d ", i+1)
for _, val := range m[i] {
fmt.Printf(" %d", val)
}
}
fmt.Print("\n")
}
func flipRow(m [][]int, row int) ([][]int) {
for j := range m {
m[row-1][j] ^= 1
}
return m
}
func flipCol(m [][]int, col int) ([][]int) {
for j := range m {
m[j][col-1] ^= 1
}
return m
}
func compareSlices(m [][]int, n[][]int) bool {
o := true
for i := range m {
for j := range m {
if m[i][j] != n[i][j] { o = false }
}
}
return o
}
| #include <stdio.h>
#include <stdlib.h>
int i, j;
void fliprow(int **b, int sz, int n)
{
for(i = 0; i < sz; i++)
b[n+1][i] = !b[n+1][i];
}
void flipcol(int **b, int sz, int n)
{
for(i = 1; i <= sz; i++)
b[i][n] = !b[i][n];
}
void initt(int **t, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
t[i][j] = rand()%2;
}
void initb(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
b[i][j] = t[i][j];
for(i = 1; i <= sz; i++)
fliprow(b, sz, rand()%sz+1);
for(i = 0; i < sz; i++)
flipcol(b, sz, rand()%sz);
}
void printb(int **b, int sz)
{
printf(" ");
for(i = 0; i < sz; i++)
printf(" %d", i);
printf("\n");
for(i = 1; i <= sz; i++)
{
printf("%d", i-1);
for(j = 0; j < sz; j++)
printf(" %d", b[i][j]);
printf("\n");
}
printf("\n");
}
int eq(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
if(b[i][j] != t[i][j])
return 0;
return 1;
}
void main()
{
int sz = 3;
int eql = 0;
int mov = 0;
int **t = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
t[i] = malloc(sz*sizeof(int));
int **b = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
b[i] = malloc(sz*sizeof(int));
char roc;
int n;
initt(t, sz);
initb(t, b, sz);
while(eq(t, b, sz))
initb(t, b, sz);
while(!eql)
{
printf("Target: \n");
printb(t, sz);
printf("Board: \n");
printb(b, sz);
printf("What to flip: ");
scanf(" %c", &roc);
scanf(" %d", &n);
switch(roc)
{
case 'r':
fliprow(b, sz, n);
break;
case 'c':
flipcol(b, sz, n);
break;
default:
perror("Please specify r or c and an number");
break;
}
printf("Moves Taken: %d\n", ++mov);
if(eq(t, b, sz))
{
printf("You win!\n");
eql = 1;
}
}
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.Denom())
f.Sub(h, f.SetInt(&w))
y, _ := f.Float64()
d := fmt.Sprintf("%.3f", y)
fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n",
i, &w, d[1:], d[2] == '0' || d[2] == '9')
}
}
| #include <stdio.h>
#include <mpfr.h>
void h(int n)
{
MPFR_DECL_INIT(a, 200);
MPFR_DECL_INIT(b, 200);
mpfr_fac_ui(a, n, MPFR_RNDD);
mpfr_set_ui(b, 2, MPFR_RNDD);
mpfr_log(b, b, MPFR_RNDD);
mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);
mpfr_div(a, a, b, MPFR_RNDD);
mpfr_div_ui(a, a, 2, MPFR_RNDD);
mpfr_frac(b, a, MPFR_RNDD);
mpfr_printf("%2d: %23.4Rf %c\n", n, a,
mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}
int main(void)
{
int n;
for (n = 1; n <= 17; n++) h(n);
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.Denom())
f.Sub(h, f.SetInt(&w))
y, _ := f.Float64()
d := fmt.Sprintf("%.3f", y)
fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n",
i, &w, d[1:], d[2] == '0' || d[2] == '9')
}
}
| #include <stdio.h>
#include <mpfr.h>
void h(int n)
{
MPFR_DECL_INIT(a, 200);
MPFR_DECL_INIT(b, 200);
mpfr_fac_ui(a, n, MPFR_RNDD);
mpfr_set_ui(b, 2, MPFR_RNDD);
mpfr_log(b, b, MPFR_RNDD);
mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);
mpfr_div(a, a, b, MPFR_RNDD);
mpfr_div_ui(a, a, 2, MPFR_RNDD);
mpfr_frac(b, a, MPFR_RNDD);
mpfr_printf("%2d: %23.4Rf %c\n", n, a,
mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}
int main(void)
{
int n;
for (n = 1; n <= 17; n++) h(n);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"math/big"
)
func main() {
ln2, _ := new(big.Rat).SetString("0.6931471805599453094172")
h := big.NewRat(1, 2)
h.Quo(h, ln2)
var f big.Rat
var w big.Int
for i := int64(1); i <= 17; i++ {
h.Quo(h.Mul(h, f.SetInt64(i)), ln2)
w.Quo(h.Num(), h.Denom())
f.Sub(h, f.SetInt(&w))
y, _ := f.Float64()
d := fmt.Sprintf("%.3f", y)
fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n",
i, &w, d[1:], d[2] == '0' || d[2] == '9')
}
}
| #include <stdio.h>
#include <mpfr.h>
void h(int n)
{
MPFR_DECL_INIT(a, 200);
MPFR_DECL_INIT(b, 200);
mpfr_fac_ui(a, n, MPFR_RNDD);
mpfr_set_ui(b, 2, MPFR_RNDD);
mpfr_log(b, b, MPFR_RNDD);
mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);
mpfr_div(a, a, b, MPFR_RNDD);
mpfr_div_ui(a, a, 2, MPFR_RNDD);
mpfr_frac(b, a, MPFR_RNDD);
mpfr_printf("%2d: %23.4Rf %c\n", n, a,
mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}
int main(void)
{
int n;
for (n = 1; n <= 17; n++) h(n);
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
"math/rand"
)
const nmax = 20
func main() {
fmt.Println(" N average analytical (error)")
fmt.Println("=== ========= ============ =========")
for n := 1; n <= nmax; n++ {
a := avg(n)
b := ana(n)
fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n",
n, a, b, math.Abs(a-b)/b*100)
}
}
func avg(n int) float64 {
const tests = 1e4
sum := 0
for t := 0; t < tests; t++ {
var v [nmax]bool
for x := 0; !v[x]; x = rand.Intn(n) {
v[x] = true
sum++
}
}
return float64(sum) / tests
}
func ana(n int) float64 {
nn := float64(n)
term := 1.
sum := 1.
for i := nn - 1; i >= 1; i-- {
term *= i / nn
sum += term
}
return sum
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_N 20
#define TIMES 1000000
double factorial(int n) {
double f = 1;
int i;
for (i = 1; i <= n; i++) f *= i;
return f;
}
double expected(int n) {
double sum = 0;
int i;
for (i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
while ((r = rand()) >= rmax);
return r / (RAND_MAX / n);
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = 1 << randint(n);
}
}
return count;
}
int main(void) {
srand(time(0));
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
double avg = (double)cnt / TIMES;
double theory = expected(n);
double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff);
}
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math"
"math/rand"
)
const nmax = 20
func main() {
fmt.Println(" N average analytical (error)")
fmt.Println("=== ========= ============ =========")
for n := 1; n <= nmax; n++ {
a := avg(n)
b := ana(n)
fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n",
n, a, b, math.Abs(a-b)/b*100)
}
}
func avg(n int) float64 {
const tests = 1e4
sum := 0
for t := 0; t < tests; t++ {
var v [nmax]bool
for x := 0; !v[x]; x = rand.Intn(n) {
v[x] = true
sum++
}
}
return float64(sum) / tests
}
func ana(n int) float64 {
nn := float64(n)
term := 1.
sum := 1.
for i := nn - 1; i >= 1; i-- {
term *= i / nn
sum += term
}
return sum
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_N 20
#define TIMES 1000000
double factorial(int n) {
double f = 1;
int i;
for (i = 1; i <= n; i++) f *= i;
return f;
}
double expected(int n) {
double sum = 0;
int i;
for (i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
while ((r = rand()) >= rmax);
return r / (RAND_MAX / n);
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = 1 << randint(n);
}
}
return count;
}
int main(void) {
srand(time(0));
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
double avg = (double)cnt / TIMES;
double theory = expected(n);
double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff);
}
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
)
func main() {
str := "Mary had a %s lamb"
txt := "little"
out := fmt.Sprintf(str, txt)
fmt.Println(out)
}
| #include <stdio.h>
int main() {
const char *extra = "little";
printf("Mary had a %s lamb.\n", extra);
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"container/heap"
"sort"
)
type IntPile []int
func (self IntPile) Top() int { return self[len(self)-1] }
func (self *IntPile) Pop() int {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
type IntPilesHeap []IntPile
func (self IntPilesHeap) Len() int { return len(self) }
func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() }
func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) }
func (self *IntPilesHeap) Pop() interface{} {
x := (*self)[len(*self)-1]
*self = (*self)[:len(*self)-1]
return x
}
func patience_sort (n []int) {
var piles []IntPile
for _, x := range n {
j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x })
if j != len(piles) {
piles[j] = append(piles[j], x)
} else {
piles = append(piles, IntPile{ x })
}
}
hp := IntPilesHeap(piles)
heap.Init(&hp)
for i, _ := range n {
smallPile := heap.Pop(&hp).(IntPile)
n[i] = smallPile.Pop()
if len(smallPile) != 0 {
heap.Push(&hp, smallPile)
}
}
if len(hp) != 0 {
panic("something went wrong")
}
}
func main() {
a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1}
patience_sort(a)
fmt.Println(a)
}
| #include<stdlib.h>
#include<stdio.h>
int* patienceSort(int* arr,int size){
int decks[size][size],i,j,min,pickedRow;
int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int));
for(i=0;i<size;i++){
for(j=0;j<size;j++){
if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){
decks[j][count[j]] = arr[i];
count[j]++;
break;
}
}
}
min = decks[0][count[0]-1];
pickedRow = 0;
for(i=0;i<size;i++){
for(j=0;j<size;j++){
if(count[j]>0 && decks[j][count[j]-1]<min){
min = decks[j][count[j]-1];
pickedRow = j;
}
}
sortedArr[i] = min;
count[pickedRow]--;
for(j=0;j<size;j++)
if(count[j]>0){
min = decks[j][count[j]-1];
pickedRow = j;
break;
}
}
free(count);
free(decks);
return sortedArr;
}
int main(int argC,char* argV[])
{
int *arr, *sortedArr, i;
if(argC==0)
printf("Usage : %s <integers to be sorted separated by space>");
else{
arr = (int*)malloc((argC-1)*sizeof(int));
for(i=1;i<=argC;i++)
arr[i-1] = atoi(argV[i]);
sortedArr = patienceSort(arr,argC-1);
for(i=0;i<argC-1;i++)
printf("%d ",sortedArr[i]);
}
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
const bases = "ACGT"
func mutate(dna string, w [3]int) string {
le := len(dna)
p := rand.Intn(le)
r := rand.Intn(300)
bytes := []byte(dna)
switch {
case r < w[0]:
base := bases[rand.Intn(4)]
fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base)
bytes[p] = base
case r < w[0]+w[1]:
fmt.Printf(" Delete @%3d %q\n", p, bytes[p])
copy(bytes[p:], bytes[p+1:])
bytes = bytes[0 : le-1]
default:
base := bases[rand.Intn(4)]
bytes = append(bytes, 0)
copy(bytes[p+1:], bytes[p:])
fmt.Printf(" Insert @%3d %q\n", p, base)
bytes[p] = base
}
return string(bytes)
}
func generate(le int) string {
bytes := make([]byte, le)
for i := 0; i < le; i++ {
bytes[i] = bases[rand.Intn(4)]
}
return string(bytes)
}
func prettyPrint(dna string, rowLen int) {
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += rowLen {
k := i + rowLen
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======\n")
}
func wstring(w [3]int) string {
return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2])
}
func main() {
rand.Seed(time.Now().UnixNano())
dna := generate(250)
prettyPrint(dna, 50)
muts := 10
w := [3]int{100, 100, 100}
fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w))
fmt.Printf("MUTATIONS (%d):\n", muts)
for i := 0; i < muts; i++ {
dna = mutate(dna, w)
}
fmt.Println()
prettyPrint(dna, 50)
}
| #include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct genome{
char base;
struct genome *next;
}genome;
typedef struct{
char mutation;
int position;
}genomeChange;
typedef struct{
int adenineCount,thymineCount,cytosineCount,guanineCount;
}baseCounts;
genome *strand;
baseCounts baseData;
int genomeLength = 100, lineLength = 50;
int numDigits(int num){
int len = 1;
while(num>10){
num /= 10;
len++;
}
return len;
}
void generateStrand(){
int baseChoice = rand()%4, i;
genome *strandIterator, *newStrand;
baseData.adenineCount = 0;
baseData.thymineCount = 0;
baseData.cytosineCount = 0;
baseData.guanineCount = 0;
strand = (genome*)malloc(sizeof(genome));
strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
strand->next = NULL;
strandIterator = strand;
for(i=1;i<genomeLength;i++){
baseChoice = rand()%4;
newStrand = (genome*)malloc(sizeof(genome));
newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
newStrand->next = NULL;
strandIterator->next = newStrand;
strandIterator = newStrand;
}
}
genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){
int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);
genomeChange mutationCommand;
mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');
mutationCommand.position = rand()%genomeLength;
return mutationCommand;
}
void printGenome(){
int rows, width = numDigits(genomeLength), len = 0,i,j;
lineLength = (genomeLength<lineLength)?genomeLength:lineLength;
rows = genomeLength/lineLength + (genomeLength%lineLength!=0);
genome* strandIterator = strand;
printf("\n\nGenome : \n--------\n");
for(i=0;i<rows;i++){
printf("\n%*d%3s",width,len,":");
for(j=0;j<lineLength && strandIterator!=NULL;j++){
printf("%c",strandIterator->base);
strandIterator = strandIterator->next;
}
len += lineLength;
}
while(strandIterator!=NULL){
printf("%c",strandIterator->base);
strandIterator = strandIterator->next;
}
printf("\n\nBase Counts\n-----------");
printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount);
printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount);
printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount);
printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount);
printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);
printf("\n");
}
void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){
int i,j,width,baseChoice;
genomeChange newMutation;
genome *strandIterator, *strandFollower, *newStrand;
for(i=0;i<numMutations;i++){
strandIterator = strand;
strandFollower = strand;
newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);
width = numDigits(genomeLength);
for(j=0;j<newMutation.position;j++){
strandFollower = strandIterator;
strandIterator = strandIterator->next;
}
if(newMutation.mutation=='S'){
if(strandIterator->base=='A'){
strandIterator->base='T';
printf("\nSwapping A at position : %*d with T",width,newMutation.position);
}
else if(strandIterator->base=='A'){
strandIterator->base='T';
printf("\nSwapping A at position : %*d with T",width,newMutation.position);
}
else if(strandIterator->base=='C'){
strandIterator->base='G';
printf("\nSwapping C at position : %*d with G",width,newMutation.position);
}
else{
strandIterator->base='C';
printf("\nSwapping G at position : %*d with C",width,newMutation.position);
}
}
else if(newMutation.mutation=='I'){
baseChoice = rand()%4;
newStrand = (genome*)malloc(sizeof(genome));
newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position);
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
newStrand->next = strandIterator;
strandFollower->next = newStrand;
genomeLength++;
}
else{
strandFollower->next = strandIterator->next;
strandIterator->next = NULL;
printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position);
free(strandIterator);
genomeLength--;
}
}
}
int main(int argc,char* argv[])
{
int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;
if(argc==1||argc>6){
printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]);
return 0;
}
switch(argc){
case 2: genomeLength = atoi(argv[1]);
break;
case 3: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
break;
case 4: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
break;
case 5: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
insertWeight = atoi(argv[4]);
break;
case 6: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
insertWeight = atoi(argv[4]);
deleteWeight = atoi(argv[5]);
break;
};
srand(time(NULL));
generateStrand();
printf("\nOriginal:");
printGenome();
mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);
printf("\n\nMutated:");
printGenome();
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
const bases = "ACGT"
func mutate(dna string, w [3]int) string {
le := len(dna)
p := rand.Intn(le)
r := rand.Intn(300)
bytes := []byte(dna)
switch {
case r < w[0]:
base := bases[rand.Intn(4)]
fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base)
bytes[p] = base
case r < w[0]+w[1]:
fmt.Printf(" Delete @%3d %q\n", p, bytes[p])
copy(bytes[p:], bytes[p+1:])
bytes = bytes[0 : le-1]
default:
base := bases[rand.Intn(4)]
bytes = append(bytes, 0)
copy(bytes[p+1:], bytes[p:])
fmt.Printf(" Insert @%3d %q\n", p, base)
bytes[p] = base
}
return string(bytes)
}
func generate(le int) string {
bytes := make([]byte, le)
for i := 0; i < le; i++ {
bytes[i] = bases[rand.Intn(4)]
}
return string(bytes)
}
func prettyPrint(dna string, rowLen int) {
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += rowLen {
k := i + rowLen
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======\n")
}
func wstring(w [3]int) string {
return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2])
}
func main() {
rand.Seed(time.Now().UnixNano())
dna := generate(250)
prettyPrint(dna, 50)
muts := 10
w := [3]int{100, 100, 100}
fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w))
fmt.Printf("MUTATIONS (%d):\n", muts)
for i := 0; i < muts; i++ {
dna = mutate(dna, w)
}
fmt.Println()
prettyPrint(dna, 50)
}
| #include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct genome{
char base;
struct genome *next;
}genome;
typedef struct{
char mutation;
int position;
}genomeChange;
typedef struct{
int adenineCount,thymineCount,cytosineCount,guanineCount;
}baseCounts;
genome *strand;
baseCounts baseData;
int genomeLength = 100, lineLength = 50;
int numDigits(int num){
int len = 1;
while(num>10){
num /= 10;
len++;
}
return len;
}
void generateStrand(){
int baseChoice = rand()%4, i;
genome *strandIterator, *newStrand;
baseData.adenineCount = 0;
baseData.thymineCount = 0;
baseData.cytosineCount = 0;
baseData.guanineCount = 0;
strand = (genome*)malloc(sizeof(genome));
strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
strand->next = NULL;
strandIterator = strand;
for(i=1;i<genomeLength;i++){
baseChoice = rand()%4;
newStrand = (genome*)malloc(sizeof(genome));
newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
newStrand->next = NULL;
strandIterator->next = newStrand;
strandIterator = newStrand;
}
}
genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){
int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);
genomeChange mutationCommand;
mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');
mutationCommand.position = rand()%genomeLength;
return mutationCommand;
}
void printGenome(){
int rows, width = numDigits(genomeLength), len = 0,i,j;
lineLength = (genomeLength<lineLength)?genomeLength:lineLength;
rows = genomeLength/lineLength + (genomeLength%lineLength!=0);
genome* strandIterator = strand;
printf("\n\nGenome : \n--------\n");
for(i=0;i<rows;i++){
printf("\n%*d%3s",width,len,":");
for(j=0;j<lineLength && strandIterator!=NULL;j++){
printf("%c",strandIterator->base);
strandIterator = strandIterator->next;
}
len += lineLength;
}
while(strandIterator!=NULL){
printf("%c",strandIterator->base);
strandIterator = strandIterator->next;
}
printf("\n\nBase Counts\n-----------");
printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount);
printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount);
printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount);
printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount);
printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);
printf("\n");
}
void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){
int i,j,width,baseChoice;
genomeChange newMutation;
genome *strandIterator, *strandFollower, *newStrand;
for(i=0;i<numMutations;i++){
strandIterator = strand;
strandFollower = strand;
newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);
width = numDigits(genomeLength);
for(j=0;j<newMutation.position;j++){
strandFollower = strandIterator;
strandIterator = strandIterator->next;
}
if(newMutation.mutation=='S'){
if(strandIterator->base=='A'){
strandIterator->base='T';
printf("\nSwapping A at position : %*d with T",width,newMutation.position);
}
else if(strandIterator->base=='A'){
strandIterator->base='T';
printf("\nSwapping A at position : %*d with T",width,newMutation.position);
}
else if(strandIterator->base=='C'){
strandIterator->base='G';
printf("\nSwapping C at position : %*d with G",width,newMutation.position);
}
else{
strandIterator->base='C';
printf("\nSwapping G at position : %*d with C",width,newMutation.position);
}
}
else if(newMutation.mutation=='I'){
baseChoice = rand()%4;
newStrand = (genome*)malloc(sizeof(genome));
newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position);
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
newStrand->next = strandIterator;
strandFollower->next = newStrand;
genomeLength++;
}
else{
strandFollower->next = strandIterator->next;
strandIterator->next = NULL;
printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position);
free(strandIterator);
genomeLength--;
}
}
}
int main(int argc,char* argv[])
{
int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;
if(argc==1||argc>6){
printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]);
return 0;
}
switch(argc){
case 2: genomeLength = atoi(argv[1]);
break;
case 3: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
break;
case 4: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
break;
case 5: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
insertWeight = atoi(argv[4]);
break;
case 6: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
insertWeight = atoi(argv[4]);
deleteWeight = atoi(argv[5]);
break;
};
srand(time(NULL));
generateStrand();
printf("\nOriginal:");
printGenome();
mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);
printf("\n\nMutated:");
printGenome();
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
const bases = "ACGT"
func mutate(dna string, w [3]int) string {
le := len(dna)
p := rand.Intn(le)
r := rand.Intn(300)
bytes := []byte(dna)
switch {
case r < w[0]:
base := bases[rand.Intn(4)]
fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base)
bytes[p] = base
case r < w[0]+w[1]:
fmt.Printf(" Delete @%3d %q\n", p, bytes[p])
copy(bytes[p:], bytes[p+1:])
bytes = bytes[0 : le-1]
default:
base := bases[rand.Intn(4)]
bytes = append(bytes, 0)
copy(bytes[p+1:], bytes[p:])
fmt.Printf(" Insert @%3d %q\n", p, base)
bytes[p] = base
}
return string(bytes)
}
func generate(le int) string {
bytes := make([]byte, le)
for i := 0; i < le; i++ {
bytes[i] = bases[rand.Intn(4)]
}
return string(bytes)
}
func prettyPrint(dna string, rowLen int) {
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += rowLen {
k := i + rowLen
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======\n")
}
func wstring(w [3]int) string {
return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2])
}
func main() {
rand.Seed(time.Now().UnixNano())
dna := generate(250)
prettyPrint(dna, 50)
muts := 10
w := [3]int{100, 100, 100}
fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w))
fmt.Printf("MUTATIONS (%d):\n", muts)
for i := 0; i < muts; i++ {
dna = mutate(dna, w)
}
fmt.Println()
prettyPrint(dna, 50)
}
| #include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct genome{
char base;
struct genome *next;
}genome;
typedef struct{
char mutation;
int position;
}genomeChange;
typedef struct{
int adenineCount,thymineCount,cytosineCount,guanineCount;
}baseCounts;
genome *strand;
baseCounts baseData;
int genomeLength = 100, lineLength = 50;
int numDigits(int num){
int len = 1;
while(num>10){
num /= 10;
len++;
}
return len;
}
void generateStrand(){
int baseChoice = rand()%4, i;
genome *strandIterator, *newStrand;
baseData.adenineCount = 0;
baseData.thymineCount = 0;
baseData.cytosineCount = 0;
baseData.guanineCount = 0;
strand = (genome*)malloc(sizeof(genome));
strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
strand->next = NULL;
strandIterator = strand;
for(i=1;i<genomeLength;i++){
baseChoice = rand()%4;
newStrand = (genome*)malloc(sizeof(genome));
newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
newStrand->next = NULL;
strandIterator->next = newStrand;
strandIterator = newStrand;
}
}
genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){
int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight);
genomeChange mutationCommand;
mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D');
mutationCommand.position = rand()%genomeLength;
return mutationCommand;
}
void printGenome(){
int rows, width = numDigits(genomeLength), len = 0,i,j;
lineLength = (genomeLength<lineLength)?genomeLength:lineLength;
rows = genomeLength/lineLength + (genomeLength%lineLength!=0);
genome* strandIterator = strand;
printf("\n\nGenome : \n--------\n");
for(i=0;i<rows;i++){
printf("\n%*d%3s",width,len,":");
for(j=0;j<lineLength && strandIterator!=NULL;j++){
printf("%c",strandIterator->base);
strandIterator = strandIterator->next;
}
len += lineLength;
}
while(strandIterator!=NULL){
printf("%c",strandIterator->base);
strandIterator = strandIterator->next;
}
printf("\n\nBase Counts\n-----------");
printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount);
printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount);
printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount);
printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount);
printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount);
printf("\n");
}
void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){
int i,j,width,baseChoice;
genomeChange newMutation;
genome *strandIterator, *strandFollower, *newStrand;
for(i=0;i<numMutations;i++){
strandIterator = strand;
strandFollower = strand;
newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight);
width = numDigits(genomeLength);
for(j=0;j<newMutation.position;j++){
strandFollower = strandIterator;
strandIterator = strandIterator->next;
}
if(newMutation.mutation=='S'){
if(strandIterator->base=='A'){
strandIterator->base='T';
printf("\nSwapping A at position : %*d with T",width,newMutation.position);
}
else if(strandIterator->base=='A'){
strandIterator->base='T';
printf("\nSwapping A at position : %*d with T",width,newMutation.position);
}
else if(strandIterator->base=='C'){
strandIterator->base='G';
printf("\nSwapping C at position : %*d with G",width,newMutation.position);
}
else{
strandIterator->base='C';
printf("\nSwapping G at position : %*d with C",width,newMutation.position);
}
}
else if(newMutation.mutation=='I'){
baseChoice = rand()%4;
newStrand = (genome*)malloc(sizeof(genome));
newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G'));
printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position);
baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++));
newStrand->next = strandIterator;
strandFollower->next = newStrand;
genomeLength++;
}
else{
strandFollower->next = strandIterator->next;
strandIterator->next = NULL;
printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position);
free(strandIterator);
genomeLength--;
}
}
}
int main(int argc,char* argv[])
{
int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10;
if(argc==1||argc>6){
printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]);
return 0;
}
switch(argc){
case 2: genomeLength = atoi(argv[1]);
break;
case 3: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
break;
case 4: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
break;
case 5: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
insertWeight = atoi(argv[4]);
break;
case 6: genomeLength = atoi(argv[1]);
numMutations = atoi(argv[2]);
swapWeight = atoi(argv[3]);
insertWeight = atoi(argv[4]);
deleteWeight = atoi(argv[5]);
break;
};
srand(time(NULL));
generateStrand();
printf("\nOriginal:");
printGenome();
mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight);
printf("\n\nMutated:");
printGenome();
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The first 100 tau numbers are:")
count := 0
i := 1
for count < 100 {
tf := countDivisors(i)
if i%tf == 0 {
fmt.Printf("%4d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
i++
}
}
| #include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
unsigned int p;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
int main() {
const unsigned int limit = 100;
unsigned int count = 0;
unsigned int n;
printf("The first %d tau numbers are:\n", limit);
for (n = 1; count < limit; ++n) {
if (n % divisor_count(n) == 0) {
printf("%6d", n);
++count;
if (count % 10 == 0) {
printf("\n");
}
}
}
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
double det_in(double **in, int n, int perm)
{
if (n == 1) return in[0][0];
double sum = 0, *m[--n];
for (int i = 0; i < n; i++)
m[i] = in[i + 1] + 1;
for (int i = 0, sgn = 1; i <= n; i++) {
sum += sgn * (in[i][0] * det_in(m, n, perm));
if (i == n) break;
m[i] = in[i] + 1;
if (!perm) sgn = -sgn;
}
return sum;
}
double det(double *in, int n, int perm)
{
double *m[n];
for (int i = 0; i < n; i++)
m[i] = in + (n * i);
return det_in(m, n, perm);
}
int main(void)
{
double x[] = { 0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19,
20, 21, 22, 23, 24 };
printf("det: %14.12g\n", det(x, 5, 0));
printf("perm: %14.12g\n", det(x, 5, 1));
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
double det_in(double **in, int n, int perm)
{
if (n == 1) return in[0][0];
double sum = 0, *m[--n];
for (int i = 0; i < n; i++)
m[i] = in[i + 1] + 1;
for (int i = 0, sgn = 1; i <= n; i++) {
sum += sgn * (in[i][0] * det_in(m, n, perm));
if (i == n) break;
m[i] = in[i] + 1;
if (!perm) sgn = -sgn;
}
return sum;
}
double det(double *in, int n, int perm)
{
double *m[n];
for (int i = 0; i < n; i++)
m[i] = in + (n * i);
return det_in(m, n, perm);
}
int main(void)
{
double x[] = { 0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19,
20, 21, 22, 23, 24 };
printf("det: %14.12g\n", det(x, 5, 0));
printf("perm: %14.12g\n", det(x, 5, 1));
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"math/big"
"time"
)
var p []*big.Int
var pd []int
func partDiffDiff(n int) int {
if n&1 == 1 {
return (n + 1) / 2
}
return n + 1
}
func partDiff(n int) int {
if n < 2 {
return 1
}
pd[n] = pd[n-1] + partDiffDiff(n-1)
return pd[n]
}
func partitionsP(n int) {
if n < 2 {
return
}
psum := new(big.Int)
for i := 1; i <= n; i++ {
pdi := partDiff(i)
if pdi > n {
break
}
sign := int64(-1)
if (i-1)%4 < 2 {
sign = 1
}
t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign))
psum.Add(psum, t)
}
p[n] = psum
}
func main() {
start := time.Now()
const N = 6666
p = make([]*big.Int, N+1)
pd = make([]int, N+1)
p[0], pd[0] = big.NewInt(1), 1
p[1], pd[1] = big.NewInt(1), 1
for n := 2; n <= N; n++ {
partitionsP(n)
}
fmt.Printf("p[%d)] = %d\n", N, p[N])
fmt.Printf("Took %s\n", time.Since(start))
}
| #include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <gmp.h>
mpz_t* partition(uint64_t n) {
mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));
mpz_init_set_ui(pn[0], 1);
mpz_init_set_ui(pn[1], 1);
for (uint64_t i = 2; i < n + 2; i ++) {
mpz_init(pn[i]);
for (uint64_t k = 1, penta; ; k++) {
penta = k * (3 * k - 1) >> 1;
if (penta >= i) break;
if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
else mpz_sub(pn[i], pn[i], pn[i - penta]);
penta += k;
if (penta >= i) break;
if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
else mpz_sub(pn[i], pn[i], pn[i - penta]);
}
}
mpz_t *tmp = &pn[n + 1];
for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);
free(pn);
return tmp;
}
int main(int argc, char const *argv[]) {
clock_t start = clock();
mpz_t *p = partition(6666);
gmp_printf("%Zd\n", p);
printf("Elapsed time: %.04f seconds\n",
(double)(clock() - start) / (double)CLOCKS_PER_SEC);
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
)
var rows, cols int
var rx, cx int
var mn []int
func main() {
src, err := ioutil.ReadFile("ww.config")
if err != nil {
fmt.Println(err)
return
}
srcRows := bytes.Split(src, []byte{'\n'})
rows = len(srcRows)
for _, r := range srcRows {
if len(r) > cols {
cols = len(r)
}
}
rx, cx = rows+2, cols+2
mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}
odd := make([]byte, rx*cx)
even := make([]byte, rx*cx)
for ri, r := range srcRows {
copy(odd[(ri+1)*cx+1:], r)
}
for {
print(odd)
step(even, odd)
fmt.Scanln()
print(even)
step(odd, even)
fmt.Scanln()
}
}
func print(grid []byte) {
fmt.Println(strings.Repeat("__", cols))
fmt.Println()
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
if grid[r*cx+c] == 0 {
fmt.Print(" ")
} else {
fmt.Printf(" %c", grid[r*cx+c])
}
}
fmt.Println()
}
}
func step(dst, src []byte) {
for r := 1; r <= rows; r++ {
for c := 1; c <= cols; c++ {
x := r*cx + c
dst[x] = src[x]
switch dst[x] {
case 'H':
dst[x] = 't'
case 't':
dst[x] = '.'
case '.':
var nn int
for _, n := range mn {
if src[x+n] == 'H' {
nn++
}
}
if nn == 1 || nn == 2 {
dst[x] = 'H'
}
}
}
}
}
|
#define ANIMATE_VT100_POSIX
#include <stdio.h>
#include <string.h>
#ifdef ANIMATE_VT100_POSIX
#include <time.h>
#endif
char world_7x14[2][512] = {
{
"+-----------+\n"
"|tH.........|\n"
"|. . |\n"
"| ... |\n"
"|. . |\n"
"|Ht.. ......|\n"
"+-----------+\n"
}
};
void next_world(const char *in, char *out, int w, int h)
{
int i;
for (i = 0; i < w*h; i++) {
switch (in[i]) {
case ' ': out[i] = ' '; break;
case 't': out[i] = '.'; break;
case 'H': out[i] = 't'; break;
case '.': {
int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') +
(in[i-1] == 'H') + (in[i+1] == 'H') +
(in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H');
out[i] = (hc == 1 || hc == 2) ? 'H' : '.';
break;
}
default:
out[i] = in[i];
}
}
out[i] = in[i];
}
int main()
{
int f;
for (f = 0; ; f = 1 - f) {
puts(world_7x14[f]);
next_world(world_7x14[f], world_7x14[1-f], 14, 7);
#ifdef ANIMATE_VT100_POSIX
printf("\x1b[%dA", 8);
printf("\x1b[%dD", 14);
{
static const struct timespec ts = { 0, 100000000 };
nanosleep(&ts, 0);
}
#endif
}
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"math"
)
type xy struct {
x, y float64
}
type seg struct {
p1, p2 xy
}
type poly struct {
name string
sides []seg
}
func inside(pt xy, pg poly) (i bool) {
for _, side := range pg.sides {
if rayIntersectsSegment(pt, side) {
i = !i
}
}
return
}
func rayIntersectsSegment(p xy, s seg) bool {
var a, b xy
if s.p1.y < s.p2.y {
a, b = s.p1, s.p2
} else {
a, b = s.p2, s.p1
}
for p.y == a.y || p.y == b.y {
p.y = math.Nextafter(p.y, math.Inf(1))
}
if p.y < a.y || p.y > b.y {
return false
}
if a.x > b.x {
if p.x > a.x {
return false
}
if p.x < b.x {
return true
}
} else {
if p.x > b.x {
return false
}
if p.x < a.x {
return true
}
}
return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)
}
var (
p1 = xy{0, 0}
p2 = xy{10, 0}
p3 = xy{10, 10}
p4 = xy{0, 10}
p5 = xy{2.5, 2.5}
p6 = xy{7.5, 2.5}
p7 = xy{7.5, 7.5}
p8 = xy{2.5, 7.5}
p9 = xy{0, 5}
p10 = xy{10, 5}
p11 = xy{3, 0}
p12 = xy{7, 0}
p13 = xy{7, 10}
p14 = xy{3, 10}
)
var tpg = []poly{
{"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},
{"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},
{p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},
{"strange", []seg{{p1, p5},
{p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},
{"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13},
{p13, p14}, {p14, p9}, {p9, p11}}},
}
var tpt = []xy{
{5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},
{1, 2}, {2, 1},
}
func main() {
for _, pg := range tpg {
fmt.Printf("%s:\n", pg.name)
for _, pt := range tpt {
fmt.Println(pt, inside(pt, pg))
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;
#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}
#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }
BIN_V(sub, a.x - b.x, a.y - b.y);
BIN_V(add, a.x + b.x, a.y + b.y);
BIN_S(dot, a.x * b.x + a.y * b.y);
BIN_S(cross, a.x * b.y - a.y * b.x);
vec vmadd(vec a, double s, vec b)
{
vec c;
c.x = a.x + s * b.x;
c.y = a.y + s * b.y;
return c;
}
int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect)
{
vec dx = vsub(x1, x0), dy = vsub(y1, y0);
double d = vcross(dy, dx), a;
if (!d) return 0;
a = (vcross(x0, dx) - vcross(y0, dx)) / d;
if (sect)
*sect = vmadd(y0, a, dy);
if (a < -tol || a > 1 + tol) return -1;
if (a < tol || a > 1 - tol) return 0;
a = (vcross(x0, dy) - vcross(y0, dy)) / d;
if (a < 0 || a > 1) return -1;
return 1;
}
double dist(vec x, vec y0, vec y1, double tol)
{
vec dy = vsub(y1, y0);
vec x1, s;
int r;
x1.x = x.x + dy.y; x1.y = x.y - dy.x;
r = intersect(x, x1, y0, y1, tol, &s);
if (r == -1) return HUGE_VAL;
s = vsub(s, x);
return sqrt(vdot(s, s));
}
#define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++)
int inside(vec v, polygon p, double tol)
{
int i, k, crosses, intersectResult;
vec *pv;
double min_x, max_x, min_y, max_y;
for (i = 0; i < p->n; i++) {
k = (i + 1) % p->n;
min_x = dist(v, p->v[i], p->v[k], tol);
if (min_x < tol) return 0;
}
min_x = max_x = p->v[0].x;
min_y = max_y = p->v[1].y;
for_v(i, pv, p) {
if (pv->x > max_x) max_x = pv->x;
if (pv->x < min_x) min_x = pv->x;
if (pv->y > max_y) max_y = pv->y;
if (pv->y < min_y) min_y = pv->y;
}
if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y)
return -1;
max_x -= min_x; max_x *= 2;
max_y -= min_y; max_y *= 2;
max_x += max_y;
vec e;
while (1) {
crosses = 0;
e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x;
e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x;
for (i = 0; i < p->n; i++) {
k = (i + 1) % p->n;
intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0);
if (!intersectResult) break;
if (intersectResult == 1) crosses++;
}
if (i == p->n) break;
}
return (crosses & 1) ? 1 : -1;
}
int main()
{
vec vsq[] = { {0,0}, {10,0}, {10,10}, {0,10},
{2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}};
polygon_t sq = { 4, vsq },
sq_hole = { 8, vsq };
vec c = { 10, 5 };
vec d = { 5, 5 };
printf("%d\n", inside(c, &sq, 1e-10));
printf("%d\n", inside(c, &sq_hole, 1e-10));
printf("%d\n", inside(d, &sq, 1e-10));
printf("%d\n", inside(d, &sq_hole, 1e-10));
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"math"
)
const bCoeff = 7
type pt struct{ x, y float64 }
func zero() pt {
return pt{math.Inf(1), math.Inf(1)}
}
func is_zero(p pt) bool {
return p.x > 1e20 || p.x < -1e20
}
func neg(p pt) pt {
return pt{p.x, -p.y}
}
func dbl(p pt) pt {
if is_zero(p) {
return p
}
L := (3 * p.x * p.x) / (2 * p.y)
x := L*L - 2*p.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func add(p, q pt) pt {
if p.x == q.x && p.y == q.y {
return dbl(p)
}
if is_zero(p) {
return q
}
if is_zero(q) {
return p
}
L := (q.y - p.y) / (q.x - p.x)
x := L*L - p.x - q.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func mul(p pt, n int) pt {
r := zero()
for i := 1; i <= n; i <<= 1 {
if i&n != 0 {
r = add(r, p)
}
p = dbl(p)
}
return r
}
func show(s string, p pt) {
fmt.Printf("%s", s)
if is_zero(p) {
fmt.Println("Zero")
} else {
fmt.Printf("(%.3f, %.3f)\n", p.x, p.y)
}
}
func from_y(y float64) pt {
return pt{
x: math.Cbrt(y*y - bCoeff),
y: y,
}
}
func main() {
a := from_y(1)
b := from_y(2)
show("a = ", a)
show("b = ", b)
c := add(a, b)
show("c = a + b = ", c)
d := neg(c)
show("d = -c = ", d)
show("c + d = ", add(c, d))
show("a + b + d = ", add(a, add(b, d)))
show("a * 12345 = ", mul(a, 12345))
}
| #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x) / (2 * p.y);
r.x = L * L - 2 * p.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt add(pt p, pt q) {
if (p.x == q.x && p.y == q.y) return dbl(p);
if (is_zero(p)) return q;
if (is_zero(q)) return p;
pt r;
double L = (q.y - p.y) / (q.x - p.x);
r.x = L * L - p.x - q.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt mul(pt p, int n) {
int i;
pt r = zero();
for (i = 1; i <= n; i <<= 1) {
if (i & n) r = add(r, p);
p = dbl(p);
}
return r;
}
void show(const char *s, pt p) {
printf("%s", s);
printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y);
}
pt from_y(double y) {
pt r;
r.x = pow(y * y - C, 1.0/3);
r.y = y;
return r;
}
int main(void) {
pt a, b, c, d;
a = from_y(1);
b = from_y(2);
show("a = ", a);
show("b = ", b);
show("c = a + b = ", c = add(a, b));
show("d = -c = ", d = neg(c));
show("c + d = ", add(c, d));
show("a + b + d = ", add(a, add(b, d)));
show("a * 12345 = ", mul(a, 12345));
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"math"
)
const bCoeff = 7
type pt struct{ x, y float64 }
func zero() pt {
return pt{math.Inf(1), math.Inf(1)}
}
func is_zero(p pt) bool {
return p.x > 1e20 || p.x < -1e20
}
func neg(p pt) pt {
return pt{p.x, -p.y}
}
func dbl(p pt) pt {
if is_zero(p) {
return p
}
L := (3 * p.x * p.x) / (2 * p.y)
x := L*L - 2*p.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func add(p, q pt) pt {
if p.x == q.x && p.y == q.y {
return dbl(p)
}
if is_zero(p) {
return q
}
if is_zero(q) {
return p
}
L := (q.y - p.y) / (q.x - p.x)
x := L*L - p.x - q.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func mul(p pt, n int) pt {
r := zero()
for i := 1; i <= n; i <<= 1 {
if i&n != 0 {
r = add(r, p)
}
p = dbl(p)
}
return r
}
func show(s string, p pt) {
fmt.Printf("%s", s)
if is_zero(p) {
fmt.Println("Zero")
} else {
fmt.Printf("(%.3f, %.3f)\n", p.x, p.y)
}
}
func from_y(y float64) pt {
return pt{
x: math.Cbrt(y*y - bCoeff),
y: y,
}
}
func main() {
a := from_y(1)
b := from_y(2)
show("a = ", a)
show("b = ", b)
c := add(a, b)
show("c = a + b = ", c)
d := neg(c)
show("d = -c = ", d)
show("c + d = ", add(c, d))
show("a + b + d = ", add(a, add(b, d)))
show("a * 12345 = ", mul(a, 12345))
}
| #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x) / (2 * p.y);
r.x = L * L - 2 * p.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt add(pt p, pt q) {
if (p.x == q.x && p.y == q.y) return dbl(p);
if (is_zero(p)) return q;
if (is_zero(q)) return p;
pt r;
double L = (q.y - p.y) / (q.x - p.x);
r.x = L * L - p.x - q.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt mul(pt p, int n) {
int i;
pt r = zero();
for (i = 1; i <= n; i <<= 1) {
if (i & n) r = add(r, p);
p = dbl(p);
}
return r;
}
void show(const char *s, pt p) {
printf("%s", s);
printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y);
}
pt from_y(double y) {
pt r;
r.x = pow(y * y - C, 1.0/3);
r.y = y;
return r;
}
int main(void) {
pt a, b, c, d;
a = from_y(1);
b = from_y(2);
show("a = ", a);
show("b = ", b);
show("c = a + b = ", c = add(a, b));
show("d = -c = ", d = neg(c));
show("c + d = ", add(c, d));
show("a + b + d = ", add(a, add(b, d)));
show("a * 12345 = ", mul(a, 12345));
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th"))
fmt.Println(strings.Count("ababababab", "abab"))
}
| #include <stdio.h>
#include <string.h>
int match(const char *s, const char *p, int overlap)
{
int c = 0, l = strlen(p);
while (*s != '\0') {
if (strncmp(s++, p, l)) continue;
if (!overlap) s += l - 1;
c++;
}
return c;
}
int main()
{
printf("%d\n", match("the three truths", "th", 0));
printf("overlap:%d\n", match("abababababa", "aba", 1));
printf("not: %d\n", match("abababababa", "aba", 0));
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"sort"
"strconv"
)
func combrep(n int, lst []byte) [][]byte {
if n == 0 {
return [][]byte{nil}
}
if len(lst) == 0 {
return nil
}
r := combrep(n, lst[1:])
for _, x := range combrep(n-1, lst) {
r = append(r, append(x, lst[0]))
}
return r
}
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
return
}
for i := index; i < n; i++ {
check := shouldSwap(s, index, i)
if check {
s[index], s[i] = s[i], s[index]
findPerms(s, index+1, n, res)
s[index], s[i] = s[i], s[index]
}
}
}
func main() {
primes := []byte{2, 3, 5, 7}
var res []string
for n := 3; n <= 6; n++ {
reps := combrep(n, primes)
for _, rep := range reps {
sum := byte(0)
for _, r := range rep {
sum += r
}
if sum == 13 {
var perms []string
for i := 0; i < len(rep); i++ {
rep[i] += 48
}
findPerms(rep, 0, len(rep), &perms)
res = append(res, perms...)
}
}
}
res2 := make([]int, len(res))
for i, r := range res {
res2[i], _ = strconv.Atoi(r)
}
sort.Ints(res2)
fmt.Println("Those numbers whose digits are all prime and sum to 13 are:")
fmt.Println(res2)
}
| #include <stdbool.h>
#include <stdio.h>
bool primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
switch (r) {
case 2:
case 3:
case 5:
case 7:
break;
default:
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
int main() {
int i, c;
c = 0;
for (i = 1; i < 1000000; i++) {
if (primeDigitsSum13(i)) {
printf("%6d ", i);
if (c++ == 10) {
c = 0;
printf("\n");
}
}
}
printf("\n");
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"sort"
"strconv"
)
func combrep(n int, lst []byte) [][]byte {
if n == 0 {
return [][]byte{nil}
}
if len(lst) == 0 {
return nil
}
r := combrep(n, lst[1:])
for _, x := range combrep(n-1, lst) {
r = append(r, append(x, lst[0]))
}
return r
}
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
return
}
for i := index; i < n; i++ {
check := shouldSwap(s, index, i)
if check {
s[index], s[i] = s[i], s[index]
findPerms(s, index+1, n, res)
s[index], s[i] = s[i], s[index]
}
}
}
func main() {
primes := []byte{2, 3, 5, 7}
var res []string
for n := 3; n <= 6; n++ {
reps := combrep(n, primes)
for _, rep := range reps {
sum := byte(0)
for _, r := range rep {
sum += r
}
if sum == 13 {
var perms []string
for i := 0; i < len(rep); i++ {
rep[i] += 48
}
findPerms(rep, 0, len(rep), &perms)
res = append(res, perms...)
}
}
}
res2 := make([]int, len(res))
for i, r := range res {
res2[i], _ = strconv.Atoi(r)
}
sort.Ints(res2)
fmt.Println("Those numbers whose digits are all prime and sum to 13 are:")
fmt.Println(res2)
}
| #include <stdbool.h>
#include <stdio.h>
bool primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
switch (r) {
case 2:
case 3:
case 5:
case 7:
break;
default:
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
int main() {
int i, c;
c = 0;
for (i = 1; i < 1000000; i++) {
if (primeDigitsSum13(i)) {
printf("%6d ", i);
if (c++ == 10) {
c = 0;
printf("\n");
}
}
}
printf("\n");
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"fmt"
"strings"
)
func main() {
c := "cat"
d := "dog"
if c == d {
fmt.Println(c, "is bytewise identical to", d)
}
if c != d {
fmt.Println(c, "is bytewise different from", d)
}
if c > d {
fmt.Println(c, "is lexically bytewise greater than", d)
}
if c < d {
fmt.Println(c, "is lexically bytewise less than", d)
}
if c >= d {
fmt.Println(c, "is lexically bytewise greater than or equal to", d)
}
if c <= d {
fmt.Println(c, "is lexically bytewise less than or equal to", d)
}
eqf := `when interpreted as UTF-8 and compared under Unicode
simple case folding rules.`
if strings.EqualFold(c, d) {
fmt.Println(c, "equal to", d, eqf)
} else {
fmt.Println(c, "not equal to", d, eqf)
}
}
|
if (strcmp(a,b)) action_on_equality();
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
if cErr := f.Close(); err == nil {
err = cErr
}
return err
}
func showNotes(w io.Writer, fn string) error {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
_, err = io.Copy(w, f)
f.Close()
return err
}
func main() {
const fn = "NOTES.TXT"
var err error
if len(os.Args) > 1 {
err = addNote(fn, strings.Join(os.Args[1:], " "))
} else {
err = showNotes(os.Stdout, fn)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
| #include <stdio.h>
#include <time.h>
#define note_file "NOTES.TXT"
int main(int argc, char**argv)
{
FILE *note = 0;
time_t tm;
int i;
char *p;
if (argc < 2) {
if ((note = fopen(note_file, "r")))
while ((i = fgetc(note)) != EOF)
putchar(i);
} else if ((note = fopen(note_file, "a"))) {
tm = time(0);
p = ctime(&tm);
while (*p) fputc(*p != '\n'?*p:'\t', note), p++;
for (i = 1; i < argc; i++)
fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
}
if (note) fclose(note);
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
if cErr := f.Close(); err == nil {
err = cErr
}
return err
}
func showNotes(w io.Writer, fn string) error {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
_, err = io.Copy(w, f)
f.Close()
return err
}
func main() {
const fn = "NOTES.TXT"
var err error
if len(os.Args) > 1 {
err = addNote(fn, strings.Join(os.Args[1:], " "))
} else {
err = showNotes(os.Stdout, fn)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
| #include <stdio.h>
#include <time.h>
#define note_file "NOTES.TXT"
int main(int argc, char**argv)
{
FILE *note = 0;
time_t tm;
int i;
char *p;
if (argc < 2) {
if ((note = fopen(note_file, "r")))
while ((i = fgetc(note)) != EOF)
putchar(i);
} else if ((note = fopen(note_file, "a"))) {
tm = time(0);
p = ctime(&tm);
while (*p) fputc(*p != '\n'?*p:'\t', note), p++;
for (i = 1; i < argc; i++)
fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
}
if (note) fclose(note);
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
)
func main() {
const nn = 32
const step = .05
xVal := make([]float64, nn)
tSin := make([]float64, nn)
tCos := make([]float64, nn)
tTan := make([]float64, nn)
for i := range xVal {
xVal[i] = float64(i) * step
tSin[i], tCos[i] = math.Sincos(xVal[i])
tTan[i] = tSin[i] / tCos[i]
}
iSin := thieleInterpolator(tSin, xVal)
iCos := thieleInterpolator(tCos, xVal)
iTan := thieleInterpolator(tTan, xVal)
fmt.Printf("%16.14f\n", 6*iSin(.5))
fmt.Printf("%16.14f\n", 3*iCos(.5))
fmt.Printf("%16.14f\n", 4*iTan(1))
}
func thieleInterpolator(x, y []float64) func(float64) float64 {
n := len(x)
ρ := make([][]float64, n)
for i := range ρ {
ρ[i] = make([]float64, n-i)
ρ[i][0] = y[i]
}
for i := 0; i < n-1; i++ {
ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
}
for i := 2; i < n; i++ {
for j := 0; j < n-i; j++ {
ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
}
}
ρ0 := ρ[0]
return func(xin float64) float64 {
var a float64
for i := n - 1; i > 1; i-- {
a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
}
return y[0] + (xin-x[0])/(ρ0[1]+a)
}
}
| #include <stdio.h>
#include <string.h>
#include <math.h>
#define N 32
#define N2 (N * (N - 1) / 2)
#define STEP .05
double xval[N], t_sin[N], t_cos[N], t_tan[N];
double r_sin[N2], r_cos[N2], r_tan[N2];
double rho(double *x, double *y, double *r, int i, int n)
{
if (n < 0) return 0;
if (!n) return y[i];
int idx = (N - 1 - n) * (N - n) / 2 + i;
if (r[idx] != r[idx])
r[idx] = (x[i] - x[i + n])
/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))
+ rho(x, y, r, i + 1, n - 2);
return r[idx];
}
double thiele(double *x, double *y, double *r, double xin, int n)
{
if (n > N - 1) return 1;
return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)
+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);
}
#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)
#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)
#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)
int main()
{
int i;
for (i = 0; i < N; i++) {
xval[i] = i * STEP;
t_sin[i] = sin(xval[i]);
t_cos[i] = cos(xval[i]);
t_tan[i] = t_sin[i] / t_cos[i];
}
for (i = 0; i < N2; i++)
r_sin[i] = r_cos[i] = r_tan[i] = 0/0.;
printf("%16.14f\n", 6 * i_sin(.5));
printf("%16.14f\n", 3 * i_cos(.5));
printf("%16.14f\n", 4 * i_tan(1.));
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"math"
)
func main() {
const nn = 32
const step = .05
xVal := make([]float64, nn)
tSin := make([]float64, nn)
tCos := make([]float64, nn)
tTan := make([]float64, nn)
for i := range xVal {
xVal[i] = float64(i) * step
tSin[i], tCos[i] = math.Sincos(xVal[i])
tTan[i] = tSin[i] / tCos[i]
}
iSin := thieleInterpolator(tSin, xVal)
iCos := thieleInterpolator(tCos, xVal)
iTan := thieleInterpolator(tTan, xVal)
fmt.Printf("%16.14f\n", 6*iSin(.5))
fmt.Printf("%16.14f\n", 3*iCos(.5))
fmt.Printf("%16.14f\n", 4*iTan(1))
}
func thieleInterpolator(x, y []float64) func(float64) float64 {
n := len(x)
ρ := make([][]float64, n)
for i := range ρ {
ρ[i] = make([]float64, n-i)
ρ[i][0] = y[i]
}
for i := 0; i < n-1; i++ {
ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
}
for i := 2; i < n; i++ {
for j := 0; j < n-i; j++ {
ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
}
}
ρ0 := ρ[0]
return func(xin float64) float64 {
var a float64
for i := n - 1; i > 1; i-- {
a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
}
return y[0] + (xin-x[0])/(ρ0[1]+a)
}
}
| #include <stdio.h>
#include <string.h>
#include <math.h>
#define N 32
#define N2 (N * (N - 1) / 2)
#define STEP .05
double xval[N], t_sin[N], t_cos[N], t_tan[N];
double r_sin[N2], r_cos[N2], r_tan[N2];
double rho(double *x, double *y, double *r, int i, int n)
{
if (n < 0) return 0;
if (!n) return y[i];
int idx = (N - 1 - n) * (N - n) / 2 + i;
if (r[idx] != r[idx])
r[idx] = (x[i] - x[i + n])
/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))
+ rho(x, y, r, i + 1, n - 2);
return r[idx];
}
double thiele(double *x, double *y, double *r, double xin, int n)
{
if (n > N - 1) return 1;
return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)
+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);
}
#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)
#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)
#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)
int main()
{
int i;
for (i = 0; i < N; i++) {
xval[i] = i * STEP;
t_sin[i] = sin(xval[i]);
t_cos[i] = cos(xval[i]);
t_tan[i] = t_sin[i] / t_cos[i];
}
for (i = 0; i < N2; i++)
r_sin[i] = r_cos[i] = r_tan[i] = 0/0.;
printf("%16.14f\n", 6 * i_sin(.5));
printf("%16.14f\n", 3 * i_cos(.5));
printf("%16.14f\n", 4 * i_tan(1.));
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"math"
)
func entropy(s string) float64 {
m := map[rune]float64{}
for _, r := range s {
m[r]++
}
hm := 0.
for _, c := range m {
hm += c * math.Log2(c)
}
l := float64(len(s))
return math.Log2(l) - hm/l
}
const F_Word1 = "1"
const F_Word2 = "0"
func FibonacciWord(n int) string {
a, b := F_Word1, F_Word2
for ; n > 1; n-- {
a, b = b, b+a
}
return a
}
func FibonacciWordGen() <-chan string {
ch := make(chan string)
go func() {
a, b := F_Word1, F_Word2
for {
ch <- a
a, b = b, b+a
}
}()
return ch
}
func main() {
fibWords := FibonacciWordGen()
fmt.Printf("%3s %9s %-18s %s\n", "N", "Length", "Entropy", "Word")
n := 1
for ; n < 10; n++ {
s := <-fibWords
if s2 := FibonacciWord(n); s != s2 {
fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
}
fmt.Printf("%3d %9d %.16f %s\n", n, len(s), entropy(s), s)
}
for ; n <= 37; n++ {
s := <-fibWords
fmt.Printf("%3d %9d %.16f\n", n, len(s), entropy(s))
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void print_headings()
{
printf("%2s", "N");
printf(" %10s", "Length");
printf(" %-20s", "Entropy");
printf(" %-40s", "Word");
printf("\n");
}
double calculate_entropy(int ones, int zeros)
{
double result = 0;
int total = ones + zeros;
result -= (double) ones / total * log2((double) ones / total);
result -= (double) zeros / total * log2((double) zeros / total);
if (result != result) {
result = 0;
}
return result;
}
void print_entropy(char *word)
{
int ones = 0;
int zeros = 0;
int i;
for (i = 0; word[i]; i++) {
char c = word[i];
switch (c) {
case '0':
zeros++;
break;
case '1':
ones++;
break;
}
}
double entropy = calculate_entropy(ones, zeros);
printf(" %-20.18f", entropy);
}
void print_word(int n, char *word)
{
printf("%2d", n);
printf(" %10ld", strlen(word));
print_entropy(word);
if (n < 10) {
printf(" %-40s", word);
} else {
printf(" %-40s", "...");
}
printf("\n");
}
int main(int argc, char *argv[])
{
print_headings();
char *last_word = malloc(2);
strcpy(last_word, "1");
char *current_word = malloc(2);
strcpy(current_word, "0");
print_word(1, last_word);
int i;
for (i = 2; i <= 37; i++) {
print_word(i, current_word);
char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);
strcpy(next_word, current_word);
strcat(next_word, last_word);
free(last_word);
last_word = current_word;
current_word = next_word;
}
free(last_word);
free(current_word);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"math"
)
func entropy(s string) float64 {
m := map[rune]float64{}
for _, r := range s {
m[r]++
}
hm := 0.
for _, c := range m {
hm += c * math.Log2(c)
}
l := float64(len(s))
return math.Log2(l) - hm/l
}
const F_Word1 = "1"
const F_Word2 = "0"
func FibonacciWord(n int) string {
a, b := F_Word1, F_Word2
for ; n > 1; n-- {
a, b = b, b+a
}
return a
}
func FibonacciWordGen() <-chan string {
ch := make(chan string)
go func() {
a, b := F_Word1, F_Word2
for {
ch <- a
a, b = b, b+a
}
}()
return ch
}
func main() {
fibWords := FibonacciWordGen()
fmt.Printf("%3s %9s %-18s %s\n", "N", "Length", "Entropy", "Word")
n := 1
for ; n < 10; n++ {
s := <-fibWords
if s2 := FibonacciWord(n); s != s2 {
fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
}
fmt.Printf("%3d %9d %.16f %s\n", n, len(s), entropy(s), s)
}
for ; n <= 37; n++ {
s := <-fibWords
fmt.Printf("%3d %9d %.16f\n", n, len(s), entropy(s))
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void print_headings()
{
printf("%2s", "N");
printf(" %10s", "Length");
printf(" %-20s", "Entropy");
printf(" %-40s", "Word");
printf("\n");
}
double calculate_entropy(int ones, int zeros)
{
double result = 0;
int total = ones + zeros;
result -= (double) ones / total * log2((double) ones / total);
result -= (double) zeros / total * log2((double) zeros / total);
if (result != result) {
result = 0;
}
return result;
}
void print_entropy(char *word)
{
int ones = 0;
int zeros = 0;
int i;
for (i = 0; word[i]; i++) {
char c = word[i];
switch (c) {
case '0':
zeros++;
break;
case '1':
ones++;
break;
}
}
double entropy = calculate_entropy(ones, zeros);
printf(" %-20.18f", entropy);
}
void print_word(int n, char *word)
{
printf("%2d", n);
printf(" %10ld", strlen(word));
print_entropy(word);
if (n < 10) {
printf(" %-40s", word);
} else {
printf(" %-40s", "...");
}
printf("\n");
}
int main(int argc, char *argv[])
{
print_headings();
char *last_word = malloc(2);
strcpy(last_word, "1");
char *current_word = malloc(2);
strcpy(current_word, "0");
print_word(1, last_word);
int i;
for (i = 2; i <= 37; i++) {
print_word(i, current_word);
char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1);
strcpy(next_word, current_word);
strcat(next_word, last_word);
free(last_word);
last_word = current_word;
current_word = next_word;
}
free(last_word);
free(current_word);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func d2d(d float64) float64 { return math.Mod(d, 360) }
func g2g(g float64) float64 { return math.Mod(g, 400) }
func m2m(m float64) float64 { return math.Mod(m, 6400) }
func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }
func d2g(d float64) float64 { return d2d(d) * 400 / 360 }
func d2m(d float64) float64 { return d2d(d) * 6400 / 360 }
func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }
func g2d(g float64) float64 { return g2g(g) * 360 / 400 }
func g2m(g float64) float64 { return g2g(g) * 6400 / 400 }
func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }
func m2d(m float64) float64 { return m2m(m) * 360 / 6400 }
func m2g(m float64) float64 { return m2m(m) * 400 / 6400 }
func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }
func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }
func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }
func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }
func s(f float64) string {
wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".")
if len(wf) == 1 {
return fmt.Sprintf("%7s ", wf[0])
}
le := len(wf[1])
if le > 7 {
le = 7
}
return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le])
}
func main() {
angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,
359, 399, 6399, 1000000}
ft := "%s %s %s %s %s\n"
fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians")
for _, a := range angles {
fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))
}
fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians")
for _, a := range angles {
fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))
}
fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians")
for _, a := range angles {
fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))
}
fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ")
for _, a := range angles {
fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))
}
}
| #define PI 3.141592653589793
#define TWO_PI 6.283185307179586
double normalize2deg(double a) {
while (a < 0) a += 360;
while (a >= 360) a -= 360;
return a;
}
double normalize2grad(double a) {
while (a < 0) a += 400;
while (a >= 400) a -= 400;
return a;
}
double normalize2mil(double a) {
while (a < 0) a += 6400;
while (a >= 6400) a -= 6400;
return a;
}
double normalize2rad(double a) {
while (a < 0) a += TWO_PI;
while (a >= TWO_PI) a -= TWO_PI;
return a;
}
double deg2grad(double a) {return a * 10 / 9;}
double deg2mil(double a) {return a * 160 / 9;}
double deg2rad(double a) {return a * PI / 180;}
double grad2deg(double a) {return a * 9 / 10;}
double grad2mil(double a) {return a * 16;}
double grad2rad(double a) {return a * PI / 200;}
double mil2deg(double a) {return a * 9 / 160;}
double mil2grad(double a) {return a / 16;}
double mil2rad(double a) {return a * PI / 3200;}
double rad2deg(double a) {return a * 180 / PI;}
double rad2grad(double a) {return a * 200 / PI;}
double rad2mil(double a) {return a * 3200 / PI;}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"os"
"path"
)
func CommonPrefix(sep byte, paths ...string) string {
switch len(paths) {
case 0:
return ""
case 1:
return path.Clean(paths[0])
}
c := []byte(path.Clean(paths[0]))
c = append(c, sep)
for _, v := range paths[1:] {
v = path.Clean(v) + string(sep)
if len(v) < len(c) {
c = c[:len(v)]
}
for i := 0; i < len(c); i++ {
if v[i] != c[i] {
c = c[:i]
break
}
}
}
for i := len(c) - 1; i >= 0; i-- {
if c[i] == sep {
c = c[:i]
break
}
}
return string(c)
}
func main() {
c := CommonPrefix(os.PathSeparator,
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members",
"/home
"/home/user1/././tmp/covertly/foo",
"/home/bob/../user1/tmp/coved/bar",
)
if c == "" {
fmt.Println("No common path")
} else {
fmt.Println("Common path:", c)
}
}
| #include <stdio.h>
int common_len(const char *const *names, int n, char sep)
{
int i, pos;
for (pos = 0; ; pos++) {
for (i = 0; i < n; i++) {
if (names[i][pos] != '\0' &&
names[i][pos] == names[0][pos])
continue;
while (pos > 0 && names[0][--pos] != sep);
return pos;
}
}
return 0;
}
int main()
{
const char *names[] = {
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members",
};
int len = common_len(names, sizeof(names) / sizeof(const char*), '/');
if (!len) printf("No common path\n");
else printf("Common path: %.*s\n", len, names[0]);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func dice5() int {
return rand.Intn(5) + 1
}
func dice7() (i int) {
for {
i = 5*dice5() + dice5()
if i < 27 {
break
}
}
return (i / 3) - 1
}
func distCheck(f func() int, n int,
repeats int, delta float64) (max float64, flatEnough bool) {
count := make([]int, n)
for i := 0; i < repeats; i++ {
count[f()-1]++
}
expected := float64(repeats) / float64(n)
for _, c := range count {
max = math.Max(max, math.Abs(float64(c)-expected))
}
return max, max < delta
}
func main() {
rand.Seed(time.Now().UnixNano())
const calls = 1000000
max, flatEnough := distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
max, flatEnough = distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}
| #include <stdlib.h>
#include <stdio.h>
#include <math.h>
inline int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
inline int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
int check(int (*gen)(), int n, int cnt, double delta)
{
int i = cnt, *bins = calloc(sizeof(int), n);
double ratio;
while (i--) bins[gen() - 1]++;
for (i = 0; i < n; i++) {
ratio = bins[i] * n / (double)cnt - 1;
if (ratio > -delta && ratio < delta) continue;
printf("bin %d out of range: %d (%g%% vs %g%%), ",
i + 1, bins[i], ratio * 100, delta * 100);
break;
}
free(bins);
return i == n;
}
int main()
{
int cnt = 1;
while ((cnt *= 10) <= 1000000) {
printf("Count = %d: ", cnt);
printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n");
}
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
s2 := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
s2[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
s2[n][k] = new(big.Int)
}
s2[n][n].SetInt64(int64(1))
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.SetInt64(int64(k))
t.Mul(&t, s2[n-1][k])
s2[n][k].Add(&t, s2[n-1][k-1])
}
}
fmt.Println("Stirling numbers of the second kind: S2(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%9d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%9d ", s2[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the S2(100, *) row:")
max := new(big.Int).Set(s2[limit][0])
for k := 1; k <= limit; k++ {
if s2[limit][k].Cmp(max) > 0 {
max.Set(s2[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has %d digits.\n", len(max.String()))
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(n-1)/2 + k - 1];
}
bool stirling_cache_create(stirling_cache* sc, int max) {
int* values = calloc(max * (max + 1)/2, sizeof(int));
if (values == NULL)
return false;
sc->max = max;
sc->values = values;
for (int n = 1; n <= max; ++n) {
for (int k = 1; k < n; ++k) {
int s1 = stirling_number2(sc, n - 1, k - 1);
int s2 = stirling_number2(sc, n - 1, k);
values[n*(n-1)/2 + k - 1] = s1 + s2 * k;
}
}
return true;
}
void stirling_cache_destroy(stirling_cache* sc) {
free(sc->values);
sc->values = NULL;
}
void print_stirling_numbers(stirling_cache* sc, int max) {
printf("Stirling numbers of the second kind:\nn/k");
for (int k = 0; k <= max; ++k)
printf(k == 0 ? "%2d" : "%8d", k);
printf("\n");
for (int n = 0; n <= max; ++n) {
printf("%2d ", n);
for (int k = 0; k <= n; ++k)
printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k));
printf("\n");
}
}
int main() {
stirling_cache sc = { 0 };
const int max = 12;
if (!stirling_cache_create(&sc, max)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
print_stirling_numbers(&sc, max);
stirling_cache_destroy(&sc);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
s2 := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
s2[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
s2[n][k] = new(big.Int)
}
s2[n][n].SetInt64(int64(1))
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.SetInt64(int64(k))
t.Mul(&t, s2[n-1][k])
s2[n][k].Add(&t, s2[n-1][k-1])
}
}
fmt.Println("Stirling numbers of the second kind: S2(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%9d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%9d ", s2[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the S2(100, *) row:")
max := new(big.Int).Set(s2[limit][0])
for k := 1; k <= limit; k++ {
if s2[limit][k].Cmp(max) > 0 {
max.Set(s2[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has %d digits.\n", len(max.String()))
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(n-1)/2 + k - 1];
}
bool stirling_cache_create(stirling_cache* sc, int max) {
int* values = calloc(max * (max + 1)/2, sizeof(int));
if (values == NULL)
return false;
sc->max = max;
sc->values = values;
for (int n = 1; n <= max; ++n) {
for (int k = 1; k < n; ++k) {
int s1 = stirling_number2(sc, n - 1, k - 1);
int s2 = stirling_number2(sc, n - 1, k);
values[n*(n-1)/2 + k - 1] = s1 + s2 * k;
}
}
return true;
}
void stirling_cache_destroy(stirling_cache* sc) {
free(sc->values);
sc->values = NULL;
}
void print_stirling_numbers(stirling_cache* sc, int max) {
printf("Stirling numbers of the second kind:\nn/k");
for (int k = 0; k <= max; ++k)
printf(k == 0 ? "%2d" : "%8d", k);
printf("\n");
for (int n = 0; n <= max; ++n) {
printf("%2d ", n);
for (int k = 0; k <= n; ++k)
printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k));
printf("\n");
}
}
int main() {
stirling_cache sc = { 0 };
const int max = 12;
if (!stirling_cache_create(&sc, max)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
print_stirling_numbers(&sc, max);
stirling_cache_destroy(&sc);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
s2 := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
s2[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
s2[n][k] = new(big.Int)
}
s2[n][n].SetInt64(int64(1))
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.SetInt64(int64(k))
t.Mul(&t, s2[n-1][k])
s2[n][k].Add(&t, s2[n-1][k-1])
}
}
fmt.Println("Stirling numbers of the second kind: S2(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%9d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%9d ", s2[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the S2(100, *) row:")
max := new(big.Int).Set(s2[limit][0])
for k := 1; k <= limit; k++ {
if s2[limit][k].Cmp(max) > 0 {
max.Set(s2[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has %d digits.\n", len(max.String()))
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(n-1)/2 + k - 1];
}
bool stirling_cache_create(stirling_cache* sc, int max) {
int* values = calloc(max * (max + 1)/2, sizeof(int));
if (values == NULL)
return false;
sc->max = max;
sc->values = values;
for (int n = 1; n <= max; ++n) {
for (int k = 1; k < n; ++k) {
int s1 = stirling_number2(sc, n - 1, k - 1);
int s2 = stirling_number2(sc, n - 1, k);
values[n*(n-1)/2 + k - 1] = s1 + s2 * k;
}
}
return true;
}
void stirling_cache_destroy(stirling_cache* sc) {
free(sc->values);
sc->values = NULL;
}
void print_stirling_numbers(stirling_cache* sc, int max) {
printf("Stirling numbers of the second kind:\nn/k");
for (int k = 0; k <= max; ++k)
printf(k == 0 ? "%2d" : "%8d", k);
printf("\n");
for (int n = 0; n <= max; ++n) {
printf("%2d ", n);
for (int k = 0; k <= n; ++k)
printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k));
printf("\n");
}
}
int main() {
stirling_cache sc = { 0 };
const int max = 12;
if (!stirling_cache_create(&sc, max)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
print_stirling_numbers(&sc, max);
stirling_cache_destroy(&sc);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);
a = malloc(400000 * sizeof(int));
a[0] = 0;
g_hash_table_add(used, GINT_TO_POINTER(0));
g_hash_table_add(used1000, GINT_TO_POINTER(0));
for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {
next = a[n - 1] - n;
if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {
next += 2 * n;
}
alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));
a[n] = next;
if (!alreadyUsed) {
g_hash_table_add(used, GINT_TO_POINTER(next));
if (next >= 0 && next <= 1000) {
g_hash_table_add(used1000, GINT_TO_POINTER(next));
}
}
if (n == 14) {
printf("The first 15 terms of the Recaman's sequence are: ");
printf("[");
for (i = 0; i < 15; ++i) printf("%d ", a[i]);
printf("\b]\n");
}
if (!foundDup && alreadyUsed) {
printf("The first duplicated term is a[%d] = %d\n", n, next);
foundDup = TRUE;
}
k = g_hash_table_size(used1000);
if (k == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
}
g_hash_table_destroy(used);
g_hash_table_destroy(used1000);
free(a);
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);
a = malloc(400000 * sizeof(int));
a[0] = 0;
g_hash_table_add(used, GINT_TO_POINTER(0));
g_hash_table_add(used1000, GINT_TO_POINTER(0));
for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {
next = a[n - 1] - n;
if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {
next += 2 * n;
}
alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));
a[n] = next;
if (!alreadyUsed) {
g_hash_table_add(used, GINT_TO_POINTER(next));
if (next >= 0 && next <= 1000) {
g_hash_table_add(used1000, GINT_TO_POINTER(next));
}
}
if (n == 14) {
printf("The first 15 terms of the Recaman's sequence are: ");
printf("[");
for (i = 0; i < 15; ++i) printf("%d ", a[i]);
printf("\b]\n");
}
if (!foundDup && alreadyUsed) {
printf("The first duplicated term is a[%d] = %d\n", n, next);
foundDup = TRUE;
}
k = g_hash_table_size(used1000);
if (k == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
}
g_hash_table_destroy(used);
g_hash_table_destroy(used1000);
free(a);
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | func inc(n int) {
x := n + 1
println(x)
}
| #include <stdlib.h>
#define SIZEOF_MEMB (sizeof(int))
#define NMEMB 100
int main()
{
int *ints = malloc(SIZEOF_MEMB*NMEMB);
ints = realloc(ints, sizeof(int)*(NMEMB+1));
int *int2 = calloc(NMEMB, SIZEOF_MEMB);
free(ints); free(int2);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
)
var b []byte
func printBoard() {
fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9])
}
var pScore, cScore int
var pMark, cMark byte = 'X', 'O'
var in = bufio.NewReader(os.Stdin)
func main() {
b = make([]byte, 9)
fmt.Println("Play by entering a digit.")
for {
for i := range b {
b[i] = '1' + byte(i)
}
computerStart := cMark == 'X'
if computerStart {
fmt.Println("I go first, playing X's")
} else {
fmt.Println("You go first, playing X's")
}
TakeTurns:
for {
if !computerStart {
if !playerTurn() {
return
}
if gameOver() {
break TakeTurns
}
}
computerStart = false
computerTurn()
if gameOver() {
break TakeTurns
}
}
fmt.Println("Score: you", pScore, "me", cScore)
fmt.Println("\nLet's play again.")
}
}
func playerTurn() bool {
var pm string
var err error
for i := 0; i < 3; i++ {
printBoard()
fmt.Printf("%c's move? ", pMark)
if pm, err = in.ReadString('\n'); err != nil {
fmt.Println(err)
return false
}
pm = strings.TrimSpace(pm)
if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] {
x := pm[0] - '1'
b[x] = pMark
return true
}
}
fmt.Println("You're not playing right.")
return false
}
var choices = make([]int, 9)
func computerTurn() {
printBoard()
var x int
defer func() {
fmt.Println("My move:", x+1)
b[x] = cMark
}()
block := -1
for _, l := range lines {
var mine, yours int
x = -1
for _, sq := range l {
switch b[sq] {
case cMark:
mine++
case pMark:
yours++
default:
x = sq
}
}
if mine == 2 && x >= 0 {
return
}
if yours == 2 && x >= 0 {
block = x
}
}
if block >= 0 {
x = block
return
}
choices = choices[:0]
for i, sq := range b {
if sq == '1'+byte(i) {
choices = append(choices, i)
}
}
x = choices[rand.Intn(len(choices))]
}
func gameOver() bool {
for _, l := range lines {
if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {
printBoard()
if b[l[0]] == cMark {
fmt.Println("I win!")
cScore++
pMark, cMark = 'X', 'O'
} else {
fmt.Println("You win!")
pScore++
pMark, cMark = 'O', 'X'
}
return true
}
}
for i, sq := range b {
if sq == '1'+byte(i) {
return false
}
}
fmt.Println("Cat game.")
pMark, cMark = cMark, pMark
return true
}
var lines = [][]int{
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{2, 4, 6},
}
| #include <stdio.h>
#include <stdlib.h>
int b[3][3];
int check_winner()
{
int i;
for (i = 0; i < 3; i++) {
if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])
return b[i][0];
if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])
return b[0][i];
}
if (!b[1][1]) return 0;
if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];
if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];
return 0;
}
void showboard()
{
const char *t = "X O";
int i, j;
for (i = 0; i < 3; i++, putchar('\n'))
for (j = 0; j < 3; j++)
printf("%c ", t[ b[i][j] + 1 ]);
printf("-----\n");
}
#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)
int best_i, best_j;
int test_move(int val, int depth)
{
int i, j, score;
int best = -1, changed = 0;
if ((score = check_winner())) return (score == val) ? 1 : -1;
for_ij {
if (b[i][j]) continue;
changed = b[i][j] = val;
score = -test_move(-val, depth + 1);
b[i][j] = 0;
if (score <= best) continue;
if (!depth) {
best_i = i;
best_j = j;
}
best = score;
}
return changed ? best : 0;
}
const char* game(int user)
{
int i, j, k, move, win = 0;
for_ij b[i][j] = 0;
printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n");
printf("You have O, I have X.\n\n");
for (k = 0; k < 9; k++, user = !user) {
while(user) {
printf("your move: ");
if (!scanf("%d", &move)) {
scanf("%*s");
continue;
}
if (--move < 0 || move >= 9) continue;
if (b[i = move / 3][j = move % 3]) continue;
b[i][j] = 1;
break;
}
if (!user) {
if (!k) {
best_i = rand() % 3;
best_j = rand() % 3;
} else
test_move(-1, 0);
b[best_i][best_j] = -1;
printf("My move: %d\n", best_i * 3 + best_j + 1);
}
showboard();
if ((win = check_winner()))
return win == 1 ? "You win.\n\n": "I win.\n\n";
}
return "A draw.\n\n";
}
int main()
{
int first = 0;
while (1) printf("%s", game(first = !first));
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import "fmt"
func main() {
for i := 1;; i++ {
fmt.Println(i)
}
}
| #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
func main() {
for i := 1;; i++ {
fmt.Println(i)
}
}
| #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#define MAXLEN 961
int makehist(char *S,int *hist,int len){
int wherechar[256];
int i,histlen;
histlen=0;
for(i=0;i<256;i++)wherechar[i]=-1;
for(i=0;i<len;i++){
if(wherechar[(int)S[i]]==-1){
wherechar[(int)S[i]]=histlen;
histlen++;
}
hist[wherechar[(int)S[i]]]++;
}
return histlen;
}
double entropy(int *hist,int histlen,int len){
int i;
double H;
H=0;
for(i=0;i<histlen;i++){
H-=(double)hist[i]/len*log2((double)hist[i]/len);
}
return H;
}
int main(void){
char S[MAXLEN];
int len,*hist,histlen;
double H;
FILE *f;
f=fopen("entropy.c","r");
for(len=0;!feof(f);len++)S[len]=fgetc(f);
S[--len]='\0';
hist=(int*)calloc(len,sizeof(int));
histlen=makehist(S,hist,len);
H=entropy(hist,histlen,len);
printf("%lf\n",H);
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#define MAXLEN 961
int makehist(char *S,int *hist,int len){
int wherechar[256];
int i,histlen;
histlen=0;
for(i=0;i<256;i++)wherechar[i]=-1;
for(i=0;i<len;i++){
if(wherechar[(int)S[i]]==-1){
wherechar[(int)S[i]]=histlen;
histlen++;
}
hist[wherechar[(int)S[i]]]++;
}
return histlen;
}
double entropy(int *hist,int histlen,int len){
int i;
double H;
H=0;
for(i=0;i<histlen;i++){
H-=(double)hist[i]/len*log2((double)hist[i]/len);
}
return H;
}
int main(void){
char S[MAXLEN];
int len,*hist,histlen;
double H;
FILE *f;
f=fopen("entropy.c","r");
for(len=0;!feof(f);len++)S[len]=fgetc(f);
S[--len]='\0';
hist=(int*)calloc(len,sizeof(int));
histlen=makehist(S,hist,len);
H=entropy(hist,histlen,len);
printf("%lf\n",H);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"net"
)
func main() {
if addrs, err := net.LookupHost("www.kame.net"); err == nil {
fmt.Println(addrs)
} else {
fmt.Println(err)
}
}
| #include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main()
{
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo("www.kame.net", NULL, &hints, &res0);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
exit(1);
}
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
} else {
printf("%s\n", host);
}
}
freeaddrinfo(res0);
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import "github.com/fogleman/gg"
var points []gg.Point
const width = 81
func peano(x, y, lg, i1, i2 int) {
if lg == 1 {
px := float64(width-x) * 10
py := float64(width-y) * 10
points = append(points, gg.Point{px, py})
return
}
lg /= 3
peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)
peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)
peano(x+lg, y+lg, lg, i1, 1-i2)
peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)
peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)
peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)
peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)
peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)
peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)
}
func main() {
peano(0, 0, width, 0, 0)
dc := gg.NewContext(820, 820)
dc.SetRGB(1, 1, 1)
dc.Clear()
for _, p := range points {
dc.LineTo(p.X, p.Y)
}
dc.SetRGB(1, 0, 1)
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("peano.png")
}
|
#include <graphics.h>
#include <math.h>
void Peano(int x, int y, int lg, int i1, int i2) {
if (lg == 1) {
lineto(3*x,3*y);
return;
}
lg = lg/3;
Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2);
Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2);
Peano(x+lg, y+lg, lg, i1, 1-i2);
Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2);
Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2);
Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2);
Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2);
Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2);
Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2);
}
int main(void) {
initwindow(1000,1000,"Peano, Peano");
Peano(0, 0, 1000, 0, 0);
getch();
cleardevice();
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func dice5() int {
return rand.Intn(5) + 1
}
func dice7() (i int) {
for {
i = 5*dice5() + dice5()
if i < 27 {
break
}
}
return (i / 3) - 1
}
func distCheck(f func() int, n int,
repeats int, delta float64) (max float64, flatEnough bool) {
count := make([]int, n)
for i := 0; i < repeats; i++ {
count[f()-1]++
}
expected := float64(repeats) / float64(n)
for _, c := range count {
max = math.Max(max, math.Abs(float64(c)-expected))
}
return max, max < delta
}
func main() {
rand.Seed(time.Now().UnixNano())
const calls = 1000000
max, flatEnough := distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
max, flatEnough = distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}
| int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
int main()
{
printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n");
printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n");
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"strings"
)
func main() {
p, tests, swaps := Solution()
fmt.Println(p)
fmt.Println("Tested", tests, "positions and did", swaps, "swaps.")
}
const conn = `
A B
/|\ /|\
/ | X | \
/ |/ \| \
C - D - E - F
\ |\ /| /
\ | X | /
\|/ \|/
G H`
var connections = []struct{ a, b int }{
{0, 2}, {0, 3}, {0, 4},
{1, 3}, {1, 4}, {1, 5},
{6, 2}, {6, 3}, {6, 4},
{7, 3}, {7, 4}, {7, 5},
{2, 3}, {3, 4}, {4, 5},
}
type pegs [8]int
func (p *pegs) Valid() bool {
for _, c := range connections {
if absdiff(p[c.a], p[c.b]) <= 1 {
return false
}
}
return true
}
func Solution() (p *pegs, tests, swaps int) {
var recurse func(int) bool
recurse = func(i int) bool {
if i >= len(p)-1 {
tests++
return p.Valid()
}
for j := i; j < len(p); j++ {
swaps++
p[i], p[j] = p[j], p[i]
if recurse(i + 1) {
return true
}
p[i], p[j] = p[j], p[i]
}
return false
}
p = &pegs{1, 2, 3, 4, 5, 6, 7, 8}
recurse(0)
return
}
func (p *pegs) String() string {
return strings.Map(func(r rune) rune {
if 'A' <= r && r <= 'H' {
return rune(p[r-'A'] + '0')
}
return r
}, conn)
}
func absdiff(a, b int) int {
if a > b {
return a - b
}
return b - a
}
| #include <stdbool.h>
#include <stdio.h>
#include <math.h>
int connections[15][2] = {
{0, 2}, {0, 3}, {0, 4},
{1, 3}, {1, 4}, {1, 5},
{6, 2}, {6, 3}, {6, 4},
{7, 3}, {7, 4}, {7, 5},
{2, 3}, {3, 4}, {4, 5},
};
int pegs[8];
int num = 0;
bool valid() {
int i;
for (i = 0; i < 15; i++) {
if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) {
return false;
}
}
return true;
}
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
void printSolution() {
printf("----- %d -----\n", num++);
printf(" %d %d\n", pegs[0], pegs[1]);
printf("%d %d %d %d\n", pegs[2], pegs[3], pegs[4], pegs[5]);
printf(" %d %d\n", pegs[6], pegs[7]);
printf("\n");
}
void solution(int le, int ri) {
if (le == ri) {
if (valid()) {
printSolution();
}
} else {
int i;
for (i = le; i <= ri; i++) {
swap(pegs + le, pegs + i);
solution(le + 1, ri);
swap(pegs + le, pegs + i);
}
}
}
int main() {
int i;
for (i = 0; i < 8; i++) {
pegs[i] = i + 1;
}
solution(0, 8 - 1);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import "fmt"
func isPrime(n uint64) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint64(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func ord(n int) string {
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%dth", n)
}
m %= 10
suffix := "th"
if m < 4 {
switch m {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
}
}
return fmt.Sprintf("%d%s", n, suffix)
}
func isMagnanimous(n uint64) bool {
if n < 10 {
return true
}
for p := uint64(10); ; p *= 10 {
q := n / p
r := n % p
if !isPrime(q + r) {
return false
}
if q < 10 {
break
}
}
return true
}
func listMags(from, thru, digs, perLine int) {
if from < 2 {
fmt.Println("\nFirst", thru, "magnanimous numbers:")
} else {
fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru))
}
for i, c := uint64(0), 0; c < thru; i++ {
if isMagnanimous(i) {
c++
if c >= from {
fmt.Printf("%*d ", digs, i)
if c%perLine == 0 {
fmt.Println()
}
}
}
}
}
func main() {
listMags(1, 45, 3, 15)
listMags(241, 250, 1, 10)
listMags(391, 400, 1, 10)
}
| #include <stdio.h>
#include <string.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
bool is_prime(ull n) {
ull d;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
d = 5;
while (d * d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
void ord(char *res, int n) {
char suffix[3];
int m = n % 100;
if (m >= 4 && m <= 20) {
sprintf(res,"%dth", n);
return;
}
switch(m % 10) {
case 1:
strcpy(suffix, "st");
break;
case 2:
strcpy(suffix, "nd");
break;
case 3:
strcpy(suffix, "rd");
break;
default:
strcpy(suffix, "th");
break;
}
sprintf(res, "%d%s", n, suffix);
}
bool is_magnanimous(ull n) {
ull p, q, r;
if (n < 10) return TRUE;
for (p = 10; ; p *= 10) {
q = n / p;
r = n % p;
if (!is_prime(q + r)) return FALSE;
if (q < 10) break;
}
return TRUE;
}
void list_mags(int from, int thru, int digs, int per_line) {
ull i = 0;
int c = 0;
char res1[13], res2[13];
if (from < 2) {
printf("\nFirst %d magnanimous numbers:\n", thru);
} else {
ord(res1, from);
ord(res2, thru);
printf("\n%s through %s magnanimous numbers:\n", res1, res2);
}
for ( ; c < thru; ++i) {
if (is_magnanimous(i)) {
if (++c >= from) {
printf("%*llu ", digs, i);
if (!(c % per_line)) printf("\n");
}
}
}
}
int main() {
list_mags(1, 45, 3, 15);
list_mags(241, 250, 1, 10);
list_mags(391, 400, 1, 10);
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"container/heap"
"fmt"
)
func main() {
p := newP()
fmt.Print("First twenty: ")
for i := 0; i < 20; i++ {
fmt.Print(p(), " ")
}
fmt.Print("\nBetween 100 and 150: ")
n := p()
for n <= 100 {
n = p()
}
for ; n < 150; n = p() {
fmt.Print(n, " ")
}
for n <= 7700 {
n = p()
}
c := 0
for ; n < 8000; n = p() {
c++
}
fmt.Println("\nNumber beween 7,700 and 8,000:", c)
p = newP()
for i := 1; i < 10000; i++ {
p()
}
fmt.Println("10,000th prime:", p())
}
func newP() func() int {
n := 1
var pq pQueue
top := &pMult{2, 4, 0}
return func() int {
for {
n++
if n < top.pMult {
heap.Push(&pq, &pMult{prime: n, pMult: n * n})
top = pq[0]
return n
}
for top.pMult == n {
top.pMult += top.prime
heap.Fix(&pq, 0)
top = pq[0]
}
}
}
}
type pMult struct {
prime int
pMult int
index int
}
type pQueue []*pMult
func (q pQueue) Len() int { return len(q) }
func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }
func (q pQueue) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
q[i].index = i
q[j].index = j
}
func (p *pQueue) Push(x interface{}) {
q := *p
e := x.(*pMult)
e.index = len(q)
*p = append(q, e)
}
func (p *pQueue) Pop() interface{} {
q := *p
last := len(q) - 1
e := q[last]
*p = q[:last]
return e
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define CHUNK_BYTES (32 << 8)
#define CHUNK_SIZE (CHUNK_BYTES << 6)
int field[CHUNK_BYTES];
#define GET(x) (field[(x)>>6] & 1<<((x)>>1&31))
#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))
typedef unsigned uint;
typedef struct {
uint *e;
uint cap, len;
} uarray;
uarray primes, offset;
void push(uarray *a, uint n)
{
if (a->len >= a->cap) {
if (!(a->cap *= 2)) a->cap = 16;
a->e = realloc(a->e, sizeof(uint) * a->cap);
}
a->e[a->len++] = n;
}
uint low;
void init(void)
{
uint p, q;
unsigned char f[1<<16];
memset(f, 0, sizeof(f));
push(&primes, 2);
push(&offset, 0);
for (p = 3; p < 1<<16; p += 2) {
if (f[p]) continue;
for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;
push(&primes, p);
push(&offset, q);
}
low = 1<<16;
}
void sieve(void)
{
uint i, p, q, hi, ptop;
if (!low) init();
memset(field, 0, sizeof(field));
hi = low + CHUNK_SIZE;
ptop = sqrt(hi) * 2 + 1;
for (i = 1; (p = primes.e[i]*2) < ptop; i++) {
for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)
SET(q);
offset.e[i] = q + low;
}
for (p = 1; p < CHUNK_SIZE; p += 2)
if (!GET(p)) push(&primes, low + p);
low = hi;
}
int main(void)
{
uint i, p, c;
while (primes.len < 20) sieve();
printf("First 20:");
for (i = 0; i < 20; i++)
printf(" %u", primes.e[i]);
putchar('\n');
while (primes.e[primes.len-1] < 150) sieve();
printf("Between 100 and 150:");
for (i = 0; i < primes.len; i++) {
if ((p = primes.e[i]) >= 100 && p < 150)
printf(" %u", primes.e[i]);
}
putchar('\n');
while (primes.e[primes.len-1] < 8000) sieve();
for (i = c = 0; i < primes.len; i++)
if ((p = primes.e[i]) >= 7700 && p < 8000) c++;
printf("%u primes between 7700 and 8000\n", c);
for (c = 10; c <= 100000000; c *= 10) {
while (primes.len < c) sieve();
printf("%uth prime: %u\n", c, primes.e[c-1]);
}
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#define LEN 3
int rand_idx(double *p, int n)
{
double s = rand() / (RAND_MAX + 1.0);
int i;
for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
return i;
}
int main()
{
int user_action, my_action;
int user_rec[] = {0, 0, 0};
const char *names[] = { "Rock", "Paper", "Scissors" };
char str[2];
const char *winner[] = { "We tied.", "Meself winned.", "You win." };
double p[LEN] = { 1./3, 1./3, 1./3 };
while (1) {
my_action = rand_idx(p,LEN);
printf("\nYour choice [1-3]:\n"
" 1. Rock\n 2. Paper\n 3. Scissors\n> ");
if (!scanf("%d", &user_action)) {
scanf("%1s", str);
if (*str == 'q') {
printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]);
return 0;
}
continue;
}
user_action --;
if (user_action > 2 || user_action < 0) {
printf("invalid choice; again\n");
continue;
}
printf("You chose %s; I chose %s. %s\n",
names[user_action], names[my_action],
winner[(my_action - user_action + 3) % 3]);
user_rec[user_action]++;
}
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#define LEN 3
int rand_idx(double *p, int n)
{
double s = rand() / (RAND_MAX + 1.0);
int i;
for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
return i;
}
int main()
{
int user_action, my_action;
int user_rec[] = {0, 0, 0};
const char *names[] = { "Rock", "Paper", "Scissors" };
char str[2];
const char *winner[] = { "We tied.", "Meself winned.", "You win." };
double p[LEN] = { 1./3, 1./3, 1./3 };
while (1) {
my_action = rand_idx(p,LEN);
printf("\nYour choice [1-3]:\n"
" 1. Rock\n 2. Paper\n 3. Scissors\n> ");
if (!scanf("%d", &user_action)) {
scanf("%1s", str);
if (*str == 'q') {
printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]);
return 0;
}
continue;
}
user_action --;
if (user_action > 2 || user_action < 0) {
printf("invalid choice; again\n");
continue;
}
printf("You chose %s; I chose %s. %s\n",
names[user_action], names[my_action],
winner[(my_action - user_action + 3) % 3]);
user_rec[user_action]++;
}
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
| #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
| #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
| #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"strings"
)
var encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" +
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" +
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" +
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" +
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" +
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" +
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" +
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" +
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" +
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" +
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" +
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" +
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" +
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" +
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" +
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK"
var freq = [26]float64{
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074,
}
func sum(a []float64) (sum float64) {
for _, f := range a {
sum += f
}
return
}
func bestMatch(a []float64) int {
sum := sum(a)
bestFit, bestRotate := 1e100, 0
for rotate := 0; rotate < 26; rotate++ {
fit := 0.0
for i := 0; i < 26; i++ {
d := a[(i+rotate)%26]/sum - freq[i]
fit += d * d / freq[i]
}
if fit < bestFit {
bestFit, bestRotate = fit, rotate
}
}
return bestRotate
}
func freqEveryNth(msg []int, key []byte) float64 {
l := len(msg)
interval := len(key)
out := make([]float64, 26)
accu := make([]float64, 26)
for j := 0; j < interval; j++ {
for k := 0; k < 26; k++ {
out[k] = 0.0
}
for i := j; i < l; i += interval {
out[msg[i]]++
}
rot := bestMatch(out)
key[j] = byte(rot + 65)
for i := 0; i < 26; i++ {
accu[i] += out[(i+rot)%26]
}
}
sum := sum(accu)
ret := 0.0
for i := 0; i < 26; i++ {
d := accu[i]/sum - freq[i]
ret += d * d / freq[i]
}
return ret
}
func decrypt(text, key string) string {
var sb strings.Builder
ki := 0
for _, c := range text {
if c < 'A' || c > 'Z' {
continue
}
ci := (c - rune(key[ki]) + 26) % 26
sb.WriteRune(ci + 65)
ki = (ki + 1) % len(key)
}
return sb.String()
}
func main() {
enc := strings.Replace(encoded, " ", "", -1)
txt := make([]int, len(enc))
for i := 0; i < len(txt); i++ {
txt[i] = int(enc[i] - 'A')
}
bestFit, bestKey := 1e100, ""
fmt.Println(" Fit Length Key")
for j := 1; j <= 26; j++ {
key := make([]byte, j)
fit := freqEveryNth(txt, key)
sKey := string(key)
fmt.Printf("%f %2d %s", fit, j, sKey)
if fit < bestFit {
bestFit, bestKey = fit, sKey
fmt.Print(" <--- best so far")
}
fmt.Println()
}
fmt.Println("\nBest key :", bestKey)
fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey))
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG"
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ"
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS"
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT"
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST"
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH"
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV"
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW"
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO"
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR"
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX"
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB"
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA"
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK";
const double freq[] = {
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074
};
int best_match(const double *a, const double *b) {
double sum = 0, fit, d, best_fit = 1e100;
int i, rotate, best_rotate = 0;
for (i = 0; i < 26; i++)
sum += a[i];
for (rotate = 0; rotate < 26; rotate++) {
fit = 0;
for (i = 0; i < 26; i++) {
d = a[(i + rotate) % 26] / sum - b[i];
fit += d * d / b[i];
}
if (fit < best_fit) {
best_fit = fit;
best_rotate = rotate;
}
}
return best_rotate;
}
double freq_every_nth(const int *msg, int len, int interval, char *key) {
double sum, d, ret;
double out[26], accu[26] = {0};
int i, j, rot;
for (j = 0; j < interval; j++) {
for (i = 0; i < 26; i++)
out[i] = 0;
for (i = j; i < len; i += interval)
out[msg[i]]++;
key[j] = rot = best_match(out, freq);
key[j] += 'A';
for (i = 0; i < 26; i++)
accu[i] += out[(i + rot) % 26];
}
for (i = 0, sum = 0; i < 26; i++)
sum += accu[i];
for (i = 0, ret = 0; i < 26; i++) {
d = accu[i] / sum - freq[i];
ret += d * d / freq[i];
}
key[interval] = '\0';
return ret;
}
int main() {
int txt[strlen(encoded)];
int len = 0, j;
char key[100];
double fit, best_fit = 1e100;
for (j = 0; encoded[j] != '\0'; j++)
if (isupper(encoded[j]))
txt[len++] = encoded[j] - 'A';
for (j = 1; j < 30; j++) {
fit = freq_every_nth(txt, len, j, key);
printf("%f, key length: %2d, %s", fit, j, key);
if (fit < best_fit) {
best_fit = fit;
printf(" <--- best so far");
}
printf("\n");
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"math/big"
)
type lft struct {
q,r,s,t big.Int
}
func (t *lft) extr(x *big.Int) *big.Rat {
var n, d big.Int
var r big.Rat
return r.SetFrac(
n.Add(n.Mul(&t.q, x), &t.r),
d.Add(d.Mul(&t.s, x), &t.t))
}
var three = big.NewInt(3)
var four = big.NewInt(4)
func (t *lft) next() *big.Int {
r := t.extr(three)
var f big.Int
return f.Div(r.Num(), r.Denom())
}
func (t *lft) safe(n *big.Int) bool {
r := t.extr(four)
var f big.Int
if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
return true
}
return false
}
func (t *lft) comp(u *lft) *lft {
var r lft
var a, b big.Int
r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))
r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))
r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))
r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))
return &r
}
func (t *lft) prod(n *big.Int) *lft {
var r lft
r.q.SetInt64(10)
r.r.Mul(r.r.SetInt64(-10), n)
r.t.SetInt64(1)
return r.comp(t)
}
func main() {
z := new(lft)
z.q.SetInt64(1)
z.t.SetInt64(1)
var k int64
lfts := func() *lft {
k++
r := new(lft)
r.q.SetInt64(k)
r.r.SetInt64(4*k+2)
r.t.SetInt64(2*k+1)
return r
}
for {
y := z.next()
if z.safe(y) {
fmt.Print(y)
z = z.prod(y)
} else {
z = z.comp(lfts())
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
got -= 2;
while (s[got] == '0' || s[got] == '9') got--;
printf("%.*s", (int)(got - done), s + done);
free(s);
done = got;
accu *= 2;
}
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
showQ(n)
}
showQ(1000)
count, p := 0, 1
for n := 2; n <= 1e5; n++ {
qn := q(n)
if qn < p {
count++
}
p = qn
}
fmt.Println("count:", count)
initMap()
showQ(1e6)
}
func showQ(n int) {
fmt.Printf("Q(%d) = %d\n", n, q(n))
}
| #include <stdio.h>
#include <stdlib.h>
#define N 100000
int main()
{
int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;
q[1] = q[2] = 1;
for (i = 3; i <= N; i++)
q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
for (i = 1; i <= 10; i++)
printf("%d%c", q[i], i == 10 ? '\n' : ' ');
printf("%d\n", q[1000]);
for (flip = 0, i = 1; i < N; i++)
flip += q[i] > q[i + 1];
printf("flips: %d\n", flip);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
showQ(n)
}
showQ(1000)
count, p := 0, 1
for n := 2; n <= 1e5; n++ {
qn := q(n)
if qn < p {
count++
}
p = qn
}
fmt.Println("count:", count)
initMap()
showQ(1e6)
}
func showQ(n int) {
fmt.Printf("Q(%d) = %d\n", n, q(n))
}
| #include <stdio.h>
#include <stdlib.h>
#define N 100000
int main()
{
int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;
q[1] = q[2] = 1;
for (i = 3; i <= N; i++)
q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
for (i = 1; i <= 10; i++)
printf("%d%c", q[i], i == 10 ? '\n' : ' ');
printf("%d\n", q[1000]);
for (flip = 0, i = 1; i < N; i++)
flip += q[i] > q[i + 1];
printf("flips: %d\n", flip);
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func
func main() {
fac := Y(almost_fac)
fib := Y(almost_fib)
fmt.Println("fac(10) = ", fac(10))
fmt.Println("fib(10) = ", fib(10))
}
func Y(f FuncFunc) Func {
g := func(r RecursiveFunc) Func {
return f(func(x int) int {
return r(r)(x)
})
}
return g(g)
}
func almost_fac(f Func) Func {
return func(x int) int {
if x <= 1 {
return 1
}
return x * f(x-1)
}
}
func almost_fib(f Func) Func {
return func(x int) int {
if x <= 2 {
return 1
}
return f(x-1)+f(x-2)
}
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, func);
func _;
int num;
} func_t;
func new(func(*f)(func, func), func _) {
func x = malloc(sizeof(func_t));
x->fn = f;
x->_ = _;
x->num = 0;
return x;
}
func call(func f, func n) {
return f->fn(f, n);
}
func Y(func(*f)(func, func)) {
func g = new(f, 0);
g->_ = g;
return g;
}
func num(int n) {
func x = new(0, 0);
x->num = n;
return x;
}
func fac(func self, func n) {
int nn = n->num;
return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num)
: num(1);
}
func fib(func self, func n) {
int nn = n->num;
return nn > 1
? num( call(self->_, num(nn - 1))->num +
call(self->_, num(nn - 2))->num )
: num(1);
}
void show(func n) { printf(" %d", n->num); }
int main() {
int i;
func f = Y(fac);
printf("fac: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
f = Y(fib);
printf("fib: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | func addsub(x, y int) (int, int) {
return x + y, x - y
}
| #include<stdio.h>
typedef struct{
int integer;
float decimal;
char letter;
char string[100];
double bigDecimal;
}Composite;
Composite example()
{
Composite C = {1, 2.3, 'a', "Hello World", 45.678};
return C;
}
int main()
{
Composite C = example();
printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import "fmt"
func main() {
const max = 1000
a := make([]int, max)
for n := 0; n < max-1; n++ {
for m := n - 1; m >= 0; m-- {
if a[m] == a[n] {
a[n+1] = n - m
break
}
}
}
fmt.Println("The first ten terms of the Van Eck sequence are:")
fmt.Println(a[:10])
fmt.Println("\nTerms 991 to 1000 of the sequence are:")
fmt.Println(a[990:])
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import "fmt"
func main() {
const max = 1000
a := make([]int, max)
for n := 0; n < max-1; n++ {
for m := n - 1; m >= 0; m-- {
if a[m] == a[n] {
a[n+1] = n - m
break
}
}
}
fmt.Println("The first ten terms of the Van Eck sequence are:")
fmt.Println(a[:10])
fmt.Println("\nTerms 991 to 1000 of the sequence are:")
fmt.Println(a[990:])
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Quit()
fmt.Println(conn)
if err = conn.Login(username, password); err != nil {
log.Fatal(err)
}
if err = conn.ChangeDir(dir); err != nil {
log.Fatal(err)
}
fmt.Println(conn.CurrentDir())
files, err := conn.List(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
}
r, err := conn.Retr(file)
if err != nil {
log.Fatal(err)
}
defer r.Close()
f, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
n, err := io.Copy(f, r)
if err != nil {
log.Fatal(err)
}
fmt.Println("Wrote", n, "bytes to", file)
}
| #include <ftplib.h>
int main(void)
{
netbuf *nbuf;
FtpInit();
FtpConnect("kernel.org", &nbuf);
FtpLogin("anonymous", "", nbuf);
FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);
FtpChdir("pub/linux/kernel", nbuf);
FtpDir((void*)0, ".", nbuf);
FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf);
FtpQuit(nbuf);
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
| #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t digits[N_DIGITS];
void gen_digits()
{
int i;
for (i = 0; i < N_DIGITS; i++)
digits[i].val = 1 + rand() % 9;
}
#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;
#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;
void reset()
{
int i;
msg = 0;
pool_ptr = pos = 0;
for (i = 0; i < POOL_SIZE; i++) {
pool[i].op = OP_NONE;
pool[i].left = pool[i].right = 0;
}
for (i = 0; i < N_DIGITS; i++)
digits[i].used = 0;
}
void bail(const char *s)
{
msg = s;
longjmp(ctx, 1);
}
expr new_expr()
{
if (pool_ptr < POOL_SIZE)
return pool + pool_ptr++;
return 0;
}
int next_tok()
{
while (isspace(str[pos])) pos++;
return str[pos];
}
int take()
{
if (str[pos] != '\0') return ++pos;
return 0;
}
expr get_fact();
expr get_term();
expr get_expr();
expr get_expr()
{
int c;
expr l, r, ret;
if (!(ret = get_term())) bail("Expected term");
while ((c = next_tok()) == '+' || c == '-') {
if (!take()) bail("Unexpected end of input");
if (!(r = get_term())) bail("Expected term");
l = ret;
ret = new_expr();
ret->op = (c == '+') ? OP_ADD : OP_SUB;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_term()
{
int c;
expr l, r, ret;
ret = get_fact();
while((c = next_tok()) == '*' || c == '/') {
if (!take()) bail("Unexpected end of input");
r = get_fact();
l = ret;
ret = new_expr();
ret->op = (c == '*') ? OP_MUL : OP_DIV;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_digit()
{
int i, c = next_tok();
expr ret;
if (c >= '0' && c <= '9') {
take();
ret = new_expr();
ret->op = OP_NUM;
ret->val = c - '0';
for (i = 0; i < N_DIGITS; i++)
if (digits[i].val == ret->val && !digits[i].used) {
digits[i].used = 1;
return ret;
}
bail("Invalid digit");
}
return 0;
}
expr get_fact()
{
int c;
expr l = get_digit();
if (l) return l;
if ((c = next_tok()) == '(') {
take();
l = get_expr();
if (next_tok() != ')') bail("Unbalanced parens");
take();
return l;
}
return 0;
}
expr parse()
{
int i;
expr ret = get_expr();
if (next_tok() != '\0')
bail("Trailing garbage");
for (i = 0; i < N_DIGITS; i++)
if (!digits[i].used)
bail("Not all digits are used");
return ret;
}
typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };
int gcd(int m, int n)
{
int t;
while (m) {
t = m; m = n % m; n = t;
}
return n;
}
void eval_tree(expr e, frac res)
{
frac_t l, r;
int t;
if (e->op == OP_NUM) {
res->num = e->val;
res->denom = 1;
return;
}
eval_tree(e->left, &l);
eval_tree(e->right, &r);
switch(e->op) {
case OP_ADD:
res->num = l.num * r.denom + l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_SUB:
res->num = l.num * r.denom - l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_MUL:
res->num = l.num * r.num;
res->denom = l.denom * r.denom;
break;
case OP_DIV:
res->num = l.num * r.denom;
res->denom = l.denom * r.num;
break;
}
if ((t = gcd(res->denom, res->num))) {
res->denom /= t;
res->num /= t;
}
}
void get_input()
{
int i;
reinput:
reset();
printf("\nAvailable digits are:");
for (i = 0; i < N_DIGITS; i++)
printf(" %d", digits[i].val);
printf(". Type an expression and I'll check it for you, or make new numbers.\n"
"Your choice? [Expr/n/q] ");
while (1) {
for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
fgets(str, MAX_INPUT, stdin);
if (*str == '\0') goto reinput;
if (str[MAX_INPUT - 1] != '\n')
bail("string too long");
for (i = 0; i < MAX_INPUT; i++)
if (str[i] == '\n') str[i] = '\0';
if (str[0] == 'q') {
printf("Bye\n");
exit(0);
}
if (str[0] == 'n') {
gen_digits();
goto reinput;
}
return;
}
}
int main()
{
frac_t f;
srand(time(0));
gen_digits();
while(1) {
get_input();
setjmp(ctx);
if (msg) {
printf("%s at '%.*s'\n", msg, pos, str);
continue;
}
eval_tree(parse(), &f);
if (f.denom == 0) bail("Divide by zero");
if (f.denom == 1 && f.num == 24)
printf("You got 24. Very good.\n");
else {
if (f.denom == 1)
printf("Eval to: %d, ", f.num);
else
printf("Eval to: %d/%d, ", f.num, f.denom);
printf("no good. Try again.\n");
}
}
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
| #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t digits[N_DIGITS];
void gen_digits()
{
int i;
for (i = 0; i < N_DIGITS; i++)
digits[i].val = 1 + rand() % 9;
}
#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;
#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;
void reset()
{
int i;
msg = 0;
pool_ptr = pos = 0;
for (i = 0; i < POOL_SIZE; i++) {
pool[i].op = OP_NONE;
pool[i].left = pool[i].right = 0;
}
for (i = 0; i < N_DIGITS; i++)
digits[i].used = 0;
}
void bail(const char *s)
{
msg = s;
longjmp(ctx, 1);
}
expr new_expr()
{
if (pool_ptr < POOL_SIZE)
return pool + pool_ptr++;
return 0;
}
int next_tok()
{
while (isspace(str[pos])) pos++;
return str[pos];
}
int take()
{
if (str[pos] != '\0') return ++pos;
return 0;
}
expr get_fact();
expr get_term();
expr get_expr();
expr get_expr()
{
int c;
expr l, r, ret;
if (!(ret = get_term())) bail("Expected term");
while ((c = next_tok()) == '+' || c == '-') {
if (!take()) bail("Unexpected end of input");
if (!(r = get_term())) bail("Expected term");
l = ret;
ret = new_expr();
ret->op = (c == '+') ? OP_ADD : OP_SUB;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_term()
{
int c;
expr l, r, ret;
ret = get_fact();
while((c = next_tok()) == '*' || c == '/') {
if (!take()) bail("Unexpected end of input");
r = get_fact();
l = ret;
ret = new_expr();
ret->op = (c == '*') ? OP_MUL : OP_DIV;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_digit()
{
int i, c = next_tok();
expr ret;
if (c >= '0' && c <= '9') {
take();
ret = new_expr();
ret->op = OP_NUM;
ret->val = c - '0';
for (i = 0; i < N_DIGITS; i++)
if (digits[i].val == ret->val && !digits[i].used) {
digits[i].used = 1;
return ret;
}
bail("Invalid digit");
}
return 0;
}
expr get_fact()
{
int c;
expr l = get_digit();
if (l) return l;
if ((c = next_tok()) == '(') {
take();
l = get_expr();
if (next_tok() != ')') bail("Unbalanced parens");
take();
return l;
}
return 0;
}
expr parse()
{
int i;
expr ret = get_expr();
if (next_tok() != '\0')
bail("Trailing garbage");
for (i = 0; i < N_DIGITS; i++)
if (!digits[i].used)
bail("Not all digits are used");
return ret;
}
typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };
int gcd(int m, int n)
{
int t;
while (m) {
t = m; m = n % m; n = t;
}
return n;
}
void eval_tree(expr e, frac res)
{
frac_t l, r;
int t;
if (e->op == OP_NUM) {
res->num = e->val;
res->denom = 1;
return;
}
eval_tree(e->left, &l);
eval_tree(e->right, &r);
switch(e->op) {
case OP_ADD:
res->num = l.num * r.denom + l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_SUB:
res->num = l.num * r.denom - l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_MUL:
res->num = l.num * r.num;
res->denom = l.denom * r.denom;
break;
case OP_DIV:
res->num = l.num * r.denom;
res->denom = l.denom * r.num;
break;
}
if ((t = gcd(res->denom, res->num))) {
res->denom /= t;
res->num /= t;
}
}
void get_input()
{
int i;
reinput:
reset();
printf("\nAvailable digits are:");
for (i = 0; i < N_DIGITS; i++)
printf(" %d", digits[i].val);
printf(". Type an expression and I'll check it for you, or make new numbers.\n"
"Your choice? [Expr/n/q] ");
while (1) {
for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
fgets(str, MAX_INPUT, stdin);
if (*str == '\0') goto reinput;
if (str[MAX_INPUT - 1] != '\n')
bail("string too long");
for (i = 0; i < MAX_INPUT; i++)
if (str[i] == '\n') str[i] = '\0';
if (str[0] == 'q') {
printf("Bye\n");
exit(0);
}
if (str[0] == 'n') {
gen_digits();
goto reinput;
}
return;
}
}
int main()
{
frac_t f;
srand(time(0));
gen_digits();
while(1) {
get_input();
setjmp(ctx);
if (msg) {
printf("%s at '%.*s'\n", msg, pos, str);
continue;
}
eval_tree(parse(), &f);
if (f.denom == 0) bail("Divide by zero");
if (f.denom == 1 && f.num == 24)
printf("You got 24. Very good.\n");
else {
if (f.denom == 1)
printf("Eval to: %d, ", f.num);
else
printf("Eval to: %d/%d, ", f.num, f.denom);
printf("no good. Try again.\n");
}
}
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
}
| for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
| #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
| #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
| #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
| #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
type matrix [][]float64
func zero(n int) matrix {
r := make([][]float64, n)
a := make([]float64, n*n)
for i := range r {
r[i] = a[n*i : n*(i+1)]
}
return r
}
func eye(n int) matrix {
r := zero(n)
for i := range r {
r[i][i] = 1
}
return r
}
func (m matrix) print(label string) {
if label > "" {
fmt.Printf("%s:\n", label)
}
for _, r := range m {
for _, e := range r {
fmt.Printf(" %9.5f", e)
}
fmt.Println()
}
}
func (a matrix) pivotize() matrix {
p := eye(len(a))
for j, r := range a {
max := r[j]
row := j
for i := j; i < len(a); i++ {
if a[i][j] > max {
max = a[i][j]
row = i
}
}
if j != row {
p[j], p[row] = p[row], p[j]
}
}
return p
}
func (m1 matrix) mul(m2 matrix) matrix {
r := zero(len(m1))
for i, r1 := range m1 {
for j := range m2 {
for k := range m1 {
r[i][j] += r1[k] * m2[k][j]
}
}
}
return r
}
func (a matrix) lu() (l, u, p matrix) {
l = zero(len(a))
u = zero(len(a))
p = a.pivotize()
a = p.mul(a)
for j := range a {
l[j][j] = 1
for i := 0; i <= j; i++ {
sum := 0.
for k := 0; k < i; k++ {
sum += u[k][j] * l[i][k]
}
u[i][j] = a[i][j] - sum
}
for i := j; i < len(a); i++ {
sum := 0.
for k := 0; k < j; k++ {
sum += u[k][j] * l[i][k]
}
l[i][j] = (a[i][j] - sum) / u[j][j]
}
}
return
}
func main() {
showLU(matrix{
{1, 3, 5},
{2, 4, 7},
{1, 1, 0}})
showLU(matrix{
{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}})
}
func showLU(a matrix) {
a.print("\na")
l, u, p := a.lu()
l.print("l")
u.print("u")
p.print("p")
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }
typedef double **mat;
#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }
#define _new(a) a = mat_new(n)
mat mat_new(_dim)
{
mat x = malloc(sizeof(double*) * n);
x[0] = malloc(sizeof(double) * n * n);
for_i x[i] = x[0] + n * i;
_zero(x);
return x;
}
#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim)
{
mat x = mat_new(n);
for_ij x[i][j] = ((double (*)[n])s)[i][j];
return x;
}
#define _del(x) mat_del(x)
void mat_del(mat x) { free(x[0]); free(x); }
#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim)
{
if (!fmt) fmt = "%8.4g";
for_i {
printf(i ? " " : " [ ");
for_j {
printf(fmt, x[i][j]);
printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n");
}
}
}
#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim)
{
mat c = _new(c);
for_ijk c[i][j] += a[i][k] * b[k][j];
return c;
}
#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim)
{
for_ij { p[i][j] = (i == j); }
for_i {
int max_j = i;
foreach(j, i, n)
if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;
if (max_j != i)
for_k { _swap(p[i][k], p[max_j][k]); }
}
}
#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
_zero(L); _zero(U);
_pivot(A, P);
mat Aprime = _mul(P, A);
for_i { L[i][i] = 1; }
for_ij {
double s;
if (j <= i) {
_sum_k(0, j, L[j][k] * U[k][i], s)
U[j][i] = Aprime[j][i] - s;
}
if (j >= i) {
_sum_k(0, i, L[j][k] * U[k][i], s);
L[j][i] = (Aprime[j][i] - s) / U[i][i];
}
}
_del(Aprime);
}
double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};
int main()
{
int n = 3;
mat A, L, P, U;
_new(L); _new(P); _new(U);
A = _copy(A3);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
printf("\n");
n = 4;
_new(L); _new(P); _new(U);
A = _copy(A4);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
return 0;
}
|
Write the same algorithm in C++ as shown in this C implementation. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define TRUE 1
#define FALSE 0
typedef unsigned char bool;
void sieve(bool *c, int limit) {
int i, p = 3, p2;
c[0] = TRUE;
c[1] = TRUE;
for (;;) {
p2 = p * p;
if (p2 >= limit) {
break;
}
for (i = p2; i < limit; i += 2*p) {
c[i] = TRUE;
}
for (;;) {
p += 2;
if (!c[p]) {
break;
}
}
}
}
void printHelper(const char *cat, int len, int lim, int n) {
const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : "";
const char *verb = (len == 1) ? "is" : "are";
printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len);
printf("The last %d %s:\n", n, verb);
}
void printArray(int *a, int len) {
int i;
printf("[");
for (i = 0; i < len; ++i) printf("%d ", a[i]);
printf("\b]");
}
int main() {
int i, ix, n, lim = 1000035;
int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2;
int pr = 0, tr = 0, qd = 0, qn = 0, un = 2;
int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10;
int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5];
int last_un[10];
bool *sv = calloc(lim - 1, sizeof(bool));
setlocale(LC_NUMERIC, "");
sieve(sv, lim);
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
unsexy++;
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pairs++;
} else continue;
if (i < lim-12 && !sv[i+12]) {
trips++;
} else continue;
if (i < lim-18 && !sv[i+18]) {
quads++;
} else continue;
if (i < lim-24 && !sv[i+24]) {
quins++;
}
}
if (pairs < lpr) lpr = pairs;
if (trips < ltr) ltr = trips;
if (quads < lqd) lqd = quads;
if (quins < lqn) lqn = quins;
if (unsexy < lun) lun = unsexy;
for (i = 3; i < lim; i += 2) {
if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) {
un++;
if (un > unsexy - lun) {
last_un[un + lun - 1 - unsexy] = i;
}
continue;
}
if (i < lim-6 && !sv[i] && !sv[i+6]) {
pr++;
if (pr > pairs - lpr) {
ix = pr + lpr - 1 - pairs;
last_pr[ix][0] = i; last_pr[ix][1] = i + 6;
}
} else continue;
if (i < lim-12 && !sv[i+12]) {
tr++;
if (tr > trips - ltr) {
ix = tr + ltr - 1 - trips;
last_tr[ix][0] = i; last_tr[ix][1] = i + 6;
last_tr[ix][2] = i + 12;
}
} else continue;
if (i < lim-18 && !sv[i+18]) {
qd++;
if (qd > quads - lqd) {
ix = qd + lqd - 1 - quads;
last_qd[ix][0] = i; last_qd[ix][1] = i + 6;
last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18;
}
} else continue;
if (i < lim-24 && !sv[i+24]) {
qn++;
if (qn > quins - lqn) {
ix = qn + lqn - 1 - quins;
last_qn[ix][0] = i; last_qn[ix][1] = i + 6;
last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18;
last_qn[ix][4] = i + 24;
}
}
}
printHelper("pairs", pairs, lim, lpr);
printf(" [");
for (i = 0; i < lpr; ++i) {
printArray(last_pr[i], 2);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("triplets", trips, lim, ltr);
printf(" [");
for (i = 0; i < ltr; ++i) {
printArray(last_tr[i], 3);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("quadruplets", quads, lim, lqd);
printf(" [");
for (i = 0; i < lqd; ++i) {
printArray(last_qd[i], 4);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("quintuplets", quins, lim, lqn);
printf(" [");
for (i = 0; i < lqn; ++i) {
printArray(last_qn[i], 5);
printf("\b] ");
}
printf("\b]\n\n");
printHelper("unsexy primes", unsexy, lim, lun);
printf(" [");
printArray(last_un, lun);
printf("\b]\n");
free(sv);
return 0;
}
| #include <array>
#include <iostream>
#include <vector>
#include <boost/circular_buffer.hpp>
#include "prime_sieve.hpp"
int main() {
using std::cout;
using std::vector;
using boost::circular_buffer;
using group_buffer = circular_buffer<vector<int>>;
const int max = 1000035;
const int max_group_size = 5;
const int diff = 6;
const int array_size = max + diff;
const int max_groups = 5;
const int max_unsexy = 10;
prime_sieve sieve(array_size);
std::array<int, max_group_size> group_count{0};
vector<group_buffer> groups(max_group_size, group_buffer(max_groups));
int unsexy_count = 0;
circular_buffer<int> unsexy_primes(max_unsexy);
vector<int> group;
for (int p = 2; p < max; ++p) {
if (!sieve.is_prime(p))
continue;
if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) {
++unsexy_count;
unsexy_primes.push_back(p);
} else {
group.clear();
group.push_back(p);
for (int group_size = 1; group_size < max_group_size; group_size++) {
int next_p = p + group_size * diff;
if (next_p >= max || !sieve.is_prime(next_p))
break;
group.push_back(next_p);
++group_count[group_size];
groups[group_size].push_back(group);
}
}
}
for (int size = 1; size < max_group_size; ++size) {
cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n';
cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":";
for (const vector<int>& group : groups[size]) {
cout << " (";
for (size_t i = 0; i < group.size(); ++i) {
if (i > 0)
cout << ' ';
cout << group[i];
}
cout << ")";
}
cout << "\n\n";
}
cout << "number of unsexy primes is " << unsexy_count << '\n';
cout << "last " << unsexy_primes.size() << " unsexy primes:";
for (int prime : unsexy_primes)
cout << ' ' << prime;
cout << '\n';
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the C version. | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
unsigned int i, j;
double* y;
if (order >= len) return 0;
y = malloc(sizeof(double) * len);
if (!order) {
memcpy(y, x, sizeof(double) * len);
return y;
}
for (j = 0; j < order; j++, x = y)
for (i = 0, len--; i < len; i++)
y[i] = x[i + 1] - x[i];
y = realloc(y, sizeof(double) * len);
return y;
}
int main(void)
{
double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
int i, len = sizeof(x) / sizeof(x[0]);
y = fwd_diff(x, len, 1);
for (i = 0; i < len - 1; i++)
printf("%g ", y[i]);
putchar('\n');
return 0;
}
| #include <vector>
#include <iterator>
#include <algorithm>
template<typename InputIterator, typename OutputIterator>
OutputIterator forward_difference(InputIterator first, InputIterator last,
OutputIterator dest)
{
if (first == last)
return dest;
typedef typename std::iterator_traits<InputIterator>::value_type value_type;
value_type temp = *first++;
while (first != last)
{
value_type temp2 = *first++;
*dest++ = temp2 - temp;
temp = temp2;
}
return dest;
}
template<typename InputIterator, typename OutputIterator>
OutputIterator nth_forward_difference(int order,
InputIterator first, InputIterator last,
OutputIterator dest)
{
if (order == 0)
return std::copy(first, last, dest);
if (order == 1)
return forward_difference(first, last, dest);
typedef typename std::iterator_traits<InputIterator>::value_type value_type;
std::vector<value_type> temp_storage;
forward_difference(first, last, std::back_inserter(temp_storage));
typename std::vector<value_type>::iterator begin = temp_storage.begin(),
end = temp_storage.end();
for (int i = 1; i < order-1; ++i)
end = forward_difference(begin, end, begin);
return forward_difference(begin, end, dest);
}
#include <iostream>
int main()
{
double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };
std::vector<double> dest;
nth_forward_difference(1, array, array+10, std::back_inserter(dest));
std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
double* end = nth_forward_difference(3, array, array+10, array);
for (double* p = array; p < end; ++p)
std::cout << *p << " ";
std::cout << std::endl;
return 0;
}
|
Change the following C code into C++ without altering its purpose. | int is_prime(unsigned int n)
{
unsigned int p;
if (!(n & 1) || n < 2 ) return n == 2;
for (p = 3; p <= n/p; p += 2)
if (!(n % p)) return 0;
return 1;
}
| #include <cmath>
bool is_prime(unsigned int n)
{
if (n <= 1)
return false;
if (n == 2)
return true;
for (unsigned int i = 2; i <= sqrt(n); ++i)
if (n % i == 0)
return false;
return true;
}
|
Convert this C block to C++, preserving its control flow and logic. | #include <stdio.h>
#include <limits.h>
static unsigned long gcd_ui(unsigned long x, unsigned long y) {
unsigned long t;
if (y < x) { t = x; x = y; y = t; }
while (y > 0) {
t = y; y = x % y; x = t;
}
return x;
}
unsigned long binomial(unsigned long n, unsigned long k) {
unsigned long d, g, r = 1;
if (k == 0) return 1;
if (k == 1) return n;
if (k >= n) return (k == n);
if (k > n/2) k = n-k;
for (d = 1; d <= k; d++) {
if (r >= ULONG_MAX/n) {
unsigned long nr, dr;
g = gcd_ui(n, d); nr = n/g; dr = d/g;
g = gcd_ui(r, dr); r = r/g; dr = dr/g;
if (r >= ULONG_MAX/nr) return 0;
r *= nr;
r /= dr;
n--;
} else {
r *= n--;
r /= d;
}
}
return r;
}
int main() {
printf("%lu\n", binomial(5, 3));
printf("%lu\n", binomial(40, 19));
printf("%lu\n", binomial(67, 31));
return 0;
}
| double Factorial(double nValue)
{
double result = nValue;
double result_next;
double pc = nValue;
do
{
result_next = result*(pc-1);
result = result_next;
pc--;
}while(pc>2);
nValue = result;
return nValue;
}
double binomialCoefficient(double n, double k)
{
if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0;
if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;
return Factorial(n) /(Factorial(k)*Factorial((n - k)));
}
|
Write the same code in C++ as shown below in C. | #define cSize( a ) ( sizeof(a)/sizeof(a[0]) )
int ar[10];
ar[0] = 1;
ar[1] = 2;
int* p;
for (p=ar;
p<(ar+cSize(ar));
p++) {
printf("%d\n",*p);
}
| int a[5];
a[0] = 1;
int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
#include <string>
std::string strings[4];
|
Change the following C code into C++ without altering its purpose. | struct link *first;
struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
}
| #include <iostream>
#include <forward_list>
int main()
{
std::forward_list<int> list{1, 2, 3, 4, 5};
for (int e : list)
std::cout << e << std::endl;
}
|
Change the programming language of this snippet from C to C++ without modifying what it does. | #include <stdlib.h>
#include <stdio.h>
int main(void)
{
const int dimx = 800, dimy = 800;
int i, j;
FILE *fp = fopen("first.ppm", "wb");
(void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
for (j = 0; j < dimy; ++j)
{
for (i = 0; i < dimx; ++i)
{
static unsigned char color[3];
color[0] = i % 256;
color[1] = j % 256;
color[2] = (i * j) % 256;
(void) fwrite(color, 1, 3, fp);
}
}
(void) fclose(fp);
return EXIT_SUCCESS;
}
| #include <fstream>
#include <cstdio>
int main() {
constexpr auto dimx = 800u, dimy = 800u;
using namespace std;
ofstream ofs("first.ppm", ios_base::out | ios_base::binary);
ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl;
for (auto j = 0u; j < dimy; ++j)
for (auto i = 0u; i < dimx; ++i)
ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);
ofs.close();
return EXIT_SUCCESS;
}
|
Convert the following code from C to C++, ensuring the logic remains intact. | #include <stdio.h>
int main() {
remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs");
return 0;
}
| #include <cstdio>
#include <direct.h>
int main() {
remove( "input.txt" );
remove( "/input.txt" );
_rmdir( "docs" );
_rmdir( "/docs" );
return 0;
}
|
Write the same code in C++ as shown below in C. |
#include <math.h>
#include <stdio.h>
#define eps 1e-6
int main(void) {
double a, b, h, n2, r, u, v;
int k, k2, m, n;
printf("From the definition, err. 3e-10\n");
n = 400;
h = 1;
for (k = 2; k <= n; k++) {
h += 1.0 / k;
}
a = log(n +.5 + 1.0 / (24*n));
printf("Hn %.16f\n", h);
printf("gamma %.16f\nk = %d\n\n", h - a, n);
printf("Sweeney, 1963, err. idem\n");
n = 21;
double s[] = {0, n};
r = n;
k = 1;
do {
k += 1;
r *= (double) n / k;
s[k & 1] += r / k;
} while (r > eps);
printf("gamma %.16f\nk = %d\n\n", s[1] - s[0] - log(n), k);
printf("Bailey, 1988\n");
n = 5;
a = 1;
h = 1;
n2 = pow(2,n);
r = 1;
k = 1;
do {
k += 1;
r *= n2 / k;
h += 1.0 / k;
b = a; a += r * h;
} while (fabs(b - a) > eps);
a *= n2 / exp(n2);
printf("gamma %.16f\nk = %d\n\n", a - n * log(2), k);
printf("Brent-McMillan, 1980\n");
n = 13;
a = -log(n);
b = 1;
u = a;
v = b;
n2 = n * n;
k2 = 0;
k = 0;
do {
k2 += 2*k + 1;
k += 1;
a *= n2 / k;
b *= n2 / k2;
a = (a + b) / k;
u += a;
v += b;
} while (fabs(a) > eps);
printf("gamma %.16f\nk = %d\n\n", u / v, k);
printf("How Euler did it in 1735\n");
double B2[] = {1.0,1.0/6,-1.0/30,1.0/42,-1.0/30,\
5.0/66,-691.0/2730,7.0/6,-3617.0/510,43867.0/798};
m = 7;
if (m > 9) return(0);
n = 10;
h = 1;
for (k = 2; k <= n; k++) {
h += 1.0 / k;
}
printf("Hn %.16f\n", h);
h -= log(n);
printf(" -ln %.16f\n", h);
a = -1.0 / (2*n);
n2 = n * n;
r = 1;
for (k = 1; k <= m; k++) {
r *= n2;
a += B2[k] / (2*k * r);
}
printf("err %.16f\ngamma %.16f\nk = %d", a, h + a, n + m);
printf("\n\nC = 0.57721566490153286...\n");
}
| #include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
double ByVaccaSeries(int numTerms)
{
double gamma = 0;
size_t next = 4;
for(double numerator = 1; numerator < numTerms; ++numerator)
{
double delta = 0;
for(size_t denominator = next/2; denominator < next; denominator+=2)
{
delta += 1.0/denominator - 1.0/(denominator + 1);
}
gamma += numerator * delta;
next *= 2;
}
return gamma;
}
double ByEulersMethod()
{
const std::array<double, 8> B2 {1.0, 1.0/6, -1.0/30, 1.0/42, -1.0/30,
5.0/66, -691.0/2730, 7.0/6};
const int n = 10;
const double h = []
{
double sum = 1;
for (int k = 2; k <= n; k++) { sum += 1.0 / k; }
return sum - log(n);
}();
double a = -1.0 / (2*n);
double r = 1;
for (int k = 1; k < ssize(B2); k++)
{
r *= n * n;
a += B2[k] / (2*k * r);
}
return h + a;
}
int main()
{
std::cout << std::setprecision(16) << "Vacca series: " << ByVaccaSeries(32);
std::cout << std::setprecision(16) << "\nEulers method: " << ByEulersMethod();
}
|
Produce a functionally identical C++ code for the snippet given in C. | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\
(x) == 2 ? "Boomtime" :\
(x) == 3 ? "Pungenday" :\
(x) == 4 ? "Prickle-Prickle" :\
"Setting Orange")
#define season( x ) ((x) == 0 ? "Chaos" :\
(x) == 1 ? "Discord" :\
(x) == 2 ? "Confusion" :\
(x) == 3 ? "Bureaucracy" :\
"The Aftermath")
#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)
#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))
char * ddate( int y, int d ){
int dyear = 1166 + y;
char * result = malloc( 100 * sizeof( char ) );
if( leap_year( y ) ){
if( d == 60 ){
sprintf( result, "St. Tib's Day, YOLD %d", dyear );
return result;
} else if( d >= 60 ){
-- d;
}
}
sprintf( result, "%s, %s %d, YOLD %d",
day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );
return result;
}
int day_of_year( int y, int m, int d ){
int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for( ; m > 1; m -- ){
d += month_lengths[ m - 2 ];
if( m == 3 && leap_year( y ) ){
++ d;
}
}
return d;
}
int main( int argc, char * argv[] ){
time_t now;
struct tm * now_time;
int year, doy;
if( argc == 1 ){
now = time( NULL );
now_time = localtime( &now );
year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;
} else if( argc == 4 ){
year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );
}
char * result = ddate( year, doy );
puts( result );
free( result );
return 0;
}
| #include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
class myTuple
{
public:
void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }
bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }
string second() { return t.second; }
private:
pair<pair<int, int>, string> t;
};
class discordian
{
public:
discordian() {
myTuple t;
t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t );
t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t );
t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t );
t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t );
t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t );
t.set( 8, 12, "Afflux" ); holyday.push_back( t );
seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" );
seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" );
wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" );
wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" );
}
void convert( int d, int m, int y ) {
if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) {
cout << "\nThis is not a date!";
return;
}
vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) );
int dd = d, day, wday, sea, yr = y + 1166;
for( int x = 1; x < m; x++ )
dd += getMaxDay( x, 1 );
day = dd % 73; if( !day ) day = 73;
wday = dd % 5;
sea = ( dd - 1 ) / 73;
if( d == 29 && m == 2 && isLeap( y ) ) {
cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr;
return;
}
cout << wdays[wday] << " " << seasons[sea] << " " << day;
if( day > 10 && day < 14 ) cout << "th";
else switch( day % 10) {
case 1: cout << "st"; break;
case 2: cout << "nd"; break;
case 3: cout << "rd"; break;
default: cout << "th";
}
cout << ", Year of Our Lady of Discord " << yr;
if( f != holyday.end() ) cout << " - " << ( *f ).second();
}
private:
int getMaxDay( int m, int y ) {
int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m];
}
bool isLeap( int y ) {
bool l = false;
if( !( y % 4 ) ) {
if( y % 100 ) l = true;
else if( !( y % 400 ) ) l = true;
}
return l;
}
vector<myTuple> holyday; vector<string> seasons, wdays;
};
int main( int argc, char* argv[] ) {
string date; discordian disc;
while( true ) {
cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break;
if( date.length() == 10 ) {
istringstream iss( date );
vector<string> vc;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );
disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) );
cout << "\n\n\n";
} else cout << "\nIs this a date?!\n\n";
}
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
int i, j;
void fliprow(int **b, int sz, int n)
{
for(i = 0; i < sz; i++)
b[n+1][i] = !b[n+1][i];
}
void flipcol(int **b, int sz, int n)
{
for(i = 1; i <= sz; i++)
b[i][n] = !b[i][n];
}
void initt(int **t, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
t[i][j] = rand()%2;
}
void initb(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
b[i][j] = t[i][j];
for(i = 1; i <= sz; i++)
fliprow(b, sz, rand()%sz+1);
for(i = 0; i < sz; i++)
flipcol(b, sz, rand()%sz);
}
void printb(int **b, int sz)
{
printf(" ");
for(i = 0; i < sz; i++)
printf(" %d", i);
printf("\n");
for(i = 1; i <= sz; i++)
{
printf("%d", i-1);
for(j = 0; j < sz; j++)
printf(" %d", b[i][j]);
printf("\n");
}
printf("\n");
}
int eq(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
if(b[i][j] != t[i][j])
return 0;
return 1;
}
void main()
{
int sz = 3;
int eql = 0;
int mov = 0;
int **t = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
t[i] = malloc(sz*sizeof(int));
int **b = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
b[i] = malloc(sz*sizeof(int));
char roc;
int n;
initt(t, sz);
initb(t, b, sz);
while(eq(t, b, sz))
initb(t, b, sz);
while(!eql)
{
printf("Target: \n");
printb(t, sz);
printf("Board: \n");
printb(b, sz);
printf("What to flip: ");
scanf(" %c", &roc);
scanf(" %d", &n);
switch(roc)
{
case 'r':
fliprow(b, sz, n);
break;
case 'c':
flipcol(b, sz, n);
break;
default:
perror("Please specify r or c and an number");
break;
}
printf("Moves Taken: %d\n", ++mov);
if(eq(t, b, sz))
{
printf("You win!\n");
eql = 1;
}
}
}
| #include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() )
{
display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r;
for( string::iterator i = r.begin(); i != r.end(); i++ )
{
byte ii = ( *i );
if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }
else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }
}
}
cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl;
}
void display()
{ system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); }
void output( string t, byte* f )
{
cout << t << endl;
cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl;
for( int y = 0; y < hei; y++ )
{
cout << static_cast<char>( y + 'a' ) << " ";
for( int x = 0; x < wid; x++ )
cout << static_cast<char>( f[x + y * wid] + 48 ) << " ";
cout << endl;
}
cout << endl << endl;
}
bool solved()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( target[x + y * wid] != field[x + y * wid] ) return false;
return true;
}
void createTarget()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( frnd() < .5f ) target[x + y * wid] = 1;
else target[x + y * wid] = 0;
memcpy( field, target, wid * hei );
}
void flipCol( int c )
{ for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }
void flipRow( int r )
{ for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }
void calcStartPos()
{
int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;
for( int x = 0; x < flips; x++ )
{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }
}
void createField()
{
if( field ){ delete [] field; delete [] target; }
int t = wid * hei; field = new byte[t]; target = new byte[t];
memset( field, 0, t ); memset( target, 0, t ); createTarget();
while( true ) { calcStartPos(); if( !solved() ) break; }
}
float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }
byte* field, *target; int wid, hei;
};
int main( int argc, char* argv[] )
{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
|
Can you help me rewrite this code in C++ instead of C, keeping it the same logically? | #include <stdio.h>
#include <stdlib.h>
int i, j;
void fliprow(int **b, int sz, int n)
{
for(i = 0; i < sz; i++)
b[n+1][i] = !b[n+1][i];
}
void flipcol(int **b, int sz, int n)
{
for(i = 1; i <= sz; i++)
b[i][n] = !b[i][n];
}
void initt(int **t, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
t[i][j] = rand()%2;
}
void initb(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
b[i][j] = t[i][j];
for(i = 1; i <= sz; i++)
fliprow(b, sz, rand()%sz+1);
for(i = 0; i < sz; i++)
flipcol(b, sz, rand()%sz);
}
void printb(int **b, int sz)
{
printf(" ");
for(i = 0; i < sz; i++)
printf(" %d", i);
printf("\n");
for(i = 1; i <= sz; i++)
{
printf("%d", i-1);
for(j = 0; j < sz; j++)
printf(" %d", b[i][j]);
printf("\n");
}
printf("\n");
}
int eq(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
if(b[i][j] != t[i][j])
return 0;
return 1;
}
void main()
{
int sz = 3;
int eql = 0;
int mov = 0;
int **t = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
t[i] = malloc(sz*sizeof(int));
int **b = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
b[i] = malloc(sz*sizeof(int));
char roc;
int n;
initt(t, sz);
initb(t, b, sz);
while(eq(t, b, sz))
initb(t, b, sz);
while(!eql)
{
printf("Target: \n");
printb(t, sz);
printf("Board: \n");
printb(b, sz);
printf("What to flip: ");
scanf(" %c", &roc);
scanf(" %d", &n);
switch(roc)
{
case 'r':
fliprow(b, sz, n);
break;
case 'c':
flipcol(b, sz, n);
break;
default:
perror("Please specify r or c and an number");
break;
}
printf("Moves Taken: %d\n", ++mov);
if(eq(t, b, sz))
{
printf("You win!\n");
eql = 1;
}
}
}
| #include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() )
{
display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r;
for( string::iterator i = r.begin(); i != r.end(); i++ )
{
byte ii = ( *i );
if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }
else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }
}
}
cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl;
}
void display()
{ system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); }
void output( string t, byte* f )
{
cout << t << endl;
cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl;
for( int y = 0; y < hei; y++ )
{
cout << static_cast<char>( y + 'a' ) << " ";
for( int x = 0; x < wid; x++ )
cout << static_cast<char>( f[x + y * wid] + 48 ) << " ";
cout << endl;
}
cout << endl << endl;
}
bool solved()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( target[x + y * wid] != field[x + y * wid] ) return false;
return true;
}
void createTarget()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( frnd() < .5f ) target[x + y * wid] = 1;
else target[x + y * wid] = 0;
memcpy( field, target, wid * hei );
}
void flipCol( int c )
{ for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }
void flipRow( int r )
{ for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }
void calcStartPos()
{
int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;
for( int x = 0; x < flips; x++ )
{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }
}
void createField()
{
if( field ){ delete [] field; delete [] target; }
int t = wid * hei; field = new byte[t]; target = new byte[t];
memset( field, 0, t ); memset( target, 0, t ); createTarget();
while( true ) { calcStartPos(); if( !solved() ) break; }
}
float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }
byte* field, *target; int wid, hei;
};
int main( int argc, char* argv[] )
{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
|
Can you help me rewrite this code in C++ instead of C, keeping it the same logically? | #include <stdio.h>
#include <stdlib.h>
int i, j;
void fliprow(int **b, int sz, int n)
{
for(i = 0; i < sz; i++)
b[n+1][i] = !b[n+1][i];
}
void flipcol(int **b, int sz, int n)
{
for(i = 1; i <= sz; i++)
b[i][n] = !b[i][n];
}
void initt(int **t, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
t[i][j] = rand()%2;
}
void initb(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
b[i][j] = t[i][j];
for(i = 1; i <= sz; i++)
fliprow(b, sz, rand()%sz+1);
for(i = 0; i < sz; i++)
flipcol(b, sz, rand()%sz);
}
void printb(int **b, int sz)
{
printf(" ");
for(i = 0; i < sz; i++)
printf(" %d", i);
printf("\n");
for(i = 1; i <= sz; i++)
{
printf("%d", i-1);
for(j = 0; j < sz; j++)
printf(" %d", b[i][j]);
printf("\n");
}
printf("\n");
}
int eq(int **t, int **b, int sz)
{
for(i = 1; i <= sz; i++)
for(j = 0; j < sz; j++)
if(b[i][j] != t[i][j])
return 0;
return 1;
}
void main()
{
int sz = 3;
int eql = 0;
int mov = 0;
int **t = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
t[i] = malloc(sz*sizeof(int));
int **b = malloc(sz*(sizeof(int)+1));
for(i = 1; i <= sz; i++)
b[i] = malloc(sz*sizeof(int));
char roc;
int n;
initt(t, sz);
initb(t, b, sz);
while(eq(t, b, sz))
initb(t, b, sz);
while(!eql)
{
printf("Target: \n");
printb(t, sz);
printf("Board: \n");
printb(b, sz);
printf("What to flip: ");
scanf(" %c", &roc);
scanf(" %d", &n);
switch(roc)
{
case 'r':
fliprow(b, sz, n);
break;
case 'c':
flipcol(b, sz, n);
break;
default:
perror("Please specify r or c and an number");
break;
}
printf("Moves Taken: %d\n", ++mov);
if(eq(t, b, sz))
{
printf("You win!\n");
eql = 1;
}
}
}
| #include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() )
{
display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r;
for( string::iterator i = r.begin(); i != r.end(); i++ )
{
byte ii = ( *i );
if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }
else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }
}
}
cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl;
}
void display()
{ system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); }
void output( string t, byte* f )
{
cout << t << endl;
cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl;
for( int y = 0; y < hei; y++ )
{
cout << static_cast<char>( y + 'a' ) << " ";
for( int x = 0; x < wid; x++ )
cout << static_cast<char>( f[x + y * wid] + 48 ) << " ";
cout << endl;
}
cout << endl << endl;
}
bool solved()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( target[x + y * wid] != field[x + y * wid] ) return false;
return true;
}
void createTarget()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( frnd() < .5f ) target[x + y * wid] = 1;
else target[x + y * wid] = 0;
memcpy( field, target, wid * hei );
}
void flipCol( int c )
{ for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }
void flipRow( int r )
{ for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }
void calcStartPos()
{
int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;
for( int x = 0; x < flips; x++ )
{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }
}
void createField()
{
if( field ){ delete [] field; delete [] target; }
int t = wid * hei; field = new byte[t]; target = new byte[t];
memset( field, 0, t ); memset( target, 0, t ); createTarget();
while( true ) { calcStartPos(); if( !solved() ) break; }
}
float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }
byte* field, *target; int wid, hei;
};
int main( int argc, char* argv[] )
{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
|
Translate the given C code snippet into C++ without altering its behavior. | #include <stdio.h>
#include <mpfr.h>
void h(int n)
{
MPFR_DECL_INIT(a, 200);
MPFR_DECL_INIT(b, 200);
mpfr_fac_ui(a, n, MPFR_RNDD);
mpfr_set_ui(b, 2, MPFR_RNDD);
mpfr_log(b, b, MPFR_RNDD);
mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);
mpfr_div(a, a, b, MPFR_RNDD);
mpfr_div_ui(a, a, 2, MPFR_RNDD);
mpfr_frac(b, a, MPFR_RNDD);
mpfr_printf("%2d: %23.4Rf %c\n", n, a,
mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}
int main(void)
{
int n;
for (n = 1; n <= 17; n++) h(n);
return 0;
}
| #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;
int main()
{
const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
decfloat numerator = 1, denominator = ln_two;
for(int n = 1; n <= 17; n++) {
decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;
decfloat tenths_dig = floor((h - floor(h)) * 10);
std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h <<
(tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n";
}
}
|
Port the provided C code into C++ while preserving the original functionality. | #include <stdio.h>
#include <mpfr.h>
void h(int n)
{
MPFR_DECL_INIT(a, 200);
MPFR_DECL_INIT(b, 200);
mpfr_fac_ui(a, n, MPFR_RNDD);
mpfr_set_ui(b, 2, MPFR_RNDD);
mpfr_log(b, b, MPFR_RNDD);
mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);
mpfr_div(a, a, b, MPFR_RNDD);
mpfr_div_ui(a, a, 2, MPFR_RNDD);
mpfr_frac(b, a, MPFR_RNDD);
mpfr_printf("%2d: %23.4Rf %c\n", n, a,
mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}
int main(void)
{
int n;
for (n = 1; n <= 17; n++) h(n);
return 0;
}
| #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;
int main()
{
const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
decfloat numerator = 1, denominator = ln_two;
for(int n = 1; n <= 17; n++) {
decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;
decfloat tenths_dig = floor((h - floor(h)) * 10);
std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h <<
(tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n";
}
}
|
Generate an equivalent C++ version of this C code. | #include <stdio.h>
#include <mpfr.h>
void h(int n)
{
MPFR_DECL_INIT(a, 200);
MPFR_DECL_INIT(b, 200);
mpfr_fac_ui(a, n, MPFR_RNDD);
mpfr_set_ui(b, 2, MPFR_RNDD);
mpfr_log(b, b, MPFR_RNDD);
mpfr_pow_ui(b, b, n + 1, MPFR_RNDD);
mpfr_div(a, a, b, MPFR_RNDD);
mpfr_div_ui(a, a, 2, MPFR_RNDD);
mpfr_frac(b, a, MPFR_RNDD);
mpfr_printf("%2d: %23.4Rf %c\n", n, a,
mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N');
}
int main(void)
{
int n;
for (n = 1; n <= 17; n++) h(n);
return 0;
}
| #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;
int main()
{
const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
decfloat numerator = 1, denominator = ln_two;
for(int n = 1; n <= 17; n++) {
decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;
decfloat tenths_dig = floor((h - floor(h)) * 10);
std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h <<
(tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.