Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Ensure the translated C code behaves exactly like the original Go snippet. | package bank
import (
"bytes"
"errors"
"fmt"
"log"
"sort"
"sync"
)
type PID string
type RID string
type RMap map[RID]int
func (m RMap) String() string {
rs := make([]string, len(m))
i := 0
for r := range m {
rs[i] = string(r)
i++
}
sort.Strings(rs)
var b bytes.Buffer
b.WriteString("{")
for _, r := range rs {
fmt.Fprintf(&b, "%q: %d, ", r, m[RID(r)])
}
bb := b.Bytes()
if len(bb) > 1 {
bb[len(bb)-2] = '}'
}
return string(bb)
}
type Bank struct {
available RMap
max map[PID]RMap
allocation map[PID]RMap
sync.Mutex
}
func (b *Bank) need(p PID, r RID) int {
return b.max[p][r] - b.allocation[p][r]
}
func New(available RMap) (b *Bank, err error) {
for r, a := range available {
if a < 0 {
return nil, fmt.Errorf("negative resource %s: %d", r, a)
}
}
return &Bank{
available: available,
max: map[PID]RMap{},
allocation: map[PID]RMap{},
}, nil
}
func (b *Bank) NewProcess(p PID, max RMap) (err error) {
b.Lock()
defer b.Unlock()
if _, ok := b.max[p]; ok {
return fmt.Errorf("process %s already registered", p)
}
for r, m := range max {
switch a, ok := b.available[r]; {
case !ok:
return fmt.Errorf("resource %s unknown", r)
case m > a:
return fmt.Errorf("resource %s: process %s max %d > available %d",
r, p, m, a)
}
}
b.max[p] = max
b.allocation[p] = RMap{}
return
}
func (b *Bank) Request(pid PID, change RMap) (err error) {
b.Lock()
defer b.Unlock()
if _, ok := b.max[pid]; !ok {
return fmt.Errorf("process %s unknown", pid)
}
for r, c := range change {
if c < 0 {
return errors.New("decrease not allowed")
}
if _, ok := b.available[r]; !ok {
return fmt.Errorf("resource %s unknown", r)
}
if c > b.need(pid, r) {
return errors.New("increase exceeds declared max")
}
}
for r, c := range change {
b.allocation[pid][r] += c
}
defer func() {
if err != nil {
for r, c := range change {
b.allocation[pid][r] -= c
}
}
}()
cash := RMap{}
for r, a := range b.available {
cash[r] = a
}
perm := make([]PID, len(b.allocation))
i := 1
for pr, a := range b.allocation {
if pr == pid {
perm[0] = pr
} else {
perm[i] = pr
i++
}
for r, a := range a {
cash[r] -= a
}
}
ret := RMap{}
m := len(perm)
for {
h := 0
h:
for ; ; h++ {
if h == m {
return errors.New("request would make deadlock possible")
}
for r := range b.available {
if b.need(perm[h], r) > cash[r]+ret[r] {
continue h
}
}
log.Println(" ", perm[h], "could terminate")
break
}
if h == 0 {
return nil
}
for r, a := range b.allocation[perm[h]] {
ret[r] += a
}
m--
perm[h] = perm[m]
}
}
| #include <stdio.h>
#include <stdbool.h>
int main() {
int curr[5][5];
int max_claim[5][5];
int avl[5];
int alloc[5] = {0, 0, 0, 0, 0};
int max_res[5];
int running[5];
int i, j, exec, r, p;
int count = 0;
bool safe = false;
printf("\nEnter the number of resources: ");
scanf("%d", &r);
printf("\nEnter the number of processes: ");
scanf("%d", &p);
for (i = 0; i < p; i++) {
running[i] = 1;
count++;
}
printf("\nEnter Claim Vector: ");
for (i = 0; i < r; i++)
scanf("%d", &max_res[i]);
printf("\nEnter Allocated Resource Table: ");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
scanf("%d", &curr[i][j]);
}
printf("\nEnter Maximum Claim table: ");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
scanf("%d", &max_claim[i][j]);
}
printf("\nThe Claim Vector is: ");
for (i = 0; i < r; i++)
printf("%d ", max_res[i]);
printf("\nThe Allocated Resource Table:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
printf("\t%d", curr[i][j]);
printf("\n");
}
printf("\nThe Maximum Claim Table:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
printf("\t%d", max_claim[i][j]);
printf("\n");
}
for (i = 0; i < p; i++)
for (j = 0; j < r; j++)
alloc[j] += curr[i][j];
printf("\nAllocated resources: ");
for (i = 0; i < r; i++)
printf("%d ", alloc[i]);
for (i = 0; i < r; i++)
avl[i] = max_res[i] - alloc[i];
printf("\nAvailable resources: ");
for (i = 0; i < r; i++)
printf("%d ", avl[i]);
printf("\n");
while (count != 0) {
safe = false;
for (i = 0; i < p; i++) {
if (running[i]) {
exec = 1;
for (j = 0; j < r; j++) {
if (max_claim[i][j] - curr[i][j] > avl[j]) {
exec = 0;
break;
}
}
if (exec) {
printf("\nProcess%d is executing.\n", i + 1);
running[i] = 0;
count--;
safe = true;
for (j = 0; j < r; j++)
avl[j] += curr[i][j];
break;
}
}
}
if (!safe) {
printf("\nThe processes are in unsafe state.");
break;
}
if (safe)
printf("\nThe process is in safe state.");
printf("\nAvailable vector: ");
for (i = 0; i < r; i++)
printf("%d ", avl[i]);
}
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
rf, err := rangeFormat([]int{
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39,
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("range format:", rf)
}
func rangeFormat(a []int) (string, error) {
if len(a) == 0 {
return "", nil
}
var parts []string
for n1 := 0; ; {
n2 := n1 + 1
for n2 < len(a) && a[n2] == a[n2-1]+1 {
n2++
}
s := strconv.Itoa(a[n1])
if n2 == n1+2 {
s += "," + strconv.Itoa(a[n2-1])
} else if n2 > n1+2 {
s += "-" + strconv.Itoa(a[n2-1])
}
parts = append(parts, s)
if n2 == len(a) {
break
}
if a[n2] == a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence repeats value %d", a[n2]))
}
if a[n2] < a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence not ordered: %d < %d", a[n2], a[n2-1]))
}
n1 = n2
}
return strings.Join(parts, ","), nil
}
| #include <stdio.h>
#include <stdlib.h>
size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "")
#define ol (s ? 100 : 0)
int i, j;
char *a = s;
for (i = j = 0; i < len; i = ++j) {
for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);
if (i + 1 < j)
a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
else
while (i <= j)
a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
}
return a - s;
#undef sep
#undef ol
}
int main()
{
int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39 };
char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
rprint(s, x, sizeof(x) / sizeof(int));
printf("%s\n", s);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
import "C"
func main() {
code := []byte{
0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,
}
le := len(code)
buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,
C.MAP_PRIVATE|C.MAP_ANON, -1, 0)
codePtr := C.CBytes(code)
C.memcpy(buf, codePtr, C.size_t(le))
var a, b byte = 7, 12
fmt.Printf("%d + %d = ", a, b)
C.runMachineCode(buf, C.byte(a), C.byte(b))
C.munmap(buf, C.size_t(le))
C.free(codePtr)
}
| #include <stdio.h>
#include <sys/mman.h>
#include <string.h>
int test (int a, int b)
{
char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
void *buf;
int c;
buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANON,-1,0);
memcpy (buf, code, sizeof(code));
c = ((int (*) (int, int))buf)(a, b);
munmap (buf, sizeof(code));
return c;
}
int main ()
{
printf("%d\n", test(7,12));
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import "fmt"
type any = interface{}
func showType(a any) {
switch a.(type) {
case rune:
fmt.Printf("The type of '%c' is %T\n", a, a)
default:
fmt.Printf("The type of '%v' is %T\n", a, a)
}
}
func main() {
values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"}
for _, value := range values {
showType(value)
}
}
| #include<stdio.h>
#include<ctype.h>
void typeDetector(char* str){
if(isalnum(str[0])!=0)
printf("\n%c is alphanumeric",str[0]);
if(isalpha(str[0])!=0)
printf("\n%c is alphabetic",str[0]);
if(iscntrl(str[0])!=0)
printf("\n%c is a control character",str[0]);
if(isdigit(str[0])!=0)
printf("\n%c is a digit",str[0]);
if(isprint(str[0])!=0)
printf("\n%c is printable",str[0]);
if(ispunct(str[0])!=0)
printf("\n%c is a punctuation character",str[0]);
if(isxdigit(str[0])!=0)
printf("\n%c is a hexadecimal digit",str[0]);
}
int main(int argC, char* argV[])
{
int i;
if(argC==1)
printf("Usage : %s <followed by ASCII characters>");
else{
for(i=1;i<argC;i++)
typeDetector(argV[i]);
}
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"strconv"
"strings"
)
const t = ` 55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`
func main() {
lines := strings.Split(t, "\n")
f := strings.Fields(lines[len(lines)-1])
d := make([]int, len(f))
var err error
for i, s := range f {
if d[i], err = strconv.Atoi(s); err != nil {
panic(err)
}
}
d1 := d[1:]
var l, r, u int
for row := len(lines) - 2; row >= 0; row-- {
l = d[0]
for i, s := range strings.Fields(lines[row]) {
if u, err = strconv.Atoi(s); err != nil {
panic(err)
}
if r = d1[i]; l > r {
d[i] = u + l
} else {
d[i] = u + r
}
l = r
}
}
fmt.Println(d[0])
}
| #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000`
func main() {
b := wbFromString(in, '1')
b.zhangSuen()
fmt.Println(b)
}
const (
white = 0
black = 1
)
type wbArray [][]byte
func wbFromString(s string, blk byte) wbArray {
lines := strings.Split(s, "\n")[1:]
b := make(wbArray, len(lines))
for i, sl := range lines {
bl := make([]byte, len(sl))
for j := 0; j < len(sl); j++ {
bl[j] = sl[j] & 1
}
b[i] = bl
}
return b
}
var sym = [2]byte{
white: ' ',
black: '#',
}
func (b wbArray) String() string {
b2 := bytes.Join(b, []byte{'\n'})
for i, b1 := range b2 {
if b1 > 1 {
continue
}
b2[i] = sym[b1]
}
return string(b2)
}
var nb = [...][2]int{
2: {-1, 0},
3: {-1, 1},
4: {0, 1},
5: {1, 1},
6: {1, 0},
7: {1, -1},
8: {0, -1},
9: {-1, -1},
}
func (b wbArray) reset(en []int) (rs bool) {
var r, c int
var p [10]byte
readP := func() {
for nx := 1; nx <= 9; nx++ {
n := nb[nx]
p[nx] = b[r+n[0]][c+n[1]]
}
}
shiftRead := func() {
n := nb[3]
p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]
n = nb[4]
p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]
n = nb[5]
p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]
}
countA := func() (ct byte) {
bit := p[9]
for nx := 2; nx <= 9; nx++ {
last := bit
bit = p[nx]
if last == white {
ct += bit
}
}
return ct
}
countB := func() (ct byte) {
for nx := 2; nx <= 9; nx++ {
ct += p[nx]
}
return ct
}
lastRow := len(b) - 1
lastCol := len(b[0]) - 1
mark := make([][]bool, lastRow)
for r = range mark {
mark[r] = make([]bool, lastCol)
}
for r = 1; r < lastRow; r++ {
c = 1
readP()
for {
m := false
if !(p[1] == black) {
goto markDone
}
if b1 := countB(); !(2 <= b1 && b1 <= 6) {
goto markDone
}
if !(countA() == 1) {
goto markDone
}
{
e1, e2 := p[en[1]], p[en[2]]
if !(p[en[0]]&e1&e2 == 0) {
goto markDone
}
if !(e1&e2&p[en[3]] == 0) {
goto markDone
}
}
m = true
rs = true
markDone:
mark[r][c] = m
c++
if c == lastCol {
break
}
shiftRead()
}
}
if rs {
for r = 1; r < lastRow; r++ {
for c = 1; c < lastCol; c++ {
if mark[r][c] {
b[r][c] = white
}
}
}
}
return rs
}
var step1 = []int{2, 4, 6, 8}
var step2 = []int{4, 2, 8, 6}
func (b wbArray) zhangSuen() {
for {
rs1 := b.reset(step1)
rs2 := b.reset(step2)
if !rs1 && !rs2 {
break
}
}
}
| #include<stdlib.h>
#include<stdio.h>
char** imageMatrix;
char blankPixel,imagePixel;
typedef struct{
int row,col;
}pixel;
int getBlackNeighbours(int row,int col){
int i,j,sum = 0;
for(i=-1;i<=1;i++){
for(j=-1;j<=1;j++){
if(i!=0 || j!=0)
sum+= (imageMatrix[row+i][col+j]==imagePixel);
}
}
return sum;
}
int getBWTransitions(int row,int col){
return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)
+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)
+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)
+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)
+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)
+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)
+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)
+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));
}
int zhangSuenTest1(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel)
&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));
}
int zhangSuenTest2(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));
}
void zhangSuen(char* inputFile, char* outputFile){
int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;
pixel* markers;
FILE* inputP = fopen(inputFile,"r");
fscanf(inputP,"%d%d",&rows,&cols);
fscanf(inputP,"%d%d",&blankPixel,&imagePixel);
blankPixel<=9?blankPixel+='0':blankPixel;
imagePixel<=9?imagePixel+='0':imagePixel;
printf("\nPrinting original image :\n");
imageMatrix = (char**)malloc(rows*sizeof(char*));
for(i=0;i<rows;i++){
imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));
fscanf(inputP,"%s\n",imageMatrix[i]);
printf("\n%s",imageMatrix[i]);
}
fclose(inputP);
endRow = rows-2;
endCol = cols-2;
do{
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
if(processed==0)
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
}while(processed==1);
FILE* outputP = fopen(outputFile,"w");
printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
printf("%c",imageMatrix[i][j]);
fprintf(outputP,"%c",imageMatrix[i][j]);
}
printf("\n");
fprintf(outputP,"\n");
}
fclose(outputP);
printf("\nImage also written to : %s",outputFile);
}
int main()
{
char inputFile[100],outputFile[100];
printf("Enter full path of input image file : ");
scanf("%s",inputFile);
printf("Enter full path of output image file : ");
scanf("%s",outputFile);
zhangSuen(inputFile,outputFile);
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"raster"
)
var g0, g1 *raster.Grmap
var ko [][]int
var kc []uint16
var mid int
func init() {
ko = [][]int{
{-1, -1}, {0, -1}, {1, -1},
{-1, 0}, {0, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1}}
kc = make([]uint16, len(ko))
mid = len(ko) / 2
}
func main() {
b, err := raster.ReadPpmFile("Lenna50.ppm")
if err != nil {
fmt.Println(err)
return
}
g0 = b.Grmap()
w, h := g0.Extent()
g1 = raster.NewGrmap(w, h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
g1.SetPx(x, y, median(x, y))
}
}
err = g1.Bitmap().WritePpmFile("median.ppm")
if err != nil {
fmt.Println(err)
}
}
func median(x, y int) uint16 {
var n int
for _, o := range ko {
c, ok := g0.GetPx(x+o[0], y+o[1])
if !ok {
continue
}
var i int
for ; i < n; i++ {
if c < kc[i] {
for j := n; j > i; j-- {
kc[j] = kc[j-1]
}
break
}
}
kc[i] = c
n++
}
switch {
case n == len(kc):
return kc[mid]
case n%2 == 1:
return kc[n/2]
}
m := n / 2
return (kc[m-1] + kc[m]) / 2
}
| #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
typedef struct { unsigned char r, g, b; } rgb_t;
typedef struct {
int w, h;
rgb_t **pix;
} image_t, *image;
typedef struct {
int r[256], g[256], b[256];
int n;
} color_histo_t;
int write_ppm(image im, char *fn)
{
FILE *fp = fopen(fn, "w");
if (!fp) return 0;
fprintf(fp, "P6\n%d %d\n255\n", im->w, im->h);
fwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);
fclose(fp);
return 1;
}
image img_new(int w, int h)
{
int i;
image im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)
+ sizeof(rgb_t) * w * h);
im->w = w; im->h = h;
im->pix = (rgb_t**)(im + 1);
for (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)
im->pix[i] = im->pix[i - 1] + w;
return im;
}
int read_num(FILE *f)
{
int n;
while (!fscanf(f, "%d ", &n)) {
if ((n = fgetc(f)) == '#') {
while ((n = fgetc(f)) != '\n')
if (n == EOF) break;
if (n == '\n') continue;
} else return 0;
}
return n;
}
image read_ppm(char *fn)
{
FILE *fp = fopen(fn, "r");
int w, h, maxval;
image im = 0;
if (!fp) return 0;
if (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))
goto bail;
w = read_num(fp);
h = read_num(fp);
maxval = read_num(fp);
if (!w || !h || !maxval) goto bail;
im = img_new(w, h);
fread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);
bail:
if (fp) fclose(fp);
return im;
}
void del_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]--;
h->g[pix->g]--;
h->b[pix->b]--;
h->n--;
}
}
void add_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]++;
h->g[pix->g]++;
h->b[pix->b]++;
h->n++;
}
}
void init_histo(image im, int row, int size, color_histo_t*h)
{
int j;
memset(h, 0, sizeof(color_histo_t));
for (j = 0; j < size && j < im->w; j++)
add_pixels(im, row, j, size, h);
}
int median(const int *x, int n)
{
int i;
for (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);
return i;
}
void median_color(rgb_t *pix, const color_histo_t *h)
{
pix->r = median(h->r, h->n);
pix->g = median(h->g, h->n);
pix->b = median(h->b, h->n);
}
image median_filter(image in, int size)
{
int row, col;
image out = img_new(in->w, in->h);
color_histo_t h;
for (row = 0; row < in->h; row ++) {
for (col = 0; col < in->w; col++) {
if (!col) init_histo(in, row, size, &h);
else {
del_pixels(in, row, col - size, size, &h);
add_pixels(in, row, col + size, size, &h);
}
median_color(out->pix[row] + col, &h);
}
}
return out;
}
int main(int c, char **v)
{
int size;
image in, out;
if (c <= 3) {
printf("Usage: %s size ppm_in ppm_out\n", v[0]);
return 0;
}
size = atoi(v[1]);
printf("filter size %d\n", size);
if (size < 0) size = 1;
in = read_ppm(v[2]);
out = median_filter(in, size);
write_ppm(out, v[3]);
free(in);
free(out);
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"github.com/sevlyar/go-daemon"
"log"
"os"
"time"
)
func work() {
f, err := os.Create("daemon_output.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {
fmt.Fprintln(f, t)
}
}()
time.Sleep(60 * time.Second)
ticker.Stop()
log.Print("ticker stopped")
}
func main() {
cntxt := &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
LogFileName: "log",
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[Rosetta Code daemon example]"},
}
d, err := cntxt.Reborn()
if err != nil {
log.Fatal("Unable to run: ", err)
}
if d != nil {
return
}
defer cntxt.Release()
log.Print("- - - - - - - - - - - - - - -")
log.Print("daemon started")
work()
}
| #include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
extern char *__progname;
time_t clock;
int fd;
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", __progname);
exit(1);
}
fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
err(1, argv[1]);
if (daemon(0, 0) < 0)
err(1, "daemon");
if (dup2(fd, STDOUT_FILENO) < 0) {
syslog(LOG_ERR, "dup2: %s", strerror(errno));
exit(1);
}
close(fd);
for (;;) {
time(&clock);
fputs(ctime(&clock), stdout);
if (fflush(stdout) == EOF) {
syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno));
exit(1);
}
sleep(1);
}
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"github.com/sevlyar/go-daemon"
"log"
"os"
"time"
)
func work() {
f, err := os.Create("daemon_output.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
ticker := time.NewTicker(time.Second)
go func() {
for t := range ticker.C {
fmt.Fprintln(f, t)
}
}()
time.Sleep(60 * time.Second)
ticker.Stop()
log.Print("ticker stopped")
}
func main() {
cntxt := &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
LogFileName: "log",
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[Rosetta Code daemon example]"},
}
d, err := cntxt.Reborn()
if err != nil {
log.Fatal("Unable to run: ", err)
}
if d != nil {
return
}
defer cntxt.Release()
log.Print("- - - - - - - - - - - - - - -")
log.Print("daemon started")
work()
}
| #include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
extern char *__progname;
time_t clock;
int fd;
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", __progname);
exit(1);
}
fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
err(1, argv[1]);
if (daemon(0, 0) < 0)
err(1, "daemon");
if (dup2(fd, STDOUT_FILENO) < 0) {
syslog(LOG_ERR, "dup2: %s", strerror(errno));
exit(1);
}
close(fd);
for (;;) {
time(&clock);
fputs(ctime(&clock), stdout);
if (fflush(stdout) == EOF) {
syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno));
exit(1);
}
sleep(1);
}
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"go/parser"
"regexp"
"strings"
)
var (
re1 = regexp.MustCompile(`[^_a-zA-Z0-9\+\-\*/=<\(\)\s]`)
re2 = regexp.MustCompile(`\b_\w*\b`)
re3 = regexp.MustCompile(`[=<+*/-]\s*not`)
re4 = regexp.MustCompile(`(=|<)\s*[^(=< ]+\s*([=<+*/-])`)
)
var subs = [][2]string{
{"=", "=="}, {" not ", " ! "}, {"(not ", "(! "}, {" or ", " || "}, {" and ", " && "},
}
func possiblyValid(expr string) error {
matches := re1.FindStringSubmatch(expr)
if matches != nil {
return fmt.Errorf("invalid character %q found", []rune(matches[0])[0])
}
if re2.MatchString(expr) {
return fmt.Errorf("identifier cannot begin with an underscore")
}
if re3.MatchString(expr) {
return fmt.Errorf("expected operand, found 'not'")
}
matches = re4.FindStringSubmatch(expr)
if matches != nil {
return fmt.Errorf("operator %q is non-associative", []rune(matches[1])[0])
}
return nil
}
func modify(err error) string {
e := err.Error()
for _, sub := range subs {
e = strings.ReplaceAll(e, strings.TrimSpace(sub[1]), strings.TrimSpace(sub[0]))
}
return strings.Split(e, ":")[2][1:]
}
func main() {
exprs := []string{
"$",
"one",
"either or both",
"a + 1",
"a + b < c",
"a = b",
"a or b = c",
"3 + not 5",
"3 + (not 5)",
"(42 + 3",
"(42 + 3)",
" not 3 < 4 or (true or 3 / 4 + 8 * 5 - 5 * 2 < 56) and 4 * 3 < 12 or not true",
" and 3 < 2",
"not 7 < 2",
"2 < 3 < 4",
"2 < (3 < 4)",
"2 < foobar - 3 < 4",
"2 < foobar and 3 < 4",
"4 * (32 - 16) + 9 = 73",
"235 76 + 1",
"true or false = not true",
"true or false = (not true)",
"not true or false = false",
"not true = false",
"a + b = not c and false",
"a + b = (not c) and false",
"a + b = (not c and false)",
"ab_c / bd2 or < e_f7",
"g not = h",
"été = false",
"i++",
"j & k",
"l or _m",
}
for _, expr := range exprs {
fmt.Printf("Statement to verify: %q\n", expr)
if err := possiblyValid(expr); err != nil {
fmt.Printf("\"false\" -> %s\n\n", err.Error())
continue
}
expr = fmt.Sprintf(" %s ", expr)
for _, sub := range subs {
expr = strings.ReplaceAll(expr, sub[0], sub[1])
}
_, err := parser.ParseExpr(expr)
if err != nil {
fmt.Println(`"false" ->`, modify(err))
} else {
fmt.Println(`"true"`)
}
fmt.Println()
}
}
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <setjmp.h>
#define AT(CHAR) ( *pos == CHAR && ++pos )
#define TEST(STR) ( strncmp( pos, STR, strlen(STR) ) == 0 \
&& ! isalnum(pos[strlen(STR)]) && pos[strlen(STR)] != '_' )
#define IS(STR) ( TEST(STR) && (pos += strlen(STR)) )
static char *pos;
static char *startpos;
static jmp_buf jmpenv;
static int
error(char *message)
{
printf("false %s\n%*s^ %s\n", startpos, pos - startpos + 7, "", message);
longjmp( jmpenv, 1 );
}
static int
expr(int level)
{
while( isspace(*pos) ) ++pos;
if( AT('(') )
{
if( expr(0) && ! AT(')') ) error("missing close paren");
}
else if( level <= 4 && IS("not") && expr(6) ) { }
else if( TEST("or") || TEST("and") || TEST("not") )
{
error("expected a primary, found an operator");
}
else if( isdigit(*pos) ) pos += strspn( pos, "0123456789" );
else if( isalpha(*pos) ) pos += strspn( pos, "0123456789_"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" );
else error("expected a primary");
do
{
while( isspace(*pos) ) ++pos;
}
while(
level <= 2 && IS("or") ? expr(3) :
level <= 3 && IS("and") ? expr(4) :
level <= 4 && (AT('=') || AT('<')) ? expr(5) :
level == 5 && (*pos == '=' || *pos == '<') ? error("non-associative") :
level <= 6 && (AT('+') || AT('-')) ? expr(7) :
level <= 7 && (AT('*') || AT('/')) ? expr(8) :
0 );
return 1;
}
static void
parse(char *source)
{
startpos = pos = source;
if( setjmp(jmpenv) ) return;
expr(0);
if( *pos ) error("unexpected character following valid parse");
printf(" true %s\n", source);
}
static char *tests[] = {
"3 + not 5",
"3 + (not 5)",
"(42 + 3",
"(42 + 3 some_other_syntax_error",
"not 3 < 4 or (true or 3/4+8*5-5*2 < 56) and 4*3 < 12 or not true",
"and 3 < 2",
"not 7 < 2",
"2 < 3 < 4",
"2 < foobar - 3 < 4",
"2 < foobar and 3 < 4",
"4 * (32 - 16) + 9 = 73",
"235 76 + 1",
"a + b = not c and false",
"a + b = (not c) and false",
"a + b = (not c and false)",
"ab_c / bd2 or < e_f7",
"g not = h",
"i++",
"j & k",
"l or _m",
"wombat",
"WOMBAT or monotreme",
"a + b - c * d / e < f and not ( g = h )",
"$",
};
int
main(int argc, char *argv[])
{
for( int i = 0; i < sizeof(tests)/sizeof(*tests); i++ ) parse(tests[i]);
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"rcu"
)
func contains(a []int, v int) bool {
for _, e := range a {
if e == v {
return true
}
}
return false
}
func main() {
const limit = 50
cpt := []int{1, 2}
for {
m := 1
l := len(cpt)
for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {
m++
}
if m >= limit {
break
}
cpt = append(cpt, m)
}
fmt.Printf("Coprime triplets under %d:\n", limit)
for i, t := range cpt {
fmt.Printf("%2d ", t)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\nFound %d such numbers\n", len(cpt))
}
|
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"rcu"
)
func contains(a []int, v int) bool {
for _, e := range a {
if e == v {
return true
}
}
return false
}
func main() {
const limit = 50
cpt := []int{1, 2}
for {
m := 1
l := len(cpt)
for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {
m++
}
if m >= limit {
break
}
cpt = append(cpt, m)
}
fmt.Printf("Coprime triplets under %d:\n", limit)
for i, t := range cpt {
fmt.Printf("%2d ", t)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\nFound %d such numbers\n", len(cpt))
}
|
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"rcu"
)
func contains(a []int, v int) bool {
for _, e := range a {
if e == v {
return true
}
}
return false
}
func main() {
const limit = 50
cpt := []int{1, 2}
for {
m := 1
l := len(cpt)
for contains(cpt, m) || rcu.Gcd(m, cpt[l-1]) != 1 || rcu.Gcd(m, cpt[l-2]) != 1 {
m++
}
if m >= limit {
break
}
cpt = append(cpt, m)
}
fmt.Printf("Coprime triplets under %d:\n", limit)
for i, t := range cpt {
fmt.Printf("%2d ", t)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\nFound %d such numbers\n", len(cpt))
}
|
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import "fmt"
func main() {
s := []int{1, 2, 2, 3, 4, 4, 5}
for i := 0; i < len(s); i++ {
curr := s[i]
var prev int
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
var prev int
for i := 0; i < len(s); i++ {
curr := s[i]
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
}
| #include <stdio.h>
int main() {
int i, gprev = 0;
int s[7] = {1, 2, 2, 3, 4, 4, 5};
for (i = 0; i < 7; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) printf("%d\n", i);
prev = curr;
}
for (i = 0; i < 7; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) printf("%d\n", i);
gprev = curr;
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"github.com/tiaguinho/gosoap"
"log"
)
type CheckVatResponse struct {
CountryCode string `xml:"countryCode"`
VatNumber string `xml:"vatNumber"`
RequestDate string `xml:"requestDate"`
Valid string `xml:"valid"`
Name string `xml:"name"`
Address string `xml:"address"`
}
var (
rv CheckVatResponse
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
soap, err := gosoap.SoapClient("http:
params := gosoap.Params{
"vatNumber": "6388047V",
"countryCode": "IE",
}
err = soap.Call("checkVat", params)
check(err)
err = soap.Unmarshal(&rv)
check(err)
fmt.Println("Country Code : ", rv.CountryCode)
fmt.Println("Vat Number : ", rv.VatNumber)
fmt.Println("Request Date : ", rv.RequestDate)
fmt.Println("Valid : ", rv.Valid)
fmt.Println("Name : ", rv.Name)
fmt.Println("Address : ", rv.Address)
}
| #include <curl/curl.h>
#include <string.h>
#include <stdio.h>
size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fwrite(ptr,size,nmeb,stream);
}
size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fread(ptr,size,nmeb,stream);
}
void callSOAP(char* URL, char * inFile, char * outFile) {
FILE * rfp = fopen(inFile, "r");
if(!rfp)
perror("Read File Open:");
FILE * wfp = fopen(outFile, "w+");
if(!wfp)
perror("Write File Open:");
struct curl_slist *header = NULL;
header = curl_slist_append (header, "Content-Type:text/xml");
header = curl_slist_append (header, "SOAPAction: rsc");
header = curl_slist_append (header, "Transfer-Encoding: chunked");
header = curl_slist_append (header, "Expect:");
CURL *curl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_READDATA, rfp);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);
curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=4)
printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]);
else
callSOAP(argV[1],argV[2],argV[3]);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. |
#include<stdio.h>
#define Hi printf("Hi There.");
#define start int main(){
#define end return 0;}
start
Hi
#warning "Don't you have anything better to do ?"
#ifdef __unix__
#warning "What are you doing still working on Unix ?"
printf("\nThis is an Unix system.");
#elif _WIN32
#warning "You couldn't afford a 64 bit ?"
printf("\nThis is a 32 bit Windows system.");
#elif _WIN64
#warning "You couldn't afford an Apple ?"
printf("\nThis is a 64 bit Windows system.");
#endif
end
| |
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"math/big"
)
const (
mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota
mask1, bit1
mask2, bit2
mask3, bit3
mask4, bit4
mask5, bit5
)
func rupb(x uint64) (out int) {
if x == 0 {
return -1
}
if x&^mask5 != 0 {
x >>= bit5
out |= bit5
}
if x&^mask4 != 0 {
x >>= bit4
out |= bit4
}
if x&^mask3 != 0 {
x >>= bit3
out |= bit3
}
if x&^mask2 != 0 {
x >>= bit2
out |= bit2
}
if x&^mask1 != 0 {
x >>= bit1
out |= bit1
}
if x&^mask0 != 0 {
out |= bit0
}
return
}
func rlwb(x uint64) (out int) {
if x == 0 {
return 0
}
if x&mask5 == 0 {
x >>= bit5
out |= bit5
}
if x&mask4 == 0 {
x >>= bit4
out |= bit4
}
if x&mask3 == 0 {
x >>= bit3
out |= bit3
}
if x&mask2 == 0 {
x >>= bit2
out |= bit2
}
if x&mask1 == 0 {
x >>= bit1
out |= bit1
}
if x&mask0 == 0 {
out |= bit0
}
return
}
func rupbBig(x *big.Int) int {
return x.BitLen() - 1
}
func rlwbBig(x *big.Int) int {
if x.BitLen() < 2 {
return 0
}
bit := uint(1)
mask := big.NewInt(1)
var ms []*big.Int
var y, z big.Int
for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {
ms = append(ms, mask)
mask = new(big.Int).Or(mask, &z)
bit <<= 1
}
out := bit
for i := len(ms) - 1; i >= 0; i-- {
bit >>= 1
if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {
out |= bit
}
}
return int(out)
}
func main() {
show()
showBig()
}
func show() {
fmt.Println("uint64:")
fmt.Println("power number rupb rlwb")
const base = 42
n := uint64(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n))
n *= base
}
}
func showBig() {
fmt.Println("\nbig numbers:")
fmt.Println(" power number rupb rlwb")
base := big.NewInt(1302)
n := big.NewInt(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n))
n.Mul(n, base)
}
}
| #include <stdio.h>
#include <stdint.h>
uint32_t msb32(uint32_t n)
{
uint32_t b = 1;
if (!n) return 0;
#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
int msb32_idx(uint32_t n)
{
int b = 0;
if (!n) return -1;
#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )
inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }
int main()
{
int32_t n;
int i;
for (i = 0, n = 1; ; i++, n *= 42) {
printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n, n,
msb32(n), msb32_idx(n),
lsb32(n), lsb32_idx(n));
if (n >= INT32_MAX / 42) break;
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"math/big"
)
const (
mask0, bit0 = (1 << (1 << iota)) - 1, 1 << iota
mask1, bit1
mask2, bit2
mask3, bit3
mask4, bit4
mask5, bit5
)
func rupb(x uint64) (out int) {
if x == 0 {
return -1
}
if x&^mask5 != 0 {
x >>= bit5
out |= bit5
}
if x&^mask4 != 0 {
x >>= bit4
out |= bit4
}
if x&^mask3 != 0 {
x >>= bit3
out |= bit3
}
if x&^mask2 != 0 {
x >>= bit2
out |= bit2
}
if x&^mask1 != 0 {
x >>= bit1
out |= bit1
}
if x&^mask0 != 0 {
out |= bit0
}
return
}
func rlwb(x uint64) (out int) {
if x == 0 {
return 0
}
if x&mask5 == 0 {
x >>= bit5
out |= bit5
}
if x&mask4 == 0 {
x >>= bit4
out |= bit4
}
if x&mask3 == 0 {
x >>= bit3
out |= bit3
}
if x&mask2 == 0 {
x >>= bit2
out |= bit2
}
if x&mask1 == 0 {
x >>= bit1
out |= bit1
}
if x&mask0 == 0 {
out |= bit0
}
return
}
func rupbBig(x *big.Int) int {
return x.BitLen() - 1
}
func rlwbBig(x *big.Int) int {
if x.BitLen() < 2 {
return 0
}
bit := uint(1)
mask := big.NewInt(1)
var ms []*big.Int
var y, z big.Int
for y.And(x, z.Lsh(mask, bit)).BitLen() == 0 {
ms = append(ms, mask)
mask = new(big.Int).Or(mask, &z)
bit <<= 1
}
out := bit
for i := len(ms) - 1; i >= 0; i-- {
bit >>= 1
if y.And(x, z.Lsh(ms[i], out)).BitLen() == 0 {
out |= bit
}
}
return int(out)
}
func main() {
show()
showBig()
}
func show() {
fmt.Println("uint64:")
fmt.Println("power number rupb rlwb")
const base = 42
n := uint64(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %19d %5d %5d\n", base, i, n, rupb(n), rlwb(n))
n *= base
}
}
func showBig() {
fmt.Println("\nbig numbers:")
fmt.Println(" power number rupb rlwb")
base := big.NewInt(1302)
n := big.NewInt(1)
for i := 0; i < 12; i++ {
fmt.Printf("%d^%02d %36d %5d %5d\n", base, i, n, rupbBig(n), rlwbBig(n))
n.Mul(n, base)
}
}
| #include <stdio.h>
#include <stdint.h>
uint32_t msb32(uint32_t n)
{
uint32_t b = 1;
if (!n) return 0;
#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
int msb32_idx(uint32_t n)
{
int b = 0;
if (!n) return -1;
#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )
inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }
int main()
{
int32_t n;
int i;
for (i = 0, n = 1; ; i++, n *= 42) {
printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n, n,
msb32(n), msb32_idx(n),
lsb32(n), lsb32_idx(n));
if (n >= INT32_MAX / 42) break;
}
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import "fmt"
func risesEqualsFalls(n int) bool {
if n < 10 {
return true
}
rises := 0
falls := 0
prev := -1
for n > 0 {
d := n % 10
if prev >= 0 {
if d < prev {
rises = rises + 1
} else if d > prev {
falls = falls + 1
}
}
prev = d
n /= 10
}
return rises == falls
}
func main() {
fmt.Println("The first 200 numbers in the sequence are:")
count := 0
n := 1
for {
if risesEqualsFalls(n) {
count++
if count <= 200 {
fmt.Printf("%3d ", n)
if count%20 == 0 {
fmt.Println()
}
}
if count == 1e7 {
fmt.Println("\nThe 10 millionth number in the sequence is ", n)
break
}
}
n++
}
}
| #include <stdio.h>
int riseEqFall(int num) {
int rdigit = num % 10;
int netHeight = 0;
while (num /= 10) {
netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
rdigit = num % 10;
}
return netHeight == 0;
}
int nextNum() {
static int num = 0;
do {num++;} while (!riseEqFall(num));
return num;
}
int main(void) {
int total, num;
printf("The first 200 numbers are: \n");
for (total = 0; total < 200; total++)
printf("%d ", nextNum());
printf("\n\nThe 10,000,000th number is: ");
for (; total < 10000000; total++) num = nextNum();
printf("%d\n", num);
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"time"
"os"
"os/exec"
"strconv"
)
func main() {
tput("clear")
tput("cup", "6", "3")
time.Sleep(1 * time.Second)
tput("cub1")
time.Sleep(1 * time.Second)
tput("cuf1")
time.Sleep(1 * time.Second)
tput("cuu1")
time.Sleep(1 * time.Second)
tput("cud", "1")
time.Sleep(1 * time.Second)
tput("cr")
time.Sleep(1 * time.Second)
var h, w int
cmd := exec.Command("stty", "size")
cmd.Stdin = os.Stdin
d, _ := cmd.Output()
fmt.Sscan(string(d), &h, &w)
tput("hpa", strconv.Itoa(w-1))
time.Sleep(2 * time.Second)
tput("home")
time.Sleep(2 * time.Second)
tput("cup", strconv.Itoa(h-1), strconv.Itoa(w-1))
time.Sleep(3 * time.Second)
}
func tput(args ...string) error {
cmd := exec.Command("tput", args...)
cmd.Stdout = os.Stdout
return cmd.Run()
}
| #include<conio.h>
#include<dos.h>
char *strings[] = {"The cursor will move one position to the left",
"The cursor will move one position to the right",
"The cursor will move vetically up one line",
"The cursor will move vertically down one line",
"The cursor will move to the beginning of the line",
"The cursor will move to the end of the line",
"The cursor will move to the top left corner of the screen",
"The cursor will move to the bottom right corner of the screen"};
int main()
{
int i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
clrscr();
cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue.");
getch();
for(i=0;i<8;i++)
{
clrscr();
gotoxy(5,MAXROW/2);
cprintf("%s",strings[i]);
getch();
switch(i){
case 0:gotoxy(wherex()-1,wherey());
break;
case 1:gotoxy(wherex()+1,wherey());
break;
case 2:gotoxy(wherex(),wherey()-1);
break;
case 3:gotoxy(wherex(),wherey()+1);
break;
case 4:for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()-1,wherey());
delay(100);
}
break;
case 5:gotoxy(wherex()-strlen(strings[i]),wherey());
for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()+1,wherey());
delay(100);
}
break;
case 6:while(wherex()!=1)
{
gotoxy(wherex()-1,wherey());
delay(100);
}
while(wherey()!=1)
{
gotoxy(wherex(),wherey()-1);
delay(100);
}
break;
case 7:while(wherex()!=MAXCOL)
{
gotoxy(wherex()+1,wherey());
delay(100);
}
while(wherey()!=MAXROW)
{
gotoxy(wherex(),wherey()+1);
delay(100);
}
break;
};
getch();
}
clrscr();
cprintf("End of demonstration.");
getch();
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
var (
dists = calcDists()
dirs = [8]int{1, -1, 10, -10, 9, 11, -11, -9}
)
func calcDists() []float64 {
dists := make([]float64, 10000)
for i := 0; i < 10000; i++ {
ab, cd := math.Floor(float64(i)/100), float64(i%100)
a, b := math.Floor(ab/10), float64(int(ab)%10)
c, d := math.Floor(cd/10), float64(int(cd)%10)
dists[i] = math.Hypot(a-c, b-d)
}
return dists
}
func dist(ci, cj int) float64 {
return dists[cj*100+ci]
}
func Es(path []int) float64 {
d := 0.0
for i := 0; i < len(path)-1; i++ {
d += dist(path[i], path[i+1])
}
return d
}
func T(k, kmax, kT int) float64 {
return (1 - float64(k)/float64(kmax)) * float64(kT)
}
func dE(s []int, u, v int) float64 {
su, sv := s[u], s[v]
a, b, c, d := dist(s[u-1], su), dist(s[u+1], su), dist(s[v-1], sv), dist(s[v+1], sv)
na, nb, nc, nd := dist(s[u-1], sv), dist(s[u+1], sv), dist(s[v-1], su), dist(s[v+1], su)
if v == u+1 {
return (na + nd) - (a + d)
} else if u == v+1 {
return (nc + nb) - (c + b)
} else {
return (na + nb + nc + nd) - (a + b + c + d)
}
}
func P(deltaE float64, k, kmax, kT int) float64 {
return math.Exp(-deltaE / T(k, kmax, kT))
}
func sa(kmax, kT int) {
rand.Seed(time.Now().UnixNano())
temp := make([]int, 99)
for i := 0; i < 99; i++ {
temp[i] = i + 1
}
rand.Shuffle(len(temp), func(i, j int) {
temp[i], temp[j] = temp[j], temp[i]
})
s := make([]int, 101)
copy(s[1:], temp)
fmt.Println("kT =", kT)
fmt.Printf("E(s0) %f\n\n", Es(s))
Emin := Es(s)
for k := 0; k <= kmax; k++ {
if k%(kmax/10) == 0 {
fmt.Printf("k:%10d T: %8.4f Es: %8.4f\n", k, T(k, kmax, kT), Es(s))
}
u := 1 + rand.Intn(99)
cv := s[u] + dirs[rand.Intn(8)]
if cv <= 0 || cv >= 100 {
continue
}
if dist(s[u], cv) > 5 {
continue
}
v := s[cv]
deltae := dE(s, u, v)
if deltae < 0 ||
P(deltae, k, kmax, kT) >= rand.Float64() {
s[u], s[v] = s[v], s[u]
Emin += deltae
}
}
fmt.Printf("\nE(s_final) %f\n", Emin)
fmt.Println("Path:")
for i := 0; i < len(s); i++ {
if i > 0 && i%10 == 0 {
fmt.Println()
}
fmt.Printf("%4d", s[i])
}
fmt.Println()
}
func main() {
sa(1e6, 1)
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#define VECSZ 100
#define STATESZ 64
typedef float floating_pt;
#define EXP expf
#define SQRT sqrtf
static floating_pt
randnum (void)
{
return (floating_pt)
((double) (random () & 2147483647) / 2147483648.0);
}
static void
shuffle (uint8_t vec[], size_t i, size_t n)
{
for (size_t j = 0; j != n; j += 1)
{
size_t k = i + j + (random () % (n - j));
uint8_t xi = vec[i];
uint8_t xk = vec[k];
vec[i] = xk;
vec[k] = xi;
}
}
static void
init_s (uint8_t vec[VECSZ])
{
for (uint8_t j = 0; j != VECSZ; j += 1)
vec[j] = j;
shuffle (vec, 1, VECSZ - 1);
}
static inline void
add_neighbor (uint8_t neigh[8],
unsigned int *neigh_size,
uint8_t neighbor)
{
if (neighbor != 0)
{
neigh[*neigh_size] = neighbor;
*neigh_size += 1;
}
}
static void
neighborhood (uint8_t neigh[8],
unsigned int *neigh_size,
uint8_t city)
{
const uint8_t i = city / 10;
const uint8_t j = city % 10;
uint8_t c0 = 0;
uint8_t c1 = 0;
uint8_t c2 = 0;
uint8_t c3 = 0;
uint8_t c4 = 0;
uint8_t c5 = 0;
uint8_t c6 = 0;
uint8_t c7 = 0;
if (i < 9)
{
c0 = (10 * (i + 1)) + j;
if (j < 9)
c1 = (10 * (i + 1)) + (j + 1);
if (0 < j)
c2 = (10 * (i + 1)) + (j - 1);
}
if (0 < i)
{
c3 = (10 * (i - 1)) + j;
if (j < 9)
c4 = (10 * (i - 1)) + (j + 1);
if (0 < j)
c5 = (10 * (i - 1)) + (j - 1);
}
if (j < 9)
c6 = (10 * i) + (j + 1);
if (0 < j)
c7 = (10 * i) + (j - 1);
*neigh_size = 0;
add_neighbor (neigh, neigh_size, c0);
add_neighbor (neigh, neigh_size, c1);
add_neighbor (neigh, neigh_size, c2);
add_neighbor (neigh, neigh_size, c3);
add_neighbor (neigh, neigh_size, c4);
add_neighbor (neigh, neigh_size, c5);
add_neighbor (neigh, neigh_size, c6);
add_neighbor (neigh, neigh_size, c7);
}
static floating_pt
distance (uint8_t m, uint8_t n)
{
const uint8_t im = m / 10;
const uint8_t jm = m % 10;
const uint8_t in = n / 10;
const uint8_t jn = n % 10;
const int di = (int) im - (int) in;
const int dj = (int) jm - (int) jn;
return SQRT ((di * di) + (dj * dj));
}
static floating_pt
path_length (uint8_t vec[VECSZ])
{
floating_pt len = distance (vec[0], vec[VECSZ - 1]);
for (size_t j = 0; j != VECSZ - 1; j += 1)
len += distance (vec[j], vec[j + 1]);
return len;
}
static void
swap_s_elements (uint8_t vec[], uint8_t u, uint8_t v)
{
size_t j = 1;
size_t iu = 0;
size_t iv = 0;
while (iu == 0 || iv == 0)
{
if (vec[j] == u)
iu = j;
else if (vec[j] == v)
iv = j;
j += 1;
}
vec[iu] = v;
vec[iv] = u;
}
static void
update_s (uint8_t vec[])
{
const uint8_t u = 1 + (random () % (VECSZ - 1));
uint8_t neighbors[8];
unsigned int num_neighbors;
neighborhood (neighbors, &num_neighbors, u);
const uint8_t v = neighbors[random () % num_neighbors];
swap_s_elements (vec, u, v);
}
static inline void
copy_s (uint8_t dst[VECSZ], uint8_t src[VECSZ])
{
memcpy (dst, src, VECSZ * (sizeof src[0]));
}
static void
trial_s (uint8_t trial[VECSZ], uint8_t vec[VECSZ])
{
copy_s (trial, vec);
update_s (trial);
}
static floating_pt
temperature (floating_pt kT, unsigned int kmax, unsigned int k)
{
return kT * (1 - ((floating_pt) k / (floating_pt) kmax));
}
static floating_pt
probability (floating_pt delta_E, floating_pt T)
{
floating_pt prob;
if (delta_E < 0)
prob = 1;
else if (T == 0)
prob = 0;
else
prob = EXP (-(delta_E / T));
return prob;
}
static void
show (unsigned int k, floating_pt T, floating_pt E)
{
printf (" %7u %7.1f %13.5f\n", k, (double) T, (double) E);
}
static void
simulate_annealing (floating_pt kT,
unsigned int kmax,
uint8_t s[VECSZ])
{
uint8_t trial[VECSZ];
unsigned int kshow = kmax / 10;
floating_pt E = path_length (s);
for (unsigned int k = 0; k != kmax + 1; k += 1)
{
const floating_pt T = temperature (kT, kmax, k);
if (k % kshow == 0)
show (k, T, E);
trial_s (trial, s);
const floating_pt E_trial = path_length (trial);
const floating_pt delta_E = E_trial - E;
const floating_pt P = probability (delta_E, T);
if (P == 1 || randnum () <= P)
{
copy_s (s, trial);
E = E_trial;
}
}
}
static void
display_path (uint8_t vec[VECSZ])
{
for (size_t i = 0; i != VECSZ; i += 1)
{
const uint8_t x = vec[i];
printf ("%2u ->", (unsigned int) x);
if ((i % 8) == 7)
printf ("\n");
else
printf (" ");
}
printf ("%2u\n", vec[0]);
}
int
main (void)
{
char state[STATESZ];
uint32_t seed[1];
int status = getentropy (&seed[0], sizeof seed[0]);
if (status < 0)
seed[0] = 1;
initstate (seed[0], state, STATESZ);
floating_pt kT = 1.0;
unsigned int kmax = 1000000;
uint8_t s[VECSZ];
init_s (s);
printf ("\n");
printf (" kT: %f\n", (double) kT);
printf (" kmax: %u\n", kmax);
printf ("\n");
printf (" k T E(s)\n");
printf (" -----------------------------\n");
simulate_annealing (kT, kmax, s);
printf ("\n");
display_path (s);
printf ("\n");
printf ("Final E(s): %.5f\n", (double) path_length (s));
printf ("\n");
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
var count = 0
func foo() {
fmt.Println("foo called")
}
func init() {
fmt.Println("first init called")
foo()
}
func init() {
fmt.Println("second init called")
main()
}
func main() {
count++
fmt.Println("main called when count is", count)
}
| #include<stdio.h>
#define start main()
int start
{
printf("Hello World !");
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import "fmt"
var count = 0
func foo() {
fmt.Println("foo called")
}
func init() {
fmt.Println("first init called")
foo()
}
func init() {
fmt.Println("second init called")
main()
}
func main() {
count++
fmt.Println("main called when count is", count)
}
| #include<stdio.h>
#define start main()
int start
{
printf("Hello World !");
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"fmt"
"rcu"
)
func main() {
sum := 0
for _, p := range rcu.Primes(2e6 - 1) {
sum += p
}
fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum))
}
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int main( void ) {
int p;
long int s = 2;
for(p=3;p<2000000;p+=2) {
if(isprime(p)) s+=p;
}
printf( "%ld\n", s );
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"github.com/fogleman/gg"
"math"
)
var dc = gg.NewContext(512, 512)
func koch(x1, y1, x2, y2 float64, iter int) {
angle := math.Pi / 3
x3 := (x1*2 + x2) / 3
y3 := (y1*2 + y2) / 3
x4 := (x1 + x2*2) / 3
y4 := (y1 + y2*2) / 3
x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)
y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)
if iter > 0 {
iter--
koch(x1, y1, x3, y3, iter)
koch(x3, y3, x5, y5, iter)
koch(x5, y5, x4, y4, iter)
koch(x4, y4, x2, y2, iter)
} else {
dc.LineTo(x1, y1)
dc.LineTo(x3, y3)
dc.LineTo(x5, y5)
dc.LineTo(x4, y4)
dc.LineTo(x2, y2)
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
koch(100, 100, 400, 400, 4)
dc.SetRGB(0, 0, 1)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("koch.png")
}
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}point;
void kochCurve(point p1,point p2,int times){
point p3,p4,p5;
double theta = pi/3;
if(times>0){
p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
kochCurve(p1,p3,times-1);
kochCurve(p3,p4,times-1);
kochCurve(p4,p5,times-1);
kochCurve(p5,p2,times-1);
}
else{
line(p1.x,p1.y,p2.x,p2.y);
}
}
int main(int argC, char** argV)
{
int w,h,r;
point p1,p2;
if(argC!=4){
printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
}
else{
w = atoi(argV[1]);
h = atoi(argV[2]);
r = atoi(argV[3]);
initwindow(w,h,"Koch Curve");
p1 = (point){10,h-10};
p2 = (point){w-10,h-10};
kochCurve(p1,p2,r);
getch();
closegraph();
}
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"math/rand"
"time"
)
func main() {
rect := image.Rect(0, 0, 640, 480)
img := image.NewRGBA(rect)
blue := color.RGBA{0, 0, 255, 255}
draw.Draw(img, rect, &image.Uniform{blue}, image.ZP, draw.Src)
yellow := color.RGBA{255, 255, 0, 255}
width := img.Bounds().Dx()
height := img.Bounds().Dy()
rand.Seed(time.Now().UnixNano())
x := rand.Intn(width)
y := rand.Intn(height)
img.Set(x, y, yellow)
cmap := map[color.Color]string{blue: "blue", yellow: "yellow"}
for i := 0; i < width; i++ {
for j := 0; j < height; j++ {
c := img.At(i, j)
if cmap[c] == "yellow" {
fmt.Printf("The color of the pixel at (%d, %d) is yellow\n", i, j)
}
}
}
}
| #include<graphics.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(NULL));
initwindow(640,480,"Yellow Random Pixel");
putpixel(rand()%640,rand()%480,YELLOW);
getch();
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"strings"
)
func main() {
const (
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
)
strs := []string{
"Forever Go programming language",
"Now is the time for all good men to come to the aid of their country.",
}
for _, str := range strs {
fmt.Println(str)
str = strings.ToLower(str)
vc, cc := 0, 0
vmap := make(map[rune]bool)
cmap := make(map[rune]bool)
for _, c := range str {
if strings.ContainsRune(vowels, c) {
vc++
vmap[c] = true
} else if strings.ContainsRune(consonants, c) {
cc++
cmap[c] = true
}
}
fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc)
fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap))
}
}
|
#include <stdio.h>
char vowels[] = {'a','e','i','o','u','\n'};
int len(char * str) {
int i = 0;
while (str[i] != '\n') i++;
return i;
}
int isvowel(char c){
int b = 0;
int v = len(vowels);
for(int i = 0; i < v;i++) {
if(c == vowels[i]) {
b = 1;
break;
}
}
return b;
}
int isletter(char c){
return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));
}
int isconsonant(char c){
return isletter(c) && !isvowel(c);
}
int cVowels(char * str) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isvowel(str[i])) {
count++;;
}
i++;
}
return count;
}
int cConsonants(char * str ) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isconsonant(str[i])) {
count++;
}
i++;
}
return count;
}
int main() {
char buff[] = "This is 1 string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff);
char buff2[] = "This is a second string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2);
printf("a: %d\n", isvowel('a'));
printf("b: %d\n", isvowel('b'));
printf("Z: %d\n", isconsonant('Z'));
printf("1: %d\n", isletter('1'));
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"strings"
)
func main() {
const (
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
)
strs := []string{
"Forever Go programming language",
"Now is the time for all good men to come to the aid of their country.",
}
for _, str := range strs {
fmt.Println(str)
str = strings.ToLower(str)
vc, cc := 0, 0
vmap := make(map[rune]bool)
cmap := make(map[rune]bool)
for _, c := range str {
if strings.ContainsRune(vowels, c) {
vc++
vmap[c] = true
} else if strings.ContainsRune(consonants, c) {
cc++
cmap[c] = true
}
}
fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc)
fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap))
}
}
|
#include <stdio.h>
char vowels[] = {'a','e','i','o','u','\n'};
int len(char * str) {
int i = 0;
while (str[i] != '\n') i++;
return i;
}
int isvowel(char c){
int b = 0;
int v = len(vowels);
for(int i = 0; i < v;i++) {
if(c == vowels[i]) {
b = 1;
break;
}
}
return b;
}
int isletter(char c){
return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));
}
int isconsonant(char c){
return isletter(c) && !isvowel(c);
}
int cVowels(char * str) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isvowel(str[i])) {
count++;;
}
i++;
}
return count;
}
int cConsonants(char * str ) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isconsonant(str[i])) {
count++;
}
i++;
}
return count;
}
int main() {
char buff[] = "This is 1 string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff);
char buff2[] = "This is a second string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2);
printf("a: %d\n", isvowel('a'));
printf("b: %d\n", isvowel('b'));
printf("Z: %d\n", isconsonant('Z'));
printf("1: %d\n", isletter('1'));
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type TokenType int
const (
tkEOI TokenType = iota
tkMul
tkDiv
tkMod
tkAdd
tkSub
tkNegate
tkNot
tkLss
tkLeq
tkGtr
tkGeq
tkEql
tkNeq
tkAssign
tkAnd
tkOr
tkIf
tkElse
tkWhile
tkPrint
tkPutc
tkLparen
tkRparen
tkLbrace
tkRbrace
tkSemi
tkComma
tkIdent
tkInteger
tkString
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type tokS struct {
tok TokenType
errLn int
errCol int
text string
}
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
}
type atr struct {
text string
enumText string
tok TokenType
rightAssociative bool
isBinary bool
isUnary bool
precedence int
nodeType NodeType
}
var atrs = []atr{
{"EOI", "End_of_input", tkEOI, false, false, false, -1, -1},
{"*", "Op_multiply", tkMul, false, true, false, 13, ndMul},
{"/", "Op_divide", tkDiv, false, true, false, 13, ndDiv},
{"%", "Op_mod", tkMod, false, true, false, 13, ndMod},
{"+", "Op_add", tkAdd, false, true, false, 12, ndAdd},
{"-", "Op_subtract", tkSub, false, true, false, 12, ndSub},
{"-", "Op_negate", tkNegate, false, false, true, 14, ndNegate},
{"!", "Op_not", tkNot, false, false, true, 14, ndNot},
{"<", "Op_less", tkLss, false, true, false, 10, ndLss},
{"<=", "Op_lessequal", tkLeq, false, true, false, 10, ndLeq},
{">", "Op_greater", tkGtr, false, true, false, 10, ndGtr},
{">=", "Op_greaterequal", tkGeq, false, true, false, 10, ndGeq},
{"==", "Op_equal", tkEql, false, true, false, 9, ndEql},
{"!=", "Op_notequal", tkNeq, false, true, false, 9, ndNeq},
{"=", "Op_assign", tkAssign, false, false, false, -1, ndAssign},
{"&&", "Op_and", tkAnd, false, true, false, 5, ndAnd},
{"||", "Op_or", tkOr, false, true, false, 4, ndOr},
{"if", "Keyword_if", tkIf, false, false, false, -1, ndIf},
{"else", "Keyword_else", tkElse, false, false, false, -1, -1},
{"while", "Keyword_while", tkWhile, false, false, false, -1, ndWhile},
{"print", "Keyword_print", tkPrint, false, false, false, -1, -1},
{"putc", "Keyword_putc", tkPutc, false, false, false, -1, -1},
{"(", "LeftParen", tkLparen, false, false, false, -1, -1},
{")", "RightParen", tkRparen, false, false, false, -1, -1},
{"{", "LeftBrace", tkLbrace, false, false, false, -1, -1},
{"}", "RightBrace", tkRbrace, false, false, false, -1, -1},
{";", "Semicolon", tkSemi, false, false, false, -1, -1},
{",", "Comma", tkComma, false, false, false, -1, -1},
{"Ident", "Identifier", tkIdent, false, false, false, -1, ndIdent},
{"Integer literal", "Integer", tkInteger, false, false, false, -1, ndInteger},
{"String literal", "String", tkString, false, false, false, -1, ndString},
}
var displayNodes = []string{
"Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti",
"While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add",
"Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal",
"NotEqual", "And", "Or",
}
var (
err error
token tokS
scanner *bufio.Scanner
)
func reportError(errLine, errCol int, msg string) {
log.Fatalf("(%d, %d) error : %s\n", errLine, errCol, msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func getEum(name string) TokenType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.tok
}
}
reportError(0, 0, fmt.Sprintf("Unknown token %s\n", name))
return tkEOI
}
func getTok() tokS {
tok := tokS{}
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
fields := strings.Fields(line)
tok.errLn, err = strconv.Atoi(fields[0])
check(err)
tok.errCol, err = strconv.Atoi(fields[1])
check(err)
tok.tok = getEum(fields[2])
le := len(fields)
if le == 4 {
tok.text = fields[3]
} else if le > 4 {
idx := strings.Index(line, `"`)
tok.text = line[idx:]
}
}
check(scanner.Err())
return tok
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, ""}
}
func makeLeaf(nodeType NodeType, value string) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func expect(msg string, s TokenType) {
if token.tok == s {
token = getTok()
return
}
reportError(token.errLn, token.errCol,
fmt.Sprintf("%s: Expecting '%s', found '%s'\n", msg, atrs[s].text, atrs[token.tok].text))
}
func expr(p int) *Tree {
var x, node *Tree
switch token.tok {
case tkLparen:
x = parenExpr()
case tkSub, tkAdd:
op := token.tok
token = getTok()
node = expr(atrs[tkNegate].precedence)
if op == tkSub {
x = makeNode(ndNegate, node, nil)
} else {
x = node
}
case tkNot:
token = getTok()
x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)
case tkIdent:
x = makeLeaf(ndIdent, token.text)
token = getTok()
case tkInteger:
x = makeLeaf(ndInteger, token.text)
token = getTok()
default:
reportError(token.errLn, token.errCol,
fmt.Sprintf("Expecting a primary, found: %s\n", atrs[token.tok].text))
}
for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {
op := token.tok
token = getTok()
q := atrs[op].precedence
if !atrs[op].rightAssociative {
q++
}
node = expr(q)
x = makeNode(atrs[op].nodeType, x, node)
}
return x
}
func parenExpr() *Tree {
expect("parenExpr", tkLparen)
t := expr(0)
expect("parenExpr", tkRparen)
return t
}
func stmt() *Tree {
var t, v, e, s, s2 *Tree
switch token.tok {
case tkIf:
token = getTok()
e = parenExpr()
s = stmt()
s2 = nil
if token.tok == tkElse {
token = getTok()
s2 = stmt()
}
t = makeNode(ndIf, e, makeNode(ndIf, s, s2))
case tkPutc:
token = getTok()
e = parenExpr()
t = makeNode(ndPrtc, e, nil)
expect("Putc", tkSemi)
case tkPrint:
token = getTok()
for expect("Print", tkLparen); ; expect("Print", tkComma) {
if token.tok == tkString {
e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)
token = getTok()
} else {
e = makeNode(ndPrti, expr(0), nil)
}
t = makeNode(ndSequence, t, e)
if token.tok != tkComma {
break
}
}
expect("Print", tkRparen)
expect("Print", tkSemi)
case tkSemi:
token = getTok()
case tkIdent:
v = makeLeaf(ndIdent, token.text)
token = getTok()
expect("assign", tkAssign)
e = expr(0)
t = makeNode(ndAssign, v, e)
expect("assign", tkSemi)
case tkWhile:
token = getTok()
e = parenExpr()
s = stmt()
t = makeNode(ndWhile, e, s)
case tkLbrace:
for expect("Lbrace", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {
t = makeNode(ndSequence, t, stmt())
}
expect("Lbrace", tkRbrace)
case tkEOI:
default:
reportError(token.errLn, token.errCol,
fmt.Sprintf("expecting start of statement, found '%s'\n", atrs[token.tok].text))
}
return t
}
func parse() *Tree {
var t *Tree
token = getTok()
for {
t = makeNode(ndSequence, t, stmt())
if t == nil || token.tok == tkEOI {
break
}
}
return t
}
func prtAst(t *Tree) {
if t == nil {
fmt.Print(";\n")
} else {
fmt.Printf("%-14s ", displayNodes[t.nodeType])
if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {
fmt.Printf("%s\n", t.value)
} else {
fmt.Println()
prtAst(t.left)
prtAst(t.right)
}
}
}
func main() {
source, err := os.Open("source.txt")
check(err)
defer source.Close()
scanner = bufio.NewScanner(source)
prtAst(parse())
}
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
type TokenType int
const (
tkEOI TokenType = iota
tkMul
tkDiv
tkMod
tkAdd
tkSub
tkNegate
tkNot
tkLss
tkLeq
tkGtr
tkGeq
tkEql
tkNeq
tkAssign
tkAnd
tkOr
tkIf
tkElse
tkWhile
tkPrint
tkPutc
tkLparen
tkRparen
tkLbrace
tkRbrace
tkSemi
tkComma
tkIdent
tkInteger
tkString
)
type NodeType int
const (
ndIdent NodeType = iota
ndString
ndInteger
ndSequence
ndIf
ndPrtc
ndPrts
ndPrti
ndWhile
ndAssign
ndNegate
ndNot
ndMul
ndDiv
ndMod
ndAdd
ndSub
ndLss
ndLeq
ndGtr
ndGeq
ndEql
ndNeq
ndAnd
ndOr
)
type tokS struct {
tok TokenType
errLn int
errCol int
text string
}
type Tree struct {
nodeType NodeType
left *Tree
right *Tree
value string
}
type atr struct {
text string
enumText string
tok TokenType
rightAssociative bool
isBinary bool
isUnary bool
precedence int
nodeType NodeType
}
var atrs = []atr{
{"EOI", "End_of_input", tkEOI, false, false, false, -1, -1},
{"*", "Op_multiply", tkMul, false, true, false, 13, ndMul},
{"/", "Op_divide", tkDiv, false, true, false, 13, ndDiv},
{"%", "Op_mod", tkMod, false, true, false, 13, ndMod},
{"+", "Op_add", tkAdd, false, true, false, 12, ndAdd},
{"-", "Op_subtract", tkSub, false, true, false, 12, ndSub},
{"-", "Op_negate", tkNegate, false, false, true, 14, ndNegate},
{"!", "Op_not", tkNot, false, false, true, 14, ndNot},
{"<", "Op_less", tkLss, false, true, false, 10, ndLss},
{"<=", "Op_lessequal", tkLeq, false, true, false, 10, ndLeq},
{">", "Op_greater", tkGtr, false, true, false, 10, ndGtr},
{">=", "Op_greaterequal", tkGeq, false, true, false, 10, ndGeq},
{"==", "Op_equal", tkEql, false, true, false, 9, ndEql},
{"!=", "Op_notequal", tkNeq, false, true, false, 9, ndNeq},
{"=", "Op_assign", tkAssign, false, false, false, -1, ndAssign},
{"&&", "Op_and", tkAnd, false, true, false, 5, ndAnd},
{"||", "Op_or", tkOr, false, true, false, 4, ndOr},
{"if", "Keyword_if", tkIf, false, false, false, -1, ndIf},
{"else", "Keyword_else", tkElse, false, false, false, -1, -1},
{"while", "Keyword_while", tkWhile, false, false, false, -1, ndWhile},
{"print", "Keyword_print", tkPrint, false, false, false, -1, -1},
{"putc", "Keyword_putc", tkPutc, false, false, false, -1, -1},
{"(", "LeftParen", tkLparen, false, false, false, -1, -1},
{")", "RightParen", tkRparen, false, false, false, -1, -1},
{"{", "LeftBrace", tkLbrace, false, false, false, -1, -1},
{"}", "RightBrace", tkRbrace, false, false, false, -1, -1},
{";", "Semicolon", tkSemi, false, false, false, -1, -1},
{",", "Comma", tkComma, false, false, false, -1, -1},
{"Ident", "Identifier", tkIdent, false, false, false, -1, ndIdent},
{"Integer literal", "Integer", tkInteger, false, false, false, -1, ndInteger},
{"String literal", "String", tkString, false, false, false, -1, ndString},
}
var displayNodes = []string{
"Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti",
"While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add",
"Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal",
"NotEqual", "And", "Or",
}
var (
err error
token tokS
scanner *bufio.Scanner
)
func reportError(errLine, errCol int, msg string) {
log.Fatalf("(%d, %d) error : %s\n", errLine, errCol, msg)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func getEum(name string) TokenType {
for _, atr := range atrs {
if atr.enumText == name {
return atr.tok
}
}
reportError(0, 0, fmt.Sprintf("Unknown token %s\n", name))
return tkEOI
}
func getTok() tokS {
tok := tokS{}
if scanner.Scan() {
line := strings.TrimRight(scanner.Text(), " \t")
fields := strings.Fields(line)
tok.errLn, err = strconv.Atoi(fields[0])
check(err)
tok.errCol, err = strconv.Atoi(fields[1])
check(err)
tok.tok = getEum(fields[2])
le := len(fields)
if le == 4 {
tok.text = fields[3]
} else if le > 4 {
idx := strings.Index(line, `"`)
tok.text = line[idx:]
}
}
check(scanner.Err())
return tok
}
func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree {
return &Tree{nodeType, left, right, ""}
}
func makeLeaf(nodeType NodeType, value string) *Tree {
return &Tree{nodeType, nil, nil, value}
}
func expect(msg string, s TokenType) {
if token.tok == s {
token = getTok()
return
}
reportError(token.errLn, token.errCol,
fmt.Sprintf("%s: Expecting '%s', found '%s'\n", msg, atrs[s].text, atrs[token.tok].text))
}
func expr(p int) *Tree {
var x, node *Tree
switch token.tok {
case tkLparen:
x = parenExpr()
case tkSub, tkAdd:
op := token.tok
token = getTok()
node = expr(atrs[tkNegate].precedence)
if op == tkSub {
x = makeNode(ndNegate, node, nil)
} else {
x = node
}
case tkNot:
token = getTok()
x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil)
case tkIdent:
x = makeLeaf(ndIdent, token.text)
token = getTok()
case tkInteger:
x = makeLeaf(ndInteger, token.text)
token = getTok()
default:
reportError(token.errLn, token.errCol,
fmt.Sprintf("Expecting a primary, found: %s\n", atrs[token.tok].text))
}
for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p {
op := token.tok
token = getTok()
q := atrs[op].precedence
if !atrs[op].rightAssociative {
q++
}
node = expr(q)
x = makeNode(atrs[op].nodeType, x, node)
}
return x
}
func parenExpr() *Tree {
expect("parenExpr", tkLparen)
t := expr(0)
expect("parenExpr", tkRparen)
return t
}
func stmt() *Tree {
var t, v, e, s, s2 *Tree
switch token.tok {
case tkIf:
token = getTok()
e = parenExpr()
s = stmt()
s2 = nil
if token.tok == tkElse {
token = getTok()
s2 = stmt()
}
t = makeNode(ndIf, e, makeNode(ndIf, s, s2))
case tkPutc:
token = getTok()
e = parenExpr()
t = makeNode(ndPrtc, e, nil)
expect("Putc", tkSemi)
case tkPrint:
token = getTok()
for expect("Print", tkLparen); ; expect("Print", tkComma) {
if token.tok == tkString {
e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil)
token = getTok()
} else {
e = makeNode(ndPrti, expr(0), nil)
}
t = makeNode(ndSequence, t, e)
if token.tok != tkComma {
break
}
}
expect("Print", tkRparen)
expect("Print", tkSemi)
case tkSemi:
token = getTok()
case tkIdent:
v = makeLeaf(ndIdent, token.text)
token = getTok()
expect("assign", tkAssign)
e = expr(0)
t = makeNode(ndAssign, v, e)
expect("assign", tkSemi)
case tkWhile:
token = getTok()
e = parenExpr()
s = stmt()
t = makeNode(ndWhile, e, s)
case tkLbrace:
for expect("Lbrace", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; {
t = makeNode(ndSequence, t, stmt())
}
expect("Lbrace", tkRbrace)
case tkEOI:
default:
reportError(token.errLn, token.errCol,
fmt.Sprintf("expecting start of statement, found '%s'\n", atrs[token.tok].text))
}
return t
}
func parse() *Tree {
var t *Tree
token = getTok()
for {
t = makeNode(ndSequence, t, stmt())
if t == nil || token.tok == tkEOI {
break
}
}
return t
}
func prtAst(t *Tree) {
if t == nil {
fmt.Print(";\n")
} else {
fmt.Printf("%-14s ", displayNodes[t.nodeType])
if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString {
fmt.Printf("%s\n", t.value)
} else {
fmt.Println()
prtAst(t.left)
prtAst(t.right)
}
}
}
func main() {
source, err := os.Open("source.txt")
check(err)
defer source.Close()
scanner = bufio.NewScanner(source)
prtAst(parse())
}
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
)
func main() {
rect := image.Rect(0, 0, 320, 240)
img := image.NewRGBA(rect)
green := color.RGBA{0, 255, 0, 255}
draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)
red := color.RGBA{255, 0, 0, 255}
img.Set(100, 100, red)
cmap := map[color.Color]string{green: "green", red: "red"}
c1 := img.At(0, 0)
c2 := img.At(100, 100)
fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.")
fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.")
}
| #include<graphics.h>
int main()
{
initwindow(320,240,"Red Pixel");
putpixel(100,100,RED);
getch();
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"rcu"
)
func main() {
var numbers []int
for i := 2; i < 200; i++ {
bds := rcu.DigitSum(i, 2)
if rcu.IsPrime(bds) {
tds := rcu.DigitSum(i, 3)
if rcu.IsPrime(tds) {
numbers = append(numbers, i)
}
}
}
fmt.Println("Numbers < 200 whose binary and ternary digit sums are prime:")
for i, n := range numbers {
fmt.Printf("%4d", n)
if (i+1)%14 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found\n", len(numbers))
}
| #include <stdio.h>
#include <stdint.h>
uint8_t prime(uint8_t n) {
uint8_t f;
if (n < 2) return 0;
for (f = 2; f < n; f++) {
if (n % f == 0) return 0;
}
return 1;
}
uint8_t digit_sum(uint8_t n, uint8_t base) {
uint8_t s = 0;
do {s += n % base;} while (n /= base);
return s;
}
int main() {
uint8_t n, s = 0;
for (n = 0; n < 200; n++) {
if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {
printf("%4d",n);
if (++s>=10) {
printf("\n");
s=0;
}
}
}
printf("\n");
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"rcu"
)
func main() {
var numbers []int
for i := 2; i < 200; i++ {
bds := rcu.DigitSum(i, 2)
if rcu.IsPrime(bds) {
tds := rcu.DigitSum(i, 3)
if rcu.IsPrime(tds) {
numbers = append(numbers, i)
}
}
}
fmt.Println("Numbers < 200 whose binary and ternary digit sums are prime:")
for i, n := range numbers {
fmt.Printf("%4d", n)
if (i+1)%14 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found\n", len(numbers))
}
| #include <stdio.h>
#include <stdint.h>
uint8_t prime(uint8_t n) {
uint8_t f;
if (n < 2) return 0;
for (f = 2; f < n; f++) {
if (n % f == 0) return 0;
}
return 1;
}
uint8_t digit_sum(uint8_t n, uint8_t base) {
uint8_t s = 0;
do {s += n % base;} while (n /= base);
return s;
}
int main() {
uint8_t n, s = 0;
for (n = 0; n < 200; n++) {
if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {
printf("%4d",n);
if (++s>=10) {
printf("\n");
s=0;
}
}
}
printf("\n");
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) >= 9 {
words = append(words, s)
}
}
count := 0
var alreadyFound []string
le := len(words)
var sb strings.Builder
for i := 0; i < le-9; i++ {
sb.Reset()
for j := i; j < i+9; j++ {
sb.WriteByte(words[j][j-i])
}
word := sb.String()
ix := sort.SearchStrings(words, word)
if ix < le && word == words[ix] {
ix2 := sort.SearchStrings(alreadyFound, word)
if ix2 == len(alreadyFound) {
count++
fmt.Printf("%2d: %s\n", count, word)
alreadyFound = append(alreadyFound, word)
}
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 80
#define MIN_LENGTH 9
#define WORD_SIZE (MIN_LENGTH + 1)
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int word_compare(const void* p1, const void* p2) {
return memcmp(p1, p2, WORD_SIZE);
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
char* words = xmalloc(WORD_SIZE * capacity);
while (fgets(line, sizeof(line), in)) {
size_t len = strlen(line) - 1;
if (len < MIN_LENGTH)
continue;
line[len] = '\0';
if (size == capacity) {
capacity *= 2;
words = xrealloc(words, WORD_SIZE * capacity);
}
memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);
++size;
}
fclose(in);
qsort(words, size, WORD_SIZE, word_compare);
int count = 0;
char prev_word[WORD_SIZE] = { 0 };
for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {
char word[WORD_SIZE] = { 0 };
for (size_t j = 0; j < MIN_LENGTH; ++j)
word[j] = words[(i + j) * WORD_SIZE + j];
if (word_compare(word, prev_word) == 0)
continue;
if (bsearch(word, words, size, WORD_SIZE, word_compare))
printf("%2d. %s\n", ++count, word);
memcpy(prev_word, word, WORD_SIZE);
}
free(words);
return EXIT_SUCCESS;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"rcu"
)
func main() {
var res []int
for n := 1; n < 1000; n++ {
digits := rcu.Digits(n, 10)
var all = true
for _, d := range digits {
if d == 0 || n%d != 0 {
all = false
break
}
}
if all {
prod := 1
for _, d := range digits {
prod *= d
}
if prod > 0 && n%prod != 0 {
res = append(res, n)
}
}
}
fmt.Println("Numbers < 1000 divisible by their digits, but not by the product thereof:")
for i, n := range res {
fmt.Printf("%4d", n)
if (i+1)%9 == 0 {
fmt.Println()
}
}
fmt.Printf("\n%d such numbers found\n", len(res))
}
| #include <stdio.h>
int divisible(int n) {
int p = 1;
int c, d;
for (c=n; c; c /= 10) {
d = c % 10;
if (!d || n % d) return 0;
p *= d;
}
return n % p;
}
int main() {
int n, c=0;
for (n=1; n<1000; n++) {
if (divisible(n)) {
printf("%5d", n);
if (!(++c % 10)) printf("\n");
}
}
printf("\n");
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {
s0, c0 := fa(a0, b0, 0)
s1, c1 := fa(a1, b1, c0)
s2, c2 := fa(a2, b2, c1)
s3, v = fa(a3, b3, c2)
return
}
func main() {
fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}
| #include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(a, b, ps, pc);
halfadder(ps, ic, s, tc);
V(oc) = V(tc) | V(pc);
}
void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
IN b0, IN b1, IN b2, IN b3,
OUT o0, OUT o1, OUT o2, OUT o3,
OUT overflow)
{
PIN(zero); V(zero) = 0;
PIN(tc0); PIN(tc1); PIN(tc2);
fulladder(a0, b0, zero, o0, tc0);
fulladder(a1, b1, tc0, o1, tc1);
fulladder(a2, b2, tc1, o2, tc2);
fulladder(a3, b3, tc2, o3, overflow);
}
int main()
{
PIN(a0); PIN(a1); PIN(a2); PIN(a3);
PIN(b0); PIN(b1); PIN(b2); PIN(b3);
PIN(s0); PIN(s1); PIN(s2); PIN(s3);
PIN(overflow);
V(a3) = 0; V(b3) = 1;
V(a2) = 0; V(b2) = 1;
V(a1) = 1; V(b1) = 1;
V(a0) = 0; V(b0) = 0;
fourbitsadder(a0, a1, a2, a3,
b0, b1, b2, b3,
s0, s1, s2, s3,
overflow);
printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
V(a3), V(a2), V(a1), V(a0),
V(b3), V(b2), V(b1), V(b0),
V(s3), V(s2), V(s1), V(s0),
V(overflow));
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {
s0, c0 := fa(a0, b0, 0)
s1, c1 := fa(a1, b1, c0)
s2, c2 := fa(a2, b2, c1)
s3, v = fa(a3, b3, c2)
return
}
func main() {
fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
}
| #include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(a, b, ps, pc);
halfadder(ps, ic, s, tc);
V(oc) = V(tc) | V(pc);
}
void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
IN b0, IN b1, IN b2, IN b3,
OUT o0, OUT o1, OUT o2, OUT o3,
OUT overflow)
{
PIN(zero); V(zero) = 0;
PIN(tc0); PIN(tc1); PIN(tc2);
fulladder(a0, b0, zero, o0, tc0);
fulladder(a1, b1, tc0, o1, tc1);
fulladder(a2, b2, tc1, o2, tc2);
fulladder(a3, b3, tc2, o3, overflow);
}
int main()
{
PIN(a0); PIN(a1); PIN(a2); PIN(a3);
PIN(b0); PIN(b1); PIN(b2); PIN(b3);
PIN(s0); PIN(s1); PIN(s2); PIN(s3);
PIN(overflow);
V(a3) = 0; V(b3) = 1;
V(a2) = 0; V(b2) = 1;
V(a1) = 1; V(b1) = 1;
V(a0) = 0; V(b0) = 0;
fourbitsadder(a0, a1, a2, a3,
b0, b1, b2, b3,
s0, s1, s2, s3,
overflow);
printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
V(a3), V(a2), V(a1), V(a0),
V(b3), V(b2), V(b1), V(b0),
V(s3), V(s2), V(s1), V(s0),
V(overflow));
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"fmt"
"log"
)
func magicSquareOdd(n int) ([][]int, error) {
if n < 3 || n%2 == 0 {
return nil, fmt.Errorf("base must be odd and > 2")
}
value := 1
gridSize := n * n
c, r := n/2, 0
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for value <= gridSize {
result[r][c] = value
if r == 0 {
if c == n-1 {
r++
} else {
r = n - 1
c++
}
} else if c == n-1 {
r--
c = 0
} else if result[r-1][c+1] == 0 {
r--
c++
} else {
r++
}
value++
}
return result, nil
}
func magicSquareSinglyEven(n int) ([][]int, error) {
if n < 6 || (n-2)%4 != 0 {
return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2")
}
size := n * n
halfN := n / 2
subSquareSize := size / 4
subSquare, err := magicSquareOdd(halfN)
if err != nil {
return nil, err
}
quadrantFactors := [4]int{0, 2, 3, 1}
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
for r := 0; r < n; r++ {
for c := 0; c < n; c++ {
quadrant := r/halfN*2 + c/halfN
result[r][c] = subSquare[r%halfN][c%halfN]
result[r][c] += quadrantFactors[quadrant] * subSquareSize
}
}
nColsLeft := halfN / 2
nColsRight := nColsLeft - 1
for r := 0; r < halfN; r++ {
for c := 0; c < n; c++ {
if c < nColsLeft || c >= n-nColsRight ||
(c == nColsLeft && r == nColsLeft) {
if c == 0 && r == nColsLeft {
continue
}
tmp := result[r][c]
result[r][c] = result[r+halfN][c]
result[r+halfN][c] = tmp
}
}
}
return result, nil
}
func main() {
const n = 6
msse, err := magicSquareSinglyEven(n)
if err != nil {
log.Fatal(err)
}
for _, row := range msse {
for _, x := range row {
fmt.Printf("%2d ", x)
}
fmt.Println()
}
fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2)
}
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** oddMagicSquare(int n) {
if (n < 3 || n % 2 == 0)
return NULL;
int value = 0;
int squareSize = n * n;
int c = n / 2, r = 0,i;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
while (++value <= squareSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
int** singlyEvenMagicSquare(int n) {
if (n < 6 || (n - 2) % 4 != 0)
return NULL;
int size = n * n;
int halfN = n / 2;
int subGridSize = size / 4, i;
int** subGrid = oddMagicSquare(halfN);
int gridFactors[] = {0, 2, 3, 1};
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int grid = (r / halfN) * 2 + (c / halfN);
result[r][c] = subGrid[r % halfN][c % halfN];
result[r][c] += gridFactors[grid] * subGridSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j;
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2);
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(singlyEvenMagicSquare(n),n);
}
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"runtime"
"ex"
)
func main() {
f := func() {
pc, _, _, _ := runtime.Caller(0)
fmt.Println(runtime.FuncForPC(pc).Name(), "here!")
}
ex.X(f)
}
| #include <stdio.h>
#define sqr(x) ((x) * (x))
#define greet printf("Hello There!\n")
int twice(int x)
{
return 2 * x;
}
int main(void)
{
int x;
printf("This will demonstrate function and label scopes.\n");
printf("All output is happening through printf(), a function declared in the header stdio.h, which is external to this program.\n");
printf("Enter a number: ");
if (scanf("%d", &x) != 1)
return 0;
switch (x % 2) {
default:
printf("Case labels in switch statements have scope local to the switch block.\n");
case 0:
printf("You entered an even number.\n");
printf("Its square is %d, which was computed by a macro. It has global scope within the translation unit.\n", sqr(x));
break;
case 1:
printf("You entered an odd number.\n");
goto sayhello;
jumpin:
printf("2 times %d is %d, which was computed by a function defined in this file. It has global scope within the translation unit.\n", x, twice(x));
printf("Since you jumped in, you will now be greeted, again!\n");
sayhello:
greet;
if (x == -1)
goto scram;
break;
}
printf("We now come to goto, it's extremely powerful but it's also prone to misuse. Its use is discouraged and it wasn't even adopted by Java and later languages.\n");
if (x != -1) {
x = -1;
goto jumpin;
}
scram:
printf("If you are trying to figure out what happened, you now understand goto.\n");
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"fmt"
"math/rand"
)
type symbols struct{ k, q, r, b, n rune }
var A = symbols{'K', 'Q', 'R', 'B', 'N'}
var W = symbols{'♔', '♕', '♖', '♗', '♘'}
var B = symbols{'♚', '♛', '♜', '♝', '♞'}
var krn = []string{
"nnrkr", "nrnkr", "nrknr", "nrkrn",
"rnnkr", "rnknr", "rnkrn",
"rknnr", "rknrn",
"rkrnn"}
func (sym symbols) chess960(id int) string {
var pos [8]rune
q, r := id/4, id%4
pos[r*2+1] = sym.b
q, r = q/4, q%4
pos[r*2] = sym.b
q, r = q/6, q%6
for i := 0; ; i++ {
if pos[i] != 0 {
continue
}
if r == 0 {
pos[i] = sym.q
break
}
r--
}
i := 0
for _, f := range krn[q] {
for pos[i] != 0 {
i++
}
switch f {
case 'k':
pos[i] = sym.k
case 'r':
pos[i] = sym.r
case 'n':
pos[i] = sym.n
}
}
return string(pos[:])
}
func main() {
fmt.Println(" ID Start position")
for _, id := range []int{0, 518, 959} {
fmt.Printf("%3d %s\n", id, A.chess960(id))
}
fmt.Println("\nRandom")
for i := 0; i < 5; i++ {
fmt.Println(W.chess960(rand.Intn(960)))
}
}
| #include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>
char rank[9];
int pos[8];
void swap(int i,int j){
int temp = pos[i];
pos[i] = pos[j];
pos[j] = temp;
}
void generateFirstRank(){
int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;
for(i=0;i<8;i++){
rank[i] = 'e';
pos[i] = i;
}
do{
kPos = rand()%8;
rPos1 = rand()%8;
rPos2 = rand()%8;
}while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));
rank[pos[rPos1]] = 'R';
rank[pos[kPos]] = 'K';
rank[pos[rPos2]] = 'R';
swap(rPos1,7);
swap(rPos2,6);
swap(kPos,5);
do{
bPos1 = rand()%5;
bPos2 = rand()%5;
}while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));
rank[pos[bPos1]] = 'B';
rank[pos[bPos2]] = 'B';
swap(bPos1,4);
swap(bPos2,3);
do{
qPos = rand()%3;
nPos1 = rand()%3;
}while(qPos==nPos1);
rank[pos[qPos]] = 'Q';
rank[pos[nPos1]] = 'N';
for(i=0;i<8;i++)
if(rank[i]=='e'){
rank[i] = 'N';
break;
}
}
void printRank(){
int i;
#ifdef _WIN32
printf("%s\n",rank);
#else
{
setlocale(LC_ALL,"");
printf("\n");
for(i=0;i<8;i++){
if(rank[i]=='K')
printf("%lc",(wint_t)9812);
else if(rank[i]=='Q')
printf("%lc",(wint_t)9813);
else if(rank[i]=='R')
printf("%lc",(wint_t)9814);
else if(rank[i]=='B')
printf("%lc",(wint_t)9815);
if(rank[i]=='N')
printf("%lc",(wint_t)9816);
}
}
#endif
}
int main()
{
int i;
srand((unsigned)time(NULL));
for(i=0;i<9;i++){
generateFirstRank();
printRank();
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen)
var dp int
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
}
| #include <stdio.h>
int main(){
int ptr=0, i=0, cell[7];
for( i=0; i<7; ++i) cell[i]=0;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 8;
while(cell[ptr])
{
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 9;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 2;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
cell[ptr]+= 1;
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 4;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 7;
putchar(cell[ptr]);
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 7;
putchar(cell[ptr]);
ptr-= 3;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 15;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
cell[ptr]-= 6;
putchar(cell[ptr]);
cell[ptr]-= 8;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
putchar(cell[ptr]);
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 4;
putchar(cell[ptr]);
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen)
var dp int
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
}
| #include <stdio.h>
int main(){
int ptr=0, i=0, cell[7];
for( i=0; i<7; ++i) cell[i]=0;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 8;
while(cell[ptr])
{
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 9;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 2;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
cell[ptr]+= 1;
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 4;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 7;
putchar(cell[ptr]);
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 7;
putchar(cell[ptr]);
ptr-= 3;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 15;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
cell[ptr]-= 6;
putchar(cell[ptr]);
cell[ptr]-= 8;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
putchar(cell[ptr]);
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 4;
putchar(cell[ptr]);
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. |
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
| int meaning_of_life();
|
Keep all operations the same but rewrite the snippet in C. |
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
| int meaning_of_life();
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(noise(3.14, 42, 7))
}
func noise(x, y, z float64) float64 {
X := int(math.Floor(x)) & 255
Y := int(math.Floor(y)) & 255
Z := int(math.Floor(z)) & 255
x -= math.Floor(x)
y -= math.Floor(y)
z -= math.Floor(z)
u := fade(x)
v := fade(y)
w := fade(z)
A := p[X] + Y
AA := p[A] + Z
AB := p[A+1] + Z
B := p[X+1] + Y
BA := p[B] + Z
BB := p[B+1] + Z
return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),
grad(p[BA], x-1, y, z)),
lerp(u, grad(p[AB], x, y-1, z),
grad(p[BB], x-1, y-1, z))),
lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),
grad(p[BA+1], x-1, y, z-1)),
lerp(u, grad(p[AB+1], x, y-1, z-1),
grad(p[BB+1], x-1, y-1, z-1))))
}
func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) }
func lerp(t, a, b float64) float64 { return a + t*(b-a) }
func grad(hash int, x, y, z float64) float64 {
switch hash & 15 {
case 0, 12:
return x + y
case 1, 14:
return y - x
case 2:
return x - y
case 3:
return -x - y
case 4:
return x + z
case 5:
return z - x
case 6:
return x - z
case 7:
return -x - z
case 8:
return y + z
case 9, 13:
return z - y
case 10:
return y - z
}
return -y - z
}
var permutation = []int{
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
}
var p = append(permutation, permutation...)
| #include<stdlib.h>
#include<stdio.h>
#include<math.h>
int p[512];
double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
double lerp(double t, double a, double b) { return a + t * (b - a); }
double grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h<8 ? x : y,
v = h<4 ? y : h==12||h==14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
double noise(double x, double y, double z) {
int X = (int)floor(x) & 255,
Y = (int)floor(y) & 255,
Z = (int)floor(z) & 255;
x -= floor(x);
y -= floor(y);
z -= floor(z);
double u = fade(x),
v = fade(y),
w = fade(z);
int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,
B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}
void loadPermutation(char* fileName){
FILE* fp = fopen(fileName,"r");
int permutation[256],i;
for(i=0;i<256;i++)
fscanf(fp,"%d",&permutation[i]);
fclose(fp);
for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];
}
int main(int argC,char* argV[])
{
if(argC!=5)
printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>");
else{
loadPermutation(argV[1]);
printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"log"
"math"
"os"
"path/filepath"
)
func commatize(n int64) 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 fileSizeDistribution(root string) {
var sizes [12]int
files := 0
directories := 0
totalSize := int64(0)
walkFunc := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
files++
if info.IsDir() {
directories++
}
size := info.Size()
if size == 0 {
sizes[0]++
return nil
}
totalSize += size
logSize := math.Log10(float64(size))
index := int(math.Floor(logSize))
sizes[index+1]++
return nil
}
err := filepath.Walk(root, walkFunc)
if err != nil {
log.Fatal(err)
}
fmt.Printf("File size distribution for '%s' :-\n\n", root)
for i := 0; i < len(sizes); i++ {
if i == 0 {
fmt.Print(" ")
} else {
fmt.Print("+ ")
}
fmt.Printf("Files less than 10 ^ %-2d bytes : %5d\n", i, sizes[i])
}
fmt.Println(" -----")
fmt.Printf("= Total number of files : %5d\n", files)
fmt.Printf(" including directories : %5d\n", directories)
c := commatize(totalSize)
fmt.Println("\n Total size of files :", c, "bytes")
}
func main() {
fileSizeDistribution("./")
}
| #include<windows.h>
#include<string.h>
#include<stdio.h>
#define MAXORDER 25
int main(int argC, char* argV[])
{
char str[MAXORDER],commandString[1000],*startPath;
long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;
int i,j,len;
double scale;
FILE* fp;
if(argC==1)
printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]);
else{
if(strchr(argV[1],' ')!=NULL){
len = strlen(argV[1]);
startPath = (char*)malloc((len+2)*sizeof(char));
startPath[0] = '\"';
startPath[len+1]='\"';
strncpy(startPath+1,argV[1],len);
startPath[len+2] = argV[1][len];
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath);
}
else if(strlen(argV[1])==1 && argV[1][0]=='.')
strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1");
else
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]);
fp = popen(commandString,"r");
while(fgets(str,100,fp)!=NULL){
if(str[0]=='0')
fileSizeLog[0]++;
else
fileSizeLog[strlen(str)]++;
}
if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]);
}
}
else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){
CONSOLE_SCREEN_BUFFER_INFO csbi;
int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);
if(val)
{
max = fileSizeLog[0];
for(i=1;i<MAXORDER;i++)
(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;
(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes |",i);
for(j=0;j<(int)(scale*fileSizeLog[i]);j++)
printf("%c",219);
printf("%Ld",fileSizeLog[i]);
}
}
}
return 0;
}
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"log"
"os"
"sort"
)
func main() {
f, err := os.Open(".")
if err != nil {
log.Fatal(err)
}
files, err := f.Readdirnames(0)
f.Close()
if err != nil {
log.Fatal(err)
}
sort.Strings(files)
for _, n := range files {
fmt.Println(n)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
int cmpstr(const void *a, const void *b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
int main(void)
{
DIR *basedir;
char path[PATH_MAX];
struct dirent *entry;
char **dirnames;
int diralloc = 128;
int dirsize = 0;
if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
perror("malloc error:");
return 1;
}
if (!getcwd(path, PATH_MAX)) {
perror("getcwd error:");
return 1;
}
if (!(basedir = opendir(path))) {
perror("opendir error:");
return 1;
}
while ((entry = readdir(basedir))) {
if (dirsize >= diralloc) {
diralloc *= 2;
if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
perror("realloc error:");
return 1;
}
}
dirnames[dirsize++] = strdup(entry->d_name);
}
qsort(dirnames, dirsize, sizeof(char*), cmpstr);
int i;
for (i = 0; i < dirsize; ++i) {
if (dirnames[i][0] != '.') {
printf("%s\n", dirnames[i]);
}
}
for (i = 0; i < dirsize; ++i)
free(dirnames[i]);
free(dirnames);
closedir(basedir);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"errors"
"fmt"
"strings"
"sync"
)
var hdText = `Humpty Dumpty sat on a wall.
Humpty Dumpty had a great fall.
All the king's horses and all the king's men,
Couldn't put Humpty together again.`
var mgText = `Old Mother Goose,
When she wanted to wander,
Would ride through the air,
On a very fine gander.
Jack's mother came in,
And caught the goose soon,
And mounting its back,
Flew up to the moon.`
func main() {
reservePrinter := startMonitor(newPrinter(5), nil)
mainPrinter := startMonitor(newPrinter(5), reservePrinter)
var busy sync.WaitGroup
busy.Add(2)
go writer(mainPrinter, "hd", hdText, &busy)
go writer(mainPrinter, "mg", mgText, &busy)
busy.Wait()
}
type printer func(string) error
func newPrinter(ink int) printer {
return func(line string) error {
if ink == 0 {
return eOutOfInk
}
for _, c := range line {
fmt.Printf("%c", c)
}
fmt.Println()
ink--
return nil
}
}
var eOutOfInk = errors.New("out of ink")
type rSync struct {
call chan string
response chan error
}
func (r *rSync) print(data string) error {
r.call <- data
return <-r.response
}
func monitor(hardPrint printer, entry, reserve *rSync) {
for {
data := <-entry.call
switch err := hardPrint(data); {
case err == nil:
entry.response <- nil
case err == eOutOfInk && reserve != nil:
entry.response <- reserve.print(data)
default:
entry.response <- err
}
}
}
func startMonitor(p printer, reservePrinter *rSync) *rSync {
entry := &rSync{make(chan string), make(chan error)}
go monitor(p, entry, reservePrinter)
return entry
}
func writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {
for _, line := range strings.Split(text, "\n") {
if err := printMonitor.print(line); err != nil {
fmt.Printf("**** writer task %q terminated: %v ****\n", id, err)
break
}
}
busy.Done()
}
| #include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
typedef struct rendezvous {
pthread_mutex_t lock;
pthread_cond_t cv_entering;
pthread_cond_t cv_accepting;
pthread_cond_t cv_done;
int (*accept_func)(void*);
int entering;
int accepting;
int done;
} rendezvous_t;
#define RENDEZVOUS_INITILIZER(accept_function) { \
.lock = PTHREAD_MUTEX_INITIALIZER, \
.cv_entering = PTHREAD_COND_INITIALIZER, \
.cv_accepting = PTHREAD_COND_INITIALIZER, \
.cv_done = PTHREAD_COND_INITIALIZER, \
.accept_func = accept_function, \
.entering = 0, \
.accepting = 0, \
.done = 0, \
}
int enter_rendezvous(rendezvous_t *rv, void* data)
{
pthread_mutex_lock(&rv->lock);
rv->entering++;
pthread_cond_signal(&rv->cv_entering);
while (!rv->accepting) {
pthread_cond_wait(&rv->cv_accepting, &rv->lock);
}
int ret = rv->accept_func(data);
rv->done = 1;
pthread_cond_signal(&rv->cv_done);
rv->entering--;
rv->accepting = 0;
pthread_mutex_unlock(&rv->lock);
return ret;
}
void accept_rendezvous(rendezvous_t *rv)
{
pthread_mutex_lock(&rv->lock);
rv->accepting = 1;
while (!rv->entering) {
pthread_cond_wait(&rv->cv_entering, &rv->lock);
}
pthread_cond_signal(&rv->cv_accepting);
while (!rv->done) {
pthread_cond_wait(&rv->cv_done, &rv->lock);
}
rv->done = 0;
rv->accepting = 0;
pthread_mutex_unlock(&rv->lock);
}
typedef struct printer {
rendezvous_t rv;
struct printer *backup;
int id;
int remaining_lines;
} printer_t;
typedef struct print_args {
struct printer *printer;
const char* line;
} print_args_t;
int print_line(printer_t *printer, const char* line) {
print_args_t args;
args.printer = printer;
args.line = line;
return enter_rendezvous(&printer->rv, &args);
}
int accept_print(void* data) {
print_args_t *args = (print_args_t*)data;
printer_t *printer = args->printer;
const char* line = args->line;
if (printer->remaining_lines) {
printf("%d: ", printer->id);
while (*line != '\0') {
putchar(*line++);
}
putchar('\n');
printer->remaining_lines--;
return 1;
}
else if (printer->backup) {
return print_line(printer->backup, line);
}
else {
return -1;
}
}
printer_t backup_printer = {
.rv = RENDEZVOUS_INITILIZER(accept_print),
.backup = NULL,
.id = 2,
.remaining_lines = 5,
};
printer_t main_printer = {
.rv = RENDEZVOUS_INITILIZER(accept_print),
.backup = &backup_printer,
.id = 1,
.remaining_lines = 5,
};
void* printer_thread(void* thread_data) {
printer_t *printer = (printer_t*) thread_data;
while (1) {
accept_rendezvous(&printer->rv);
}
}
typedef struct poem {
char* name;
char* lines[];
} poem_t;
poem_t humpty_dumpty = {
.name = "Humpty Dumpty",
.lines = {
"Humpty Dumpty sat on a wall.",
"Humpty Dumpty had a great fall.",
"All the king's horses and all the king's men",
"Couldn't put Humpty together again.",
""
},
};
poem_t mother_goose = {
.name = "Mother Goose",
.lines = {
"Old Mother Goose",
"When she wanted to wander,",
"Would ride through the air",
"On a very fine gander.",
"Jack's mother came in,",
"And caught the goose soon,",
"And mounting its back,",
"Flew up to the moon.",
""
},
};
void* poem_thread(void* thread_data) {
poem_t *poem = (poem_t*)thread_data;
for (unsigned i = 0; poem->lines[i] != ""; i++) {
int ret = print_line(&main_printer, poem->lines[i]);
if (ret < 0) {
printf(" %s out of ink!\n", poem->name);
exit(1);
}
}
return NULL;
}
int main(void)
{
pthread_t threads[4];
pthread_create(&threads[0], NULL, poem_thread, &humpty_dumpty);
pthread_create(&threads[1], NULL, poem_thread, &mother_goose);
pthread_create(&threads[2], NULL, printer_thread, &main_printer);
pthread_create(&threads[3], NULL, printer_thread, &backup_printer);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_cancel(threads[2]);
pthread_cancel(threads[3]);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"rcu"
)
func main() {
var primes []int
candidates := []int{3, 33}
for i := 303; i <= 393; i += 10 {
candidates = append(candidates, i)
}
for i := 3003; i <= 3993; i += 10 {
candidates = append(candidates, i)
}
for _, cand := range candidates {
if rcu.IsPrime(cand) {
primes = append(primes, cand)
}
}
fmt.Println("Primes under 4,000 which begin and end in 3:")
for i, p := range primes {
fmt.Printf("%5s ", rcu.Commatize(p))
if (i+1)%11 == 0 {
fmt.Println()
}
}
fmt.Println("\nFound", len(primes), "Such primes.")
pc := len(primes)
for i := 30003; i <= 39993; i += 10 {
if rcu.IsPrime(i) {
pc++
}
}
for i := 300003; i <= 399993; i += 10 {
if rcu.IsPrime(i) {
pc++
}
}
pcc := rcu.Commatize(pc)
fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.")
}
| #include<stdio.h>
#include<stdlib.h>
#include<math.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int main(void) {
int np = 1, d, i, n;
printf( "3 " );
for(d=1; d<6; d++) {
for(i=3; i<pow(10,d)-1; i+=10) {
n = i + 3*pow(10,d);
if(isprime(n)) {
++np;
if(n<4009) {
printf("%d ",n);
if(!(np%10)) printf("\n");
}
}
}
}
printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np );
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"rcu"
)
func main() {
var primes []int
candidates := []int{3, 33}
for i := 303; i <= 393; i += 10 {
candidates = append(candidates, i)
}
for i := 3003; i <= 3993; i += 10 {
candidates = append(candidates, i)
}
for _, cand := range candidates {
if rcu.IsPrime(cand) {
primes = append(primes, cand)
}
}
fmt.Println("Primes under 4,000 which begin and end in 3:")
for i, p := range primes {
fmt.Printf("%5s ", rcu.Commatize(p))
if (i+1)%11 == 0 {
fmt.Println()
}
}
fmt.Println("\nFound", len(primes), "Such primes.")
pc := len(primes)
for i := 30003; i <= 39993; i += 10 {
if rcu.IsPrime(i) {
pc++
}
}
for i := 300003; i <= 399993; i += 10 {
if rcu.IsPrime(i) {
pc++
}
}
pcc := rcu.Commatize(pc)
fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.")
}
| #include<stdio.h>
#include<stdlib.h>
#include<math.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int main(void) {
int np = 1, d, i, n;
printf( "3 " );
for(d=1; d<6; d++) {
for(i=3; i<pow(10,d)-1; i+=10) {
n = i + 3*pow(10,d);
if(isprime(n)) {
++np;
if(n<4009) {
printf("%d ",n);
if(!(np%10)) printf("\n");
}
}
}
}
printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np );
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import (
"fmt"
"rcu"
)
func main() {
var primes []int
candidates := []int{3, 33}
for i := 303; i <= 393; i += 10 {
candidates = append(candidates, i)
}
for i := 3003; i <= 3993; i += 10 {
candidates = append(candidates, i)
}
for _, cand := range candidates {
if rcu.IsPrime(cand) {
primes = append(primes, cand)
}
}
fmt.Println("Primes under 4,000 which begin and end in 3:")
for i, p := range primes {
fmt.Printf("%5s ", rcu.Commatize(p))
if (i+1)%11 == 0 {
fmt.Println()
}
}
fmt.Println("\nFound", len(primes), "Such primes.")
pc := len(primes)
for i := 30003; i <= 39993; i += 10 {
if rcu.IsPrime(i) {
pc++
}
}
for i := 300003; i <= 399993; i += 10 {
if rcu.IsPrime(i) {
pc++
}
}
pcc := rcu.Commatize(pc)
fmt.Println("\nFound", pcc, "primes under 1,000,000 which begin and end with 3.")
}
| #include<stdio.h>
#include<stdlib.h>
#include<math.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int main(void) {
int np = 1, d, i, n;
printf( "3 " );
for(d=1; d<6; d++) {
for(i=3; i<pow(10,d)-1; i+=10) {
n = i + 3*pow(10,d);
if(isprime(n)) {
++np;
if(n<4009) {
printf("%d ",n);
if(!(np%10)) printf("\n");
}
}
}
}
printf( "\n\nThere were %d primes of the form 3x3 below one million.\n", np );
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import "fmt"
const jobs = 12
type environment struct{ seq, cnt int }
var (
env [jobs]environment
seq, cnt *int
)
func hail() {
fmt.Printf("% 4d", *seq)
if *seq == 1 {
return
}
(*cnt)++
if *seq&1 != 0 {
*seq = 3*(*seq) + 1
} else {
*seq /= 2
}
}
func switchTo(id int) {
seq = &env[id].seq
cnt = &env[id].cnt
}
func main() {
for i := 0; i < jobs; i++ {
switchTo(i)
env[i].seq = i + 1
}
again:
for i := 0; i < jobs; i++ {
switchTo(i)
hail()
}
fmt.Println()
for j := 0; j < jobs; j++ {
switchTo(j)
if *seq != 1 {
goto again
}
}
fmt.Println()
fmt.Println("COUNTS:")
for i := 0; i < jobs; i++ {
switchTo(i)
fmt.Printf("% 4d", *cnt)
}
fmt.Println()
}
| #include <stdio.h>
#define JOBS 12
#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a))
typedef struct { int seq, cnt; } env_t;
env_t env[JOBS] = {{0, 0}};
int *seq, *cnt;
void hail()
{
printf("% 4d", *seq);
if (*seq == 1) return;
++*cnt;
*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;
}
void switch_to(int id)
{
seq = &env[id].seq;
cnt = &env[id].cnt;
}
int main()
{
int i;
jobs(i) { env[i].seq = i + 1; }
again: jobs(i) { hail(); }
jobs(i) { if (1 != *seq) goto again; }
printf("COUNTS:\n");
jobs(i) { printf("% 4d", *cnt); }
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"bytes"
"encoding/hex"
"fmt"
"log"
"strings"
)
var testCases = []struct {
rune
string
}{
{'A', "41"},
{'ö', "C3 B6"},
{'Ж', "D0 96"},
{'€', "E2 82 AC"},
{'𝄞', "F0 9D 84 9E"},
}
func main() {
for _, tc := range testCases {
u := fmt.Sprintf("U+%04X", tc.rune)
b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1))
if err != nil {
log.Fatal("bad test data")
}
e := encodeUTF8(tc.rune)
d := decodeUTF8(b)
fmt.Printf("%c %-7s %X\n", d, u, e)
if !bytes.Equal(e, b) {
log.Fatal("encodeUTF8 wrong")
}
if d != tc.rune {
log.Fatal("decodeUTF8 wrong")
}
}
}
const (
b2Lead = 0xC0
b2Mask = 0x1F
b3Lead = 0xE0
b3Mask = 0x0F
b4Lead = 0xF0
b4Mask = 0x07
mbLead = 0x80
mbMask = 0x3F
)
func encodeUTF8(r rune) []byte {
switch i := uint32(r); {
case i <= 1<<7-1:
return []byte{byte(r)}
case i <= 1<<11-1:
return []byte{
b2Lead | byte(r>>6),
mbLead | byte(r)&mbMask}
case i <= 1<<16-1:
return []byte{
b3Lead | byte(r>>12),
mbLead | byte(r>>6)&mbMask,
mbLead | byte(r)&mbMask}
default:
return []byte{
b4Lead | byte(r>>18),
mbLead | byte(r>>12)&mbMask,
mbLead | byte(r>>6)&mbMask,
mbLead | byte(r)&mbMask}
}
}
func decodeUTF8(b []byte) rune {
switch b0 := b[0]; {
case b0 < 0x80:
return rune(b0)
case b0 < 0xE0:
return rune(b0&b2Mask)<<6 |
rune(b[1]&mbMask)
case b0 < 0xF0:
return rune(b0&b3Mask)<<12 |
rune(b[1]&mbMask)<<6 |
rune(b[2]&mbMask)
default:
return rune(b0&b4Mask)<<18 |
rune(b[1]&mbMask)<<12 |
rune(b[2]&mbMask)<<6 |
rune(b[3]&mbMask)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
typedef struct {
char mask;
char lead;
uint32_t beg;
uint32_t end;
int bits_stored;
}utf_t;
utf_t * utf[] = {
[0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 },
[1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 },
[2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 },
[3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 },
[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 },
&(utf_t){0},
};
int codepoint_len(const uint32_t cp);
int utf8_len(const char ch);
char *to_utf8(const uint32_t cp);
uint32_t to_cp(const char chr[4]);
int codepoint_len(const uint32_t cp)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((cp >= (*u)->beg) && (cp <= (*u)->end)) {
break;
}
++len;
}
if(len > 4)
exit(1);
return len;
}
int utf8_len(const char ch)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((ch & ~(*u)->mask) == (*u)->lead) {
break;
}
++len;
}
if(len > 4) {
exit(1);
}
return len;
}
char *to_utf8(const uint32_t cp)
{
static char ret[5];
const int bytes = codepoint_len(cp);
int shift = utf[0]->bits_stored * (bytes - 1);
ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;
shift -= utf[0]->bits_stored;
for(int i = 1; i < bytes; ++i) {
ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;
shift -= utf[0]->bits_stored;
}
ret[bytes] = '\0';
return ret;
}
uint32_t to_cp(const char chr[4])
{
int bytes = utf8_len(*chr);
int shift = utf[0]->bits_stored * (bytes - 1);
uint32_t codep = (*chr++ & utf[bytes]->mask) << shift;
for(int i = 1; i < bytes; ++i, ++chr) {
shift -= utf[0]->bits_stored;
codep |= ((char)*chr & utf[0]->mask) << shift;
}
return codep;
}
int main(void)
{
const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};
printf("Character Unicode UTF-8 encoding (hex)\n");
printf("----------------------------------------\n");
char *utf8;
uint32_t codepoint;
for(in = input; *in; ++in) {
utf8 = to_utf8(*in);
codepoint = to_cp(utf8);
printf("%s U+%-7.4x", utf8, codepoint);
for(int i = 0; utf8[i] && i < 4; ++i) {
printf("%hhx ", utf8[i]);
}
printf("\n");
}
return 0;
}
|
Change the following Go code into C without altering its purpose. | package raster
import "math"
func ipart(x float64) float64 {
return math.Floor(x)
}
func round(x float64) float64 {
return ipart(x + .5)
}
func fpart(x float64) float64 {
return x - ipart(x)
}
func rfpart(x float64) float64 {
return 1 - fpart(x)
}
func (g *Grmap) AaLine(x1, y1, x2, y2 float64) {
dx := x2 - x1
dy := y2 - y1
ax := dx
if ax < 0 {
ax = -ax
}
ay := dy
if ay < 0 {
ay = -ay
}
var plot func(int, int, float64)
if ax < ay {
x1, y1 = y1, x1
x2, y2 = y2, x2
dx, dy = dy, dx
plot = func(x, y int, c float64) {
g.SetPx(y, x, uint16(c*math.MaxUint16))
}
} else {
plot = func(x, y int, c float64) {
g.SetPx(x, y, uint16(c*math.MaxUint16))
}
}
if x2 < x1 {
x1, x2 = x2, x1
y1, y2 = y2, y1
}
gradient := dy / dx
xend := round(x1)
yend := y1 + gradient*(xend-x1)
xgap := rfpart(x1 + .5)
xpxl1 := int(xend)
ypxl1 := int(ipart(yend))
plot(xpxl1, ypxl1, rfpart(yend)*xgap)
plot(xpxl1, ypxl1+1, fpart(yend)*xgap)
intery := yend + gradient
xend = round(x2)
yend = y2 + gradient*(xend-x2)
xgap = fpart(x2 + 0.5)
xpxl2 := int(xend)
ypxl2 := int(ipart(yend))
plot(xpxl2, ypxl2, rfpart(yend)*xgap)
plot(xpxl2, ypxl2+1, fpart(yend)*xgap)
for x := xpxl1 + 1; x <= xpxl2-1; x++ {
plot(x, int(ipart(intery)), rfpart(intery))
plot(x, int(ipart(intery))+1, fpart(intery))
intery = intery + gradient
}
}
| void draw_line_antialias(
image img,
unsigned int x0, unsigned int y0,
unsigned int x1, unsigned int y1,
color_component r,
color_component g,
color_component b );
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import "C"
import "fmt"
import "unsafe"
func main() {
d := C.XOpenDisplay(nil)
f7, f6 := C.CString("F7"), C.CString("F6")
defer C.free(unsafe.Pointer(f7))
defer C.free(unsafe.Pointer(f6))
if d != nil {
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))),
C.Mod1Mask,
C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
C.XGrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))),
C.Mod1Mask,
C.DefaultRootWindow_macro(d), C.True, C.GrabModeAsync, C.GrabModeAsync)
var event C.XEvent
for {
C.XNextEvent(d, &event)
if C.getXEvent_type(event) == C.KeyPress {
xkeyEvent := C.getXEvent_xkey(event)
s := C.XLookupKeysym(&xkeyEvent, 0)
if s == C.XK_F7 {
fmt.Println("something's happened")
} else if s == C.XK_F6 {
break
}
}
}
C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f7))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
C.XUngrabKey(d, C.int(C.XKeysymToKeycode(d, C.XStringToKeysym(f6))), C.Mod1Mask, C.DefaultRootWindow_macro(d))
} else {
fmt.Println("XOpenDisplay did not succeed")
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
int main()
{
Display *d;
XEvent event;
d = XOpenDisplay(NULL);
if ( d != NULL ) {
XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")),
Mod1Mask,
DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")),
Mod1Mask,
DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
for(;;)
{
XNextEvent(d, &event);
if ( event.type == KeyPress ) {
KeySym s = XLookupKeysym(&event.xkey, 0);
if ( s == XK_F7 ) {
printf("something's happened\n");
} else if ( s == XK_F6 ) {
break;
}
}
}
XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d));
XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d));
}
return EXIT_SUCCESS;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import "fmt"
func mcnugget(limit int) {
sv := make([]bool, limit+1)
for s := 0; s <= limit; s += 6 {
for n := s; n <= limit; n += 9 {
for t := n; t <= limit; t += 20 {
sv[t] = true
}
}
}
for i := limit; i >= 0; i-- {
if !sv[i] {
fmt.Println("Maximum non-McNuggets number is", i)
return
}
}
}
func main() {
mcnugget(100)
}
| #include <stdio.h>
int
main() {
int max = 0, i = 0, sixes, nines, twenties;
loopstart: while (i < 100) {
for (sixes = 0; sixes*6 < i; sixes++) {
if (sixes*6 == i) {
i++;
goto loopstart;
}
for (nines = 0; nines*9 < i; nines++) {
if (sixes*6 + nines*9 == i) {
i++;
goto loopstart;
}
for (twenties = 0; twenties*20 < i; twenties++) {
if (sixes*6 + nines*9 + twenties*20 == i) {
i++;
goto loopstart;
}
}
}
}
max = i;
i++;
}
printf("Maximum non-McNuggets number is %d\n", max);
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"log"
"strings"
)
const dimensions int = 8
func setupMagicSquareData(d int) ([][]int, error) {
var output [][]int
if d < 4 || d%4 != 0 {
return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
}
var bits uint = 0x9669
size := d * d
mult := d / 4
for i, r := 0, 0; r < d; r++ {
output = append(output, []int{})
for c := 0; c < d; i, c = i+1, c+1 {
bitPos := c/mult + (r/mult)*4
if (bits & (1 << uint(bitPos))) != 0 {
output[r] = append(output[r], i+1)
} else {
output[r] = append(output[r], size-i)
}
}
}
return output, nil
}
func arrayItoa(input []int) []string {
var output []string
for _, i := range input {
output = append(output, fmt.Sprintf("%4d", i))
}
return output
}
func main() {
data, err := setupMagicSquareData(dimensions)
if err != nil {
log.Fatal(err)
}
magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2
for _, row := range data {
fmt.Println(strings.Join(arrayItoa(row), " "))
}
fmt.Printf("\nMagic Constant: %d\n", magicConstant)
}
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"math"
)
func main() {
var zero float64
var negZero, posInf, negInf, nan float64
negZero = zero * -1
posInf = 1 / zero
negInf = -1 / zero
nan = zero / zero
fmt.Println(negZero, posInf, negInf, nan)
fmt.Println(math.Float64frombits(1<<63),
math.Inf(1), math.Inf(-1), math.NaN())
fmt.Println()
validateNaN(negInf+posInf, "-Inf + Inf")
validateNaN(0*posInf, "0 * Inf")
validateNaN(posInf/posInf, "Inf / Inf")
validateNaN(math.Mod(posInf, 1), "Inf % 1")
validateNaN(1+nan, "1 + NaN")
validateZero(1/posInf, "1 / Inf")
validateGT(posInf, math.MaxFloat64, "Inf > max value")
validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
validateNE(nan, nan, "NaN != NaN")
validateEQ(negZero, 0, "-0 == 0")
}
func validateNaN(n float64, op string) {
if math.IsNaN(n) {
fmt.Println(op, "-> NaN")
} else {
fmt.Println("!!! Expected NaN from", op, " Found", n)
}
}
func validateZero(n float64, op string) {
if n == 0 {
fmt.Println(op, "-> 0")
} else {
fmt.Println("!!! Expected 0 from", op, " Found", n)
}
}
func validateGT(a, b float64, op string) {
if a > b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
func validateNE(a, b float64, op string) {
if a == b {
fmt.Println("!!! Expected", op, " Found not true.")
} else {
fmt.Println(op)
}
}
func validateEQ(a, b float64, op string) {
if a == b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
| #include <stdio.h>
int main()
{
double inf = 1/0.0;
double minus_inf = -1/0.0;
double minus_zero = -1/ inf ;
double nan = 0.0/0.0;
printf("positive infinity: %f\n",inf);
printf("negative infinity: %f\n",minus_inf);
printf("negative zero: %f\n",minus_zero);
printf("not a number: %f\n",nan);
printf("+inf + 2.0 = %f\n",inf + 2.0);
printf("+inf - 10.1 = %f\n",inf - 10.1);
printf("+inf + -inf = %f\n",inf + minus_inf);
printf("0.0 * +inf = %f\n",0.0 * inf);
printf("1.0/-0.0 = %f\n",1.0/minus_zero);
printf("NaN + 1.0 = %f\n",nan + 1.0);
printf("NaN + NaN = %f\n",nan + nan);
printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"math"
)
func main() {
var zero float64
var negZero, posInf, negInf, nan float64
negZero = zero * -1
posInf = 1 / zero
negInf = -1 / zero
nan = zero / zero
fmt.Println(negZero, posInf, negInf, nan)
fmt.Println(math.Float64frombits(1<<63),
math.Inf(1), math.Inf(-1), math.NaN())
fmt.Println()
validateNaN(negInf+posInf, "-Inf + Inf")
validateNaN(0*posInf, "0 * Inf")
validateNaN(posInf/posInf, "Inf / Inf")
validateNaN(math.Mod(posInf, 1), "Inf % 1")
validateNaN(1+nan, "1 + NaN")
validateZero(1/posInf, "1 / Inf")
validateGT(posInf, math.MaxFloat64, "Inf > max value")
validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
validateNE(nan, nan, "NaN != NaN")
validateEQ(negZero, 0, "-0 == 0")
}
func validateNaN(n float64, op string) {
if math.IsNaN(n) {
fmt.Println(op, "-> NaN")
} else {
fmt.Println("!!! Expected NaN from", op, " Found", n)
}
}
func validateZero(n float64, op string) {
if n == 0 {
fmt.Println(op, "-> 0")
} else {
fmt.Println("!!! Expected 0 from", op, " Found", n)
}
}
func validateGT(a, b float64, op string) {
if a > b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
func validateNE(a, b float64, op string) {
if a == b {
fmt.Println("!!! Expected", op, " Found not true.")
} else {
fmt.Println(op)
}
}
func validateEQ(a, b float64, op string) {
if a == b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
| #include <stdio.h>
int main()
{
double inf = 1/0.0;
double minus_inf = -1/0.0;
double minus_zero = -1/ inf ;
double nan = 0.0/0.0;
printf("positive infinity: %f\n",inf);
printf("negative infinity: %f\n",minus_inf);
printf("negative zero: %f\n",minus_zero);
printf("not a number: %f\n",nan);
printf("+inf + 2.0 = %f\n",inf + 2.0);
printf("+inf - 10.1 = %f\n",inf - 10.1);
printf("+inf + -inf = %f\n",inf + minus_inf);
printf("0.0 * +inf = %f\n",0.0 * inf);
printf("1.0/-0.0 = %f\n",1.0/minus_zero);
printf("NaN + 1.0 = %f\n",nan + 1.0);
printf("NaN + NaN = %f\n",nan + nan);
printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"fmt"
"math"
)
const CONST = 0x2545F4914F6CDD1D
type XorshiftStar struct{ state uint64 }
func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }
func (xor *XorshiftStar) seed(state uint64) { xor.state = state }
func (xor *XorshiftStar) nextInt() uint32 {
x := xor.state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
xor.state = x
return uint32((x * CONST) >> 32)
}
func (xor *XorshiftStar) nextFloat() float64 {
return float64(xor.nextInt()) / (1 << 32)
}
func main() {
randomGen := XorshiftStarNew(1234567)
for i := 0; i < 5; i++ {
fmt.Println(randomGen.nextInt())
}
var counts [5]int
randomGen.seed(987654321)
for i := 0; i < 1e5; i++ {
j := int(math.Floor(randomGen.nextFloat() * 5))
counts[j]++
}
fmt.Println("\nThe counts for 100,000 repetitions are:")
for i := 0; i < 5; i++ {
fmt.Printf(" %d : %d\n", i, counts[i])
}
}
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
static uint64_t state;
static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;
void seed(uint64_t num) {
state = num;
}
uint32_t next_int() {
uint64_t x;
uint32_t answer;
x = state;
x = x ^ (x >> 12);
x = x ^ (x << 25);
x = x ^ (x >> 27);
state = x;
answer = ((x * STATE_MAGIC) >> 32);
return answer;
}
float next_float() {
return (float)next_int() / (1LL << 32);
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("\n");
seed(987654321);
for (i = 0; i < 100000; i++) {
int j = (int)floor(next_float() * 5.0);
counts[j]++;
}
for (i = 0; i < 5; i++) {
printf("%d: %d\n", i, counts[i]);
}
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := NewFourIsSeq()
fmt.Print("The lengths of the first 201 words are:")
for i := 1; i <= 201; i++ {
if i%25 == 1 {
fmt.Printf("\n%3d: ", i)
}
_, n := f.WordLen(i)
fmt.Printf(" %2d", n)
}
fmt.Println()
fmt.Println("Length of sentence so far:", f.TotalLength())
for i := 1000; i <= 1e7; i *= 10 {
w, n := f.WordLen(i)
fmt.Printf("Word %8d is %q, with %d letters.", i, w, n)
fmt.Println(" Length of sentence so far:", f.TotalLength())
}
}
type FourIsSeq struct {
i int
words []string
}
func NewFourIsSeq() *FourIsSeq {
return &FourIsSeq{
words: []string{
"Four", "is", "the", "number",
"of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,",
},
}
}
func (f *FourIsSeq) WordLen(w int) (string, int) {
for len(f.words) < w {
f.i++
n := countLetters(f.words[f.i])
ns := say(int64(n))
os := sayOrdinal(int64(f.i+1)) + ","
f.words = append(f.words, strings.Fields(ns)...)
f.words = append(f.words, "in", "the")
f.words = append(f.words, strings.Fields(os)...)
}
word := f.words[w-1]
return word, countLetters(word)
}
func (f FourIsSeq) TotalLength() int {
cnt := 0
for _, w := range f.words {
cnt += len(w) + 1
}
return cnt - 1
}
func countLetters(s string) int {
cnt := 0
for _, r := range s {
if unicode.IsLetter(r) {
cnt++
}
}
return cnt
}
| #include <ctype.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
typedef struct named_number_tag {
const char* cardinal;
const char* ordinal;
integer number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "biliionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_small_name(const number_names* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const char* get_big_name(const named_number* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const named_number* get_named_number(integer n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
typedef struct word_tag {
size_t offset;
size_t length;
} word_t;
typedef struct word_list_tag {
GArray* words;
GString* str;
} word_list;
void word_list_create(word_list* words) {
words->words = g_array_new(FALSE, FALSE, sizeof(word_t));
words->str = g_string_new(NULL);
}
void word_list_destroy(word_list* words) {
g_string_free(words->str, TRUE);
g_array_free(words->words, TRUE);
}
void word_list_clear(word_list* words) {
g_string_truncate(words->str, 0);
g_array_set_size(words->words, 0);
}
void word_list_append(word_list* words, const char* str) {
size_t offset = words->str->len;
size_t len = strlen(str);
g_string_append_len(words->str, str, len);
word_t word;
word.offset = offset;
word.length = len;
g_array_append_val(words->words, word);
}
word_t* word_list_get(word_list* words, size_t index) {
return &g_array_index(words->words, word_t, index);
}
void word_list_extend(word_list* words, const char* str) {
word_t* word = word_list_get(words, words->words->len - 1);
size_t len = strlen(str);
word->length += len;
g_string_append_len(words->str, str, len);
}
size_t append_number_name(word_list* words, integer n, bool ordinal) {
size_t count = 0;
if (n < 20) {
word_list_append(words, get_small_name(&small[n], ordinal));
count = 1;
} else if (n < 100) {
if (n % 10 == 0) {
word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));
} else {
word_list_append(words, get_small_name(&tens[n/10 - 2], false));
word_list_extend(words, "-");
word_list_extend(words, get_small_name(&small[n % 10], ordinal));
}
count = 1;
} else {
const named_number* num = get_named_number(n);
integer p = num->number;
count += append_number_name(words, n/p, false);
if (n % p == 0) {
word_list_append(words, get_big_name(num, ordinal));
++count;
} else {
word_list_append(words, get_big_name(num, false));
++count;
count += append_number_name(words, n % p, ordinal);
}
}
return count;
}
size_t count_letters(word_list* words, size_t index) {
const word_t* word = word_list_get(words, index);
size_t letters = 0;
const char* s = words->str->str + word->offset;
for (size_t i = 0, n = word->length; i < n; ++i) {
if (isalpha((unsigned char)s[i]))
++letters;
}
return letters;
}
void sentence(word_list* result, size_t count) {
static const char* words[] = {
"Four", "is", "the", "number", "of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,"
};
word_list_clear(result);
size_t n = sizeof(words)/sizeof(words[0]);
for (size_t i = 0; i < n; ++i)
word_list_append(result, words[i]);
for (size_t i = 1; count > n; ++i) {
n += append_number_name(result, count_letters(result, i), false);
word_list_append(result, "in");
word_list_append(result, "the");
n += 2;
n += append_number_name(result, i + 1, true);
word_list_extend(result, ",");
}
}
size_t sentence_length(const word_list* words) {
size_t n = words->words->len;
if (n == 0)
return 0;
return words->str->len + n - 1;
}
int main() {
setlocale(LC_ALL, "");
size_t n = 201;
word_list result = { 0 };
word_list_create(&result);
sentence(&result, n);
printf("Number of letters in first %'lu words in the sequence:\n", n);
for (size_t i = 0; i < n; ++i) {
if (i != 0)
printf("%c", i % 25 == 0 ? '\n' : ' ');
printf("%'2lu", count_letters(&result, i));
}
printf("\nSentence length: %'lu\n", sentence_length(&result));
for (n = 1000; n <= 10000000; n *= 10) {
sentence(&result, n);
const word_t* word = word_list_get(&result, n - 1);
const char* s = result.str->str + word->offset;
printf("The %'luth word is '%.*s' and has %lu letters. ", n,
(int)word->length, s, count_letters(&result, n - 1));
printf("Sentence length: %'lu\n" , sentence_length(&result));
}
word_list_destroy(&result);
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | PACKAGE MAIN
IMPORT (
"FMT"
"TIME"
)
CONST PAGEWIDTH = 80
FUNC MAIN() {
PRINTCAL(1969)
}
FUNC PRINTCAL(YEAR INT) {
THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)
VAR (
DAYARR [12][7][6]INT
MONTH, LASTMONTH TIME.MONTH
WEEKINMONTH, DAYINMONTH INT
)
FOR THISDATE.YEAR() == YEAR {
IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {
WEEKINMONTH = 0
DAYINMONTH = 1
}
WEEKDAY := THISDATE.WEEKDAY()
IF WEEKDAY == 0 && DAYINMONTH > 1 {
WEEKINMONTH++
}
DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()
LASTMONTH = MONTH
DAYINMONTH++
THISDATE = THISDATE.ADD(TIME.HOUR * 24)
}
CENTRE := FMT.SPRINTF("%D", PAGEWIDTH/2)
FMT.PRINTF("%"+CENTRE+"S\N\N", "[SNOOPY]")
CENTRE = FMT.SPRINTF("%D", PAGEWIDTH/2-2)
FMT.PRINTF("%"+CENTRE+"D\N\N", YEAR)
MONTHS := [12]STRING{
" JANUARY ", " FEBRUARY", " MARCH ", " APRIL ",
" MAY ", " JUNE ", " JULY ", " AUGUST ",
"SEPTEMBER", " OCTOBER ", " NOVEMBER", " DECEMBER"}
DAYS := [7]STRING{"SU", "MO", "TU", "WE", "TH", "FR", "SA"}
FOR QTR := 0; QTR < 4; QTR++ {
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {
FMT.PRINTF(" %S ", MONTHS[QTR*3+MONTHINQTR])
}
FMT.PRINTLN()
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {
FOR DAY := 0; DAY < 7; DAY++ {
FMT.PRINTF(" %S", DAYS[DAY])
}
FMT.PRINTF(" ")
}
FMT.PRINTLN()
FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {
FOR DAY := 0; DAY < 7; DAY++ {
IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {
FMT.PRINTF(" ")
} ELSE {
FMT.PRINTF("%3D", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])
}
}
FMT.PRINTF(" ")
}
FMT.PRINTLN()
}
FMT.PRINTLN()
}
}
|
INT PUTCHAR(INT);
INT WIDTH = 80, YEAR = 1969;
INT COLS, LEAD, GAP;
CONST CHAR *WDAYS[] = { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };
STRUCT MONTHS {
CONST CHAR *NAME;
INT DAYS, START_WDAY, AT;
} MONTHS[12] = {
{ "JANUARY", 31, 0, 0 },
{ "FEBRUARY", 28, 0, 0 },
{ "MARCH", 31, 0, 0 },
{ "APRIL", 30, 0, 0 },
{ "MAY", 31, 0, 0 },
{ "JUNE", 30, 0, 0 },
{ "JULY", 31, 0, 0 },
{ "AUGUST", 31, 0, 0 },
{ "SEPTEMBER", 30, 0, 0 },
{ "OCTOBER", 31, 0, 0 },
{ "NOVEMBER", 30, 0, 0 },
{ "DECEMBER", 31, 0, 0 }
};
VOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }
VOID PRINT(CONST CHAR * S){ WHILE (*S != '\0') { PUTCHAR(*S++); } }
INT STRLEN(CONST CHAR * S)
{
INT L = 0;
WHILE (*S++ != '\0') { L ++; };
RETURN L;
}
INT ATOI(CONST CHAR * S)
{
INT I = 0;
INT SIGN = 1;
CHAR C;
WHILE ((C = *S++) != '\0') {
IF (C == '-')
SIGN *= -1;
ELSE {
I *= 10;
I += (C - '0');
}
}
RETURN I * SIGN;
}
VOID INIT_MONTHS(VOID)
{
INT I;
IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))
MONTHS[1].DAYS = 29;
YEAR--;
MONTHS[0].START_WDAY
= (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;
FOR (I = 1; I < 12; I++)
MONTHS[I].START_WDAY =
(MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;
COLS = (WIDTH + 2) / 22;
WHILE (12 % COLS) COLS--;
GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;
IF (GAP > 4) GAP = 4;
LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;
YEAR++;
}
VOID PRINT_ROW(INT ROW)
{
INT C, I, FROM = ROW * COLS, TO = FROM + COLS;
SPACE(LEAD);
FOR (C = FROM; C < TO; C++) {
I = STRLEN(MONTHS[C].NAME);
SPACE((20 - I)/2);
PRINT(MONTHS[C].NAME);
SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));
}
PUTCHAR('\012');
SPACE(LEAD);
FOR (C = FROM; C < TO; C++) {
FOR (I = 0; I < 7; I++) {
PRINT(WDAYS[I]);
PRINT(I == 6 ? "" : " ");
}
IF (C < TO - 1) SPACE(GAP);
ELSE PUTCHAR('\012');
}
WHILE (1) {
FOR (C = FROM; C < TO; C++)
IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;
IF (C == TO) BREAK;
SPACE(LEAD);
FOR (C = FROM; C < TO; C++) {
FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);
WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {
INT MM = ++MONTHS[C].AT;
PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));
PUTCHAR('0' + (MM %10));
IF (I < 7 || C < TO - 1) PUTCHAR(' ');
}
WHILE (I++ <= 7 && C < TO - 1) SPACE(3);
IF (C < TO - 1) SPACE(GAP - 1);
MONTHS[C].START_WDAY = 0;
}
PUTCHAR('\012');
}
PUTCHAR('\012');
}
VOID PRINT_YEAR(VOID)
{
INT Y = YEAR;
INT ROW;
CHAR BUF[32];
CHAR * B = &(BUF[31]);
*B-- = '\0';
DO {
*B-- = '0' + (Y % 10);
Y /= 10;
} WHILE (Y > 0);
B++;
SPACE((WIDTH - STRLEN(B)) / 2);
PRINT(B);PUTCHAR('\012');PUTCHAR('\012');
FOR (ROW = 0; ROW * COLS < 12; ROW++)
PRINT_ROW(ROW);
}
INT MAIN(INT C, CHAR **V)
{
INT I, YEAR_SET = 0, RESULT = 0;
FOR (I = 1; I < C && RESULT == 0; I++) {
IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\0') {
IF (++I == C || (WIDTH = ATOI(V[I])) < 20)
RESULT = 1;
} ELSE IF (!YEAR_SET) {
YEAR = ATOI(V[I]);
IF (YEAR <= 0)
YEAR = 1969;
YEAR_SET = 1;
} ELSE
RESULT = 1;
}
IF (RESULT == 0) {
INIT_MONTHS();
PRINT_YEAR();
} ELSE {
PRINT("BAD ARGS\012USAGE: ");
PRINT(V[0]);
PRINT(" YEAR [-W WIDTH (>= 20)]\012");
}
RETURN RESULT;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"log"
"math/big"
"strings"
)
type result struct {
name string
size int
start int
end int
}
func (r result) String() string {
return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end)
}
func validate(diagram string) []string {
var lines []string
for _, line := range strings.Split(diagram, "\n") {
line = strings.Trim(line, " \t")
if line != "" {
lines = append(lines, line)
}
}
if len(lines) == 0 {
log.Fatal("diagram has no non-empty lines!")
}
width := len(lines[0])
cols := (width - 1) / 3
if cols != 8 && cols != 16 && cols != 32 && cols != 64 {
log.Fatal("number of columns should be 8, 16, 32 or 64")
}
if len(lines)%2 == 0 {
log.Fatal("number of non-empty lines should be odd")
}
if lines[0] != strings.Repeat("+--", cols)+"+" {
log.Fatal("incorrect header line")
}
for i, line := range lines {
if i == 0 {
continue
} else if i%2 == 0 {
if line != lines[0] {
log.Fatal("incorrect separator line")
}
} else if len(line) != width {
log.Fatal("inconsistent line widths")
} else if line[0] != '|' || line[width-1] != '|' {
log.Fatal("non-separator lines must begin and end with '|'")
}
}
return lines
}
func decode(lines []string) []result {
fmt.Println("Name Bits Start End")
fmt.Println("======= ==== ===== ===")
start := 0
width := len(lines[0])
var results []result
for i, line := range lines {
if i%2 == 0 {
continue
}
line := line[1 : width-1]
for _, name := range strings.Split(line, "|") {
size := (len(name) + 1) / 3
name = strings.TrimSpace(name)
res := result{name, size, start, start + size - 1}
results = append(results, res)
fmt.Println(res)
start += size
}
}
return results
}
func unpack(results []result, hex string) {
fmt.Println("\nTest string in hex:")
fmt.Println(hex)
fmt.Println("\nTest string in binary:")
bin := hex2bin(hex)
fmt.Println(bin)
fmt.Println("\nUnpacked:\n")
fmt.Println("Name Size Bit pattern")
fmt.Println("======= ==== ================")
for _, res := range results {
fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1])
}
}
func hex2bin(hex string) string {
z := new(big.Int)
z.SetString(hex, 16)
return fmt.Sprintf("%0*b", 4*len(hex), z)
}
func main() {
const diagram = `
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
`
lines := validate(diagram)
fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n")
for _, line := range lines {
fmt.Println(line)
}
fmt.Println("\nDecoded:\n")
results := decode(lines)
hex := "78477bbf5496e12e1bf169a4"
unpack(results, hex)
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };
char *Lines[MAX_ROWS] = {
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ID |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" |QR| Opcode |AA|TC|RD|RA| Z | RCODE |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | QDCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ANCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | NSCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ARCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
};
typedef struct {
unsigned bit3s;
unsigned mask;
unsigned data;
char A[NAME_SZ+2];
}NAME_T;
NAME_T names[MAX_NAMES];
unsigned idx_name;
enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};
unsigned header[MAX_HDR];
unsigned idx_hdr;
int bit_hdr(char *pLine);
int bit_names(char *pLine);
void dump_names(void);
void make_test_hdr(void);
int main(void){
char *p1; int rv;
printf("Extract meta-data from bit-encoded text form\n");
make_test_hdr();
idx_name = 0;
for( int i=0; i<MAX_ROWS;i++ ){
p1 = Lines[i];
if( p1==NULL ) break;
if( rv = bit_hdr(Lines[i]), rv>0) continue;
if( rv = bit_names(Lines[i]),rv>0) continue;
}
dump_names();
}
int bit_hdr(char *pLine){
char *p1 = strchr(pLine,'+');
if( p1==NULL ) return 0;
int numbits=0;
for( int i=0; i<strlen(p1)-1; i+=3 ){
if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;
numbits++;
}
return numbits;
}
int bit_names(char *pLine){
char *p1,*p2 = pLine, tmp[80];
unsigned sz=0, maskbitcount = 15;
while(1){
p1 = strchr(p2,'|'); if( p1==NULL ) break;
p1++;
p2 = strchr(p1,'|'); if( p2==NULL ) break;
sz = p2-p1;
tmp[sz] = 0;
int k=0;
for(int j=0; j<sz;j++){
if( p1[j] > ' ') tmp[k++] = p1[j];
}
tmp[k]= 0; sz++;
NAME_T *pn = &names[idx_name++];
strcpy(&pn->A[0], &tmp[0]);
pn->bit3s = sz/3;
if( pn->bit3s < 16 ){
for( int i=0; i<pn->bit3s; i++){
pn->mask |= 1 << maskbitcount--;
}
pn->data = header[idx_hdr] & pn->mask;
unsigned m2 = pn->mask;
while( (m2 & 1)==0 ){
m2>>=1;
pn->data >>= 1;
}
if( pn->mask == 0xf ) idx_hdr++;
}
else{
pn->data = header[idx_hdr++];
}
}
return sz;
}
void dump_names(void){
NAME_T *pn;
printf("-name-bits-mask-data-\n");
for( int i=0; i<MAX_NAMES; i++ ){
pn = &names[i];
if( pn->bit3s < 1 ) break;
printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data);
}
puts("bye..");
}
void make_test_hdr(void){
header[ID] = 1024;
header[QDCOUNT] = 12;
header[ANCOUNT] = 34;
header[NSCOUNT] = 56;
header[ARCOUNT] = 78;
header[BITS] = 0xB50A;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"github.com/biogo/biogo/align"
ab "github.com/biogo/biogo/alphabet"
"github.com/biogo/biogo/feat"
"github.com/biogo/biogo/seq/linear"
)
func main() {
lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz",
feat.Undefined, '-', 0, true))
nw := make(align.NW, lc.Len())
for i := range nw {
r := make([]int, lc.Len())
nw[i] = r
for j := range r {
if j != i {
r[j] = -1
}
}
}
a := &linear.Seq{Seq: ab.BytesToLetters([]byte("rosettacode"))}
a.Alpha = lc
b := &linear.Seq{Seq: ab.BytesToLetters([]byte("raisethysword"))}
b.Alpha = lc
aln, err := nw.Align(a, b)
if err != nil {
fmt.Println(err)
return
}
fa := align.Format(a, b, aln, '-')
fmt.Printf("%s\n%s\n", fa[0], fa[1])
aa := fmt.Sprint(fa[0])
ba := fmt.Sprint(fa[1])
ma := make([]byte, len(aa))
for i := range ma {
if aa[i] == ba[i] {
ma[i] = ' '
} else {
ma[i] = '|'
}
}
fmt.Println(string(ma))
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct edit_s edit_t, *edit;
struct edit_s {
char c1, c2;
int n;
edit next;
};
void leven(char *a, char *b)
{
int i, j, la = strlen(a), lb = strlen(b);
edit *tbl = malloc(sizeof(edit) * (1 + la));
tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));
for (i = 1; i <= la; i++)
tbl[i] = tbl[i-1] + (1+lb);
for (i = la; i >= 0; i--) {
char *aa = a + i;
for (j = lb; j >= 0; j--) {
char *bb = b + j;
if (!*aa && !*bb) continue;
edit e = &tbl[i][j];
edit repl = &tbl[i+1][j+1];
edit dela = &tbl[i+1][j];
edit delb = &tbl[i][j+1];
e->c1 = *aa;
e->c2 = *bb;
if (!*aa) {
e->next = delb;
e->n = e->next->n + 1;
continue;
}
if (!*bb) {
e->next = dela;
e->n = e->next->n + 1;
continue;
}
e->next = repl;
if (*aa == *bb) {
e->n = e->next->n;
continue;
}
if (e->next->n > delb->n) {
e->next = delb;
e->c1 = 0;
}
if (e->next->n > dela->n) {
e->next = dela;
e->c1 = *aa;
e->c2 = 0;
}
e->n = e->next->n + 1;
}
}
edit p = tbl[0];
printf("%s -> %s: %d edits\n", a, b, p->n);
while (p->next) {
if (p->c1 == p->c2)
printf("%c", p->c1);
else {
putchar('(');
if (p->c1) putchar(p->c1);
putchar(',');
if (p->c2) putchar(p->c2);
putchar(')');
}
p = p->next;
}
putchar('\n');
free(tbl[0]);
free(tbl);
}
int main(void)
{
leven("raisethysword", "rosettacode");
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"log"
"math/rand"
"testing"
"time"
"github.com/gonum/plot"
"github.com/gonum/plot/plotter"
"github.com/gonum/plot/plotutil"
"github.com/gonum/plot/vg"
)
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
for index := 0; index < itemCount; index++ {
if a[index] > a[index+1] {
a[index], a[index+1] = a[index+1], a[index]
hasChanged = true
}
}
if hasChanged == false {
break
}
}
}
func insertionsort(a []int) {
for i := 1; i < len(a); i++ {
value := a[i]
j := i - 1
for j >= 0 && a[j] > value {
a[j+1] = a[j]
j = j - 1
}
a[j+1] = value
}
}
func quicksort(a []int) {
var pex func(int, int)
pex = func(lower, upper int) {
for {
switch upper - lower {
case -1, 0:
return
case 1:
if a[upper] < a[lower] {
a[upper], a[lower] = a[lower], a[upper]
}
return
}
bx := (upper + lower) / 2
b := a[bx]
lp := lower
up := upper
outer:
for {
for lp < upper && !(b < a[lp]) {
lp++
}
for {
if lp > up {
break outer
}
if a[up] < b {
break
}
up--
}
a[lp], a[up] = a[up], a[lp]
lp++
up--
}
if bx < lp {
if bx < lp-1 {
a[bx], a[lp-1] = a[lp-1], b
}
up = lp - 2
} else {
if bx > lp {
a[bx], a[lp] = a[lp], b
}
up = lp - 1
lp++
}
if up-lower < upper-lp {
pex(lower, up)
lower = lp
} else {
pex(lp, upper)
upper = up
}
}
}
pex(0, len(a)-1)
}
func ones(n int) []int {
s := make([]int, n)
for i := range s {
s[i] = 1
}
return s
}
func ascending(n int) []int {
s := make([]int, n)
v := 1
for i := 0; i < n; {
if rand.Intn(3) == 0 {
s[i] = v
i++
}
v++
}
return s
}
func shuffled(n int) []int {
return rand.Perm(n)
}
const (
nPts = 7
inc = 1000
)
var (
p *plot.Plot
sortName = []string{"Bubble sort", "Insertion sort", "Quicksort"}
sortFunc = []func([]int){bubblesort, insertionsort, quicksort}
dataName = []string{"Ones", "Ascending", "Shuffled"}
dataFunc = []func(int) []int{ones, ascending, shuffled}
)
func main() {
rand.Seed(time.Now().Unix())
var err error
p, err = plot.New()
if err != nil {
log.Fatal(err)
}
p.X.Label.Text = "Data size"
p.Y.Label.Text = "microseconds"
p.Y.Scale = plot.LogScale{}
p.Y.Tick.Marker = plot.LogTicks{}
p.Y.Min = .5
for dx, name := range dataName {
s, err := plotter.NewScatter(plotter.XYs{})
if err != nil {
log.Fatal(err)
}
s.Shape = plotutil.DefaultGlyphShapes[dx]
p.Legend.Add(name, s)
}
for sx, name := range sortName {
l, err := plotter.NewLine(plotter.XYs{})
if err != nil {
log.Fatal(err)
}
l.Color = plotutil.DarkColors[sx]
p.Legend.Add(name, l)
}
for sx := range sortFunc {
bench(sx, 0, 1)
bench(sx, 1, 5)
bench(sx, 2, 5)
}
if err := p.Save(5*vg.Inch, 5*vg.Inch, "comp.png"); err != nil {
log.Fatal(err)
}
}
func bench(sx, dx, rep int) {
log.Println("bench", sortName[sx], dataName[dx], "x", rep)
pts := make(plotter.XYs, nPts)
sf := sortFunc[sx]
for i := range pts {
x := (i + 1) * inc
s0 := dataFunc[dx](x)
s := make([]int, x)
var tSort int64
for j := 0; j < rep; j++ {
tSort += testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
copy(s, s0)
sf(s)
}
}).NsPerOp()
}
tSort /= int64(rep)
log.Println(x, "items", tSort, "ns")
pts[i] = struct{ X, Y float64 }{float64(x), float64(tSort) * .001}
}
pl, ps, err := plotter.NewLinePoints(pts)
if err != nil {
log.Fatal(err)
}
pl.Color = plotutil.DarkColors[sx]
ps.Color = plotutil.DarkColors[sx]
ps.Shape = plotutil.DefaultGlyphShapes[dx]
p.Add(pl, ps)
}
| #ifndef _CSEQUENCE_H
#define _CSEQUENCE_H
#include <stdlib.h>
void setfillconst(double c);
void fillwithconst(double *v, int n);
void fillwithrrange(double *v, int n);
void shuffledrange(double *v, int n);
#endif
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import "fmt"
type node struct {
int
left, right *node
}
func leaves(t *node) chan int {
ch := make(chan int)
var f func(*node)
f = func(n *node) {
if n == nil {
return
}
if n.left == nil && n.right == nil {
ch <- n.int
} else {
f(n.left)
f(n.right)
}
}
go func() {
f(t)
close(ch)
}()
return ch
}
func sameFringe(t1, t2 *node) bool {
f1 := leaves(t1)
f2 := leaves(t2)
for l1 := range f1 {
if l2, ok := <-f2; !ok || l1 != l2 {
return false
}
}
_, ok := <-f2
return !ok
}
func main() {
t1 := &node{3,
&node{1,
&node{int: 1},
&node{int: 2}},
&node{8,
&node{int: 5},
&node{int: 13}}}
t2 := &node{-8,
&node{-3,
&node{-1,
&node{int: 1},
&node{int: 2}},
&node{int: 5}},
&node{int: 13}}
fmt.Println(sameFringe(t1, t2))
}
| #include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
typedef struct {
ucontext_t caller, callee;
char stack[8192];
void *in, *out;
} co_t;
co_t * co_new(void(*f)(), void *data)
{
co_t * c = malloc(sizeof(*c));
getcontext(&c->callee);
c->in = data;
c->callee.uc_stack.ss_sp = c->stack;
c->callee.uc_stack.ss_size = sizeof(c->stack);
c->callee.uc_link = &c->caller;
makecontext(&c->callee, f, 1, (int)c);
return c;
}
void co_del(co_t *c)
{
free(c);
}
inline void
co_yield(co_t *c, void *data)
{
c->out = data;
swapcontext(&c->callee, &c->caller);
}
inline void *
co_collect(co_t *c)
{
c->out = 0;
swapcontext(&c->caller, &c->callee);
return c->out;
}
typedef struct node node;
struct node {
int v;
node *left, *right;
};
node *newnode(int v)
{
node *n = malloc(sizeof(node));
n->left = n->right = 0;
n->v = v;
return n;
}
void tree_insert(node **root, node *n)
{
while (*root) root = ((*root)->v > n->v)
? &(*root)->left
: &(*root)->right;
*root = n;
}
void tree_trav(int x)
{
co_t *c = (co_t *) x;
void trav(node *root) {
if (!root) return;
trav(root->left);
co_yield(c, root);
trav(root->right);
}
trav(c->in);
}
int tree_eq(node *t1, node *t2)
{
co_t *c1 = co_new(tree_trav, t1);
co_t *c2 = co_new(tree_trav, t2);
node *p = 0, *q = 0;
do {
p = co_collect(c1);
q = co_collect(c2);
} while (p && q && (p->v == q->v));
co_del(c1);
co_del(c2);
return !p && !q;
}
int main()
{
int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };
node *t1 = 0, *t2 = 0, *t3 = 0;
void mktree(int *buf, node **root) {
int i;
for (i = 0; buf[i] >= 0; i++)
tree_insert(root, newnode(buf[i]));
}
mktree(x, &t1);
mktree(y, &t2);
mktree(z, &t3);
printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no");
printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no");
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"flag"
"fmt"
)
func main() {
b := flag.Bool("b", false, "just a boolean")
s := flag.String("s", "", "any ol' string")
n := flag.Int("n", 0, "your lucky number")
flag.Parse()
fmt.Println("b:", *b)
fmt.Println("s:", *s)
fmt.Println("n:", *n)
}
| #include <stdio.h>
int main(int argc, char **argv){
int i;
const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
enum {CREATE,PRINT,TITLE,DATE,AUTH};
if (argc<2) {
usage: printf ("Usage: %s [commands]\n"
"-c Create new entry.\n"
"-p Print the latest entry.\n"
"-t Sort by title.\n"
"-d Sort by date.\n"
"-a Sort by author.\n",argv[0]);
return 0;
}
for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
switch (i) {
case CREATE:
...
break;
case PRINT:
...
break;
...
...
default:
printf ("Unknown command..." ...);
goto usage;
}
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"flag"
"fmt"
)
func main() {
b := flag.Bool("b", false, "just a boolean")
s := flag.String("s", "", "any ol' string")
n := flag.Int("n", 0, "your lucky number")
flag.Parse()
fmt.Println("b:", *b)
fmt.Println("s:", *s)
fmt.Println("n:", *n)
}
| #include <stdio.h>
int main(int argc, char **argv){
int i;
const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
enum {CREATE,PRINT,TITLE,DATE,AUTH};
if (argc<2) {
usage: printf ("Usage: %s [commands]\n"
"-c Create new entry.\n"
"-p Print the latest entry.\n"
"-t Sort by title.\n"
"-d Sort by date.\n"
"-a Sort by author.\n",argv[0]);
return 0;
}
for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
switch (i) {
case CREATE:
...
break;
case PRINT:
...
break;
...
...
default:
printf ("Unknown command..." ...);
goto usage;
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"fmt"
"strconv"
"strings"
)
func a(n int) {
s, _ := strconv.Atoi(strings.Repeat("1", n) + "3")
t := s * s
fmt.Printf("%d %d\n", s, t)
}
func main() {
for n := 0; n <= 7; n++ {
a(n)
}
}
| #include <stdio.h>
#include <stdint.h>
uint64_t ones_plus_three(uint64_t ones) {
uint64_t r = 0;
while (ones--) r = r*10 + 1;
return r*10 + 3;
}
int main() {
uint64_t n;
for (n=0; n<8; n++) {
uint64_t x = ones_plus_three(n);
printf("%8lu^2 = %15lu\n", x, x*x);
}
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"strconv"
"strings"
)
func a(n int) {
s, _ := strconv.Atoi(strings.Repeat("1", n) + "3")
t := s * s
fmt.Printf("%d %d\n", s, t)
}
func main() {
for n := 0; n <= 7; n++ {
a(n)
}
}
| #include <stdio.h>
#include <stdint.h>
uint64_t ones_plus_three(uint64_t ones) {
uint64_t r = 0;
while (ones--) r = r*10 + 1;
return r*10 + 3;
}
int main() {
uint64_t n;
for (n=0; n<8; n++) {
uint64_t x = ones_plus_three(n);
printf("%8lu^2 = %15lu\n", x, x*x);
}
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"github.com/micmonay/keybd_event"
"log"
"runtime"
"time"
)
func main() {
kb, err := keybd_event.NewKeyBonding()
if err != nil {
log.Fatal(err)
}
if runtime.GOOS == "linux" {
time.Sleep(2 * time.Second)
}
kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)
err = kb.Launching()
if err != nil {
log.Fatal(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
int main(int argc, char *argv[])
{
Display *dpy;
Window win;
GC gc;
int scr;
Atom WM_DELETE_WINDOW;
XEvent ev;
XEvent ev2;
KeySym keysym;
int loop;
dpy = XOpenDisplay(NULL);
if (dpy == NULL) {
fputs("Cannot open display", stderr);
exit(1);
}
scr = XDefaultScreen(dpy);
win = XCreateSimpleWindow(dpy,
XRootWindow(dpy, scr),
10, 10, 300, 200, 1,
XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));
XStoreName(dpy, win, argv[0]);
XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);
XMapWindow(dpy, win);
XFlush(dpy);
gc = XDefaultGC(dpy, scr);
WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True);
XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);
loop = 1;
while (loop) {
XNextEvent(dpy, &ev);
switch (ev.type)
{
case Expose:
{
char msg1[] = "Clic in the window to generate";
char msg2[] = "a key press event";
XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);
XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);
}
break;
case ButtonPress:
puts("ButtonPress event received");
ev2.type = KeyPress;
ev2.xkey.state = ShiftMask;
ev2.xkey.keycode = 24 + (rand() % 33);
ev2.xkey.same_screen = True;
XSendEvent(dpy, win, True, KeyPressMask, &ev2);
break;
case ClientMessage:
if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)
loop = 0;
break;
case KeyPress:
puts("KeyPress event received");
printf("> keycode: %d\n", ev.xkey.keycode);
keysym = XLookupKeysym(&(ev.xkey), 0);
if (keysym == XK_q ||
keysym == XK_Escape) {
loop = 0;
} else {
char buffer[] = " ";
int nchars = XLookupString(
&(ev.xkey),
buffer,
2,
&keysym,
NULL );
if (nchars == 1)
printf("> Key '%c' pressed\n", buffer[0]);
}
break;
}
}
XDestroyWindow(dpy, win);
XCloseDisplay(dpy);
return 1;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
const (
empty = iota
black
white
)
const (
bqueen = 'B'
wqueen = 'W'
bbullet = '•'
wbullet = '◦'
)
type position struct{ i, j int }
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {
if m == 0 {
return true
}
placingBlack := true
for i := 0; i < n; i++ {
inner:
for j := 0; j < n; j++ {
pos := position{i, j}
for _, queen := range *pBlackQueens {
if queen == pos || !placingBlack && isAttacking(queen, pos) {
continue inner
}
}
for _, queen := range *pWhiteQueens {
if queen == pos || placingBlack && isAttacking(queen, pos) {
continue inner
}
}
if placingBlack {
*pBlackQueens = append(*pBlackQueens, pos)
placingBlack = false
} else {
*pWhiteQueens = append(*pWhiteQueens, pos)
if place(m-1, n, pBlackQueens, pWhiteQueens) {
return true
}
*pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
*pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]
placingBlack = true
}
}
}
if !placingBlack {
*pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
}
return false
}
func isAttacking(queen, pos position) bool {
if queen.i == pos.i {
return true
}
if queen.j == pos.j {
return true
}
if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {
return true
}
return false
}
func printBoard(n int, blackQueens, whiteQueens []position) {
board := make([]int, n*n)
for _, queen := range blackQueens {
board[queen.i*n+queen.j] = black
}
for _, queen := range whiteQueens {
board[queen.i*n+queen.j] = white
}
for i, b := range board {
if i != 0 && i%n == 0 {
fmt.Println()
}
switch b {
case black:
fmt.Printf("%c ", bqueen)
case white:
fmt.Printf("%c ", wqueen)
case empty:
if i%2 == 0 {
fmt.Printf("%c ", bbullet)
} else {
fmt.Printf("%c ", wbullet)
}
}
}
fmt.Println("\n")
}
func main() {
nms := [][2]int{
{2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
{5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
{6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
{7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
}
for _, nm := range nms {
n, m := nm[0], nm[1]
fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n)
var blackQueens, whiteQueens []position
if place(m, n, &blackQueens, &whiteQueens) {
printBoard(n, blackQueens, whiteQueens)
} else {
fmt.Println("No solution exists.\n")
}
}
}
| #include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
enum Piece {
Empty,
Black,
White,
};
typedef struct Position_t {
int x, y;
} Position;
struct Node_t {
Position pos;
struct Node_t *next;
};
void releaseNode(struct Node_t *head) {
if (head == NULL) return;
releaseNode(head->next);
head->next = NULL;
free(head);
}
typedef struct List_t {
struct Node_t *head;
struct Node_t *tail;
size_t length;
} List;
List makeList() {
return (List) { NULL, NULL, 0 };
}
void releaseList(List *lst) {
if (lst == NULL) return;
releaseNode(lst->head);
lst->head = NULL;
lst->tail = NULL;
}
void addNode(List *lst, Position pos) {
struct Node_t *newNode;
if (lst == NULL) {
exit(EXIT_FAILURE);
}
newNode = malloc(sizeof(struct Node_t));
if (newNode == NULL) {
exit(EXIT_FAILURE);
}
newNode->next = NULL;
newNode->pos = pos;
if (lst->head == NULL) {
lst->head = lst->tail = newNode;
} else {
lst->tail->next = newNode;
lst->tail = newNode;
}
lst->length++;
}
void removeAt(List *lst, size_t pos) {
if (lst == NULL) return;
if (pos == 0) {
struct Node_t *temp = lst->head;
if (lst->tail == lst->head) {
lst->tail = NULL;
}
lst->head = lst->head->next;
temp->next = NULL;
free(temp);
lst->length--;
} else {
struct Node_t *temp = lst->head;
struct Node_t *rem;
size_t i = pos;
while (i-- > 1) {
temp = temp->next;
}
rem = temp->next;
if (rem == lst->tail) {
lst->tail = temp;
}
temp->next = rem->next;
rem->next = NULL;
free(rem);
lst->length--;
}
}
bool isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| abs(queen.x - pos.x) == abs(queen.y - pos.y);
}
bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {
struct Node_t *queenNode;
bool placingBlack = true;
int i, j;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
if (m == 0) return true;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
Position pos = { i, j };
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
if (placingBlack) {
addNode(pBlackQueens, pos);
placingBlack = false;
} else {
addNode(pWhiteQueens, pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
removeAt(pBlackQueens, pBlackQueens->length - 1);
removeAt(pWhiteQueens, pWhiteQueens->length - 1);
placingBlack = true;
}
inner: {}
}
}
if (!placingBlack) {
removeAt(pBlackQueens, pBlackQueens->length - 1);
}
return false;
}
void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {
size_t length = n * n;
struct Node_t *queenNode;
char *board;
size_t i, j, k;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
board = calloc(length, sizeof(char));
if (board == NULL) {
exit(EXIT_FAILURE);
}
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = Black;
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = White;
queenNode = queenNode->next;
}
for (i = 0; i < length; i++) {
if (i != 0 && i % n == 0) {
printf("\n");
}
switch (board[i]) {
case Black:
printf("B ");
break;
case White:
printf("W ");
break;
default:
j = i / n;
k = i - j * n;
if (j % 2 == k % 2) {
printf(" ");
} else {
printf("# ");
}
break;
}
}
printf("\n\n");
}
void test(int n, int q) {
List blackQueens = makeList();
List whiteQueens = makeList();
printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n);
if (place(q, n, &blackQueens, &whiteQueens)) {
printBoard(n, &blackQueens, &whiteQueens);
} else {
printf("No solution exists.\n\n");
}
releaseList(&blackQueens);
releaseList(&whiteQueens);
}
int main() {
test(2, 1);
test(3, 1);
test(3, 2);
test(4, 1);
test(4, 2);
test(4, 3);
test(5, 1);
test(5, 2);
test(5, 3);
test(5, 4);
test(5, 5);
test(6, 1);
test(6, 2);
test(6, 3);
test(6, 4);
test(6, 5);
test(6, 6);
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
return EXIT_SUCCESS;
}
|
Write a version of this Go function in C with identical behavior. | package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
| while(1) puts("SPAM");
|
Write a version of this Go function in C with identical behavior. | package main
import "fmt"
type person struct{
name string
age int
}
func copy(p person) person {
return person{p.name, p.age}
}
func main() {
p := person{"Dave", 40}
fmt.Println(p)
q := copy(p)
fmt.Println(q)
}
|
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]
#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)
#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)
#define COMPILE_TIME_ASSERT(X) COMPILE_TIME_ASSERT2(X,__LINE__)
COMPILE_TIME_ASSERT(sizeof(long)==8);
int main()
{
COMPILE_TIME_ASSERT(sizeof(int)==4);
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"rcu"
"strconv"
)
func equalSets(s1, s2 map[rune]bool) bool {
if len(s1) != len(s2) {
return false
}
for k, _ := range s1 {
_, ok := s2[k]
if !ok {
return false
}
}
return true
}
func main() {
const limit = 100_000
count := 0
fmt.Println("Numbers under 100,000 which use the same digits in decimal or hex:")
for n := 0; n < limit; n++ {
h := strconv.FormatInt(int64(n), 16)
hs := make(map[rune]bool)
for _, c := range h {
hs[c] = true
}
ns := make(map[rune]bool)
for _, c := range strconv.Itoa(n) {
ns[c] = true
}
if equalSets(hs, ns) {
count++
fmt.Printf("%6s ", rcu.Commatize(n))
if count%10 == 0 {
fmt.Println()
}
}
}
fmt.Printf("\n\n%d such numbers found.\n", count)
}
| #include <stdio.h>
#define LIMIT 100000
int digitset(int num, int base) {
int set;
for (set = 0; num; num /= base)
set |= 1 << num % base;
return set;
}
int main() {
int i, c = 0;
for (i = 0; i < LIMIT; i++)
if (digitset(i,10) == digitset(i,16))
printf("%6d%c", i, ++c%10 ? ' ' : '\n');
printf("\n");
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import "fmt"
func largestPrimeFactor(n uint64) uint64 {
if n < 2 {
return 1
}
inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6}
max := uint64(1)
for n%2 == 0 {
max = 2
n /= 2
}
for n%3 == 0 {
max = 3
n /= 3
}
for n%5 == 0 {
max = 5
n /= 5
}
k := uint64(7)
i := 0
for k*k <= n {
if n%k == 0 {
max = k
n /= k
} else {
k += inc[i]
i = (i + 1) % 8
}
}
if n > 1 {
return n
}
return max
}
func main() {
n := uint64(600851475143)
fmt.Println("The largest prime factor of", n, "is", largestPrimeFactor(n), "\b.")
}
| #include <stdio.h>
#include <stdlib.h>
int isprime( long int n ) {
int i=3;
if(!(n%2)) return 0;
while( i*i < n ) {
if(!(n%i)) return 0;
i+=2;
}
return 1;
}
int main(void) {
long int n=600851475143, j=3;
while(!isprime(n)) {
if(!(n%j)) n/=j;
j+=2;
}
printf( "%ld\n", n );
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import "fmt"
func largestProperDivisor(n int) int {
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return n / i
}
}
return 1
}
func main() {
fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
fmt.Print(" 1 ")
for n := 2; n <= 100; n++ {
if n%2 == 0 {
fmt.Printf("%2d ", n/2)
} else {
fmt.Printf("%2d ", largestProperDivisor(n))
}
if n%10 == 0 {
fmt.Println()
}
}
}
| #include <stdio.h>
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf("%3d", lpd(i));
if (i % 10 == 0) printf("\n");
}
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"strconv"
)
func toWord(w int64) string { return fmt.Sprintf("W%05d", w) }
func fromWord(ws string) int64 {
var u, _ = strconv.ParseUint(ws[1:], 10, 64)
return int64(u)
}
func main() {
fmt.Println("Starting figures:")
lat := 28.3852
lon := -81.5638
fmt.Printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon)
ilat := int64(lat*10000 + 900000)
ilon := int64(lon*10000 + 1800000)
latlon := (ilat << 22) + ilon
w1 := (latlon >> 28) & 0x7fff
w2 := (latlon >> 14) & 0x3fff
w3 := latlon & 0x3fff
w1s := toWord(w1)
w2s := toWord(w2)
w3s := toWord(w3)
fmt.Println("\nThree word location is:")
fmt.Printf(" %s %s %s\n", w1s, w2s, w3s)
w1 = fromWord(w1s)
w2 = fromWord(w2s)
w3 = fromWord(w3s)
latlon = (w1 << 28) | (w2 << 14) | w3
ilat = latlon >> 22
ilon = latlon & 0x3fffff
lat = float64(ilat-900000) / 10000
lon = float64(ilon-1800000) / 10000
fmt.Println("\nAfter reversing the procedure:")
fmt.Printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon)
}
| #include <stdio.h>
#include <stdlib.h>
typedef long long int64;
void to_word(char *ws, int64 w) {
sprintf(ws, "W%05lld", w);
}
int64 from_word(char *ws) {
return atoi(++ws);
}
int main() {
double lat, lon;
int64 latlon, ilat, ilon, w1, w2, w3;
char w1s[7], w2s[7], w3s[7];
printf("Starting figures:\n");
lat = 28.3852;
lon = -81.5638;
printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon);
ilat = (int64)(lat*10000 + 900000);
ilon = (int64)(lon*10000 + 1800000);
latlon = (ilat << 22) + ilon;
w1 = (latlon >> 28) & 0x7fff;
w2 = (latlon >> 14) & 0x3fff;
w3 = latlon & 0x3fff;
to_word(w1s, w1);
to_word(w2s, w2);
to_word(w3s, w3);
printf("\nThree word location is:\n");
printf(" %s %s %s\n", w1s, w2s, w3s);
w1 = from_word(w1s);
w2 = from_word(w2s);
w3 = from_word(w3s);
latlon = (w1 << 28) | (w2 << 14) | w3;
ilat = latlon >> 22;
ilon = latlon & 0x3fffff;
lat = (double)(ilat-900000) / 10000;
lon = (double)(ilon-1800000) / 10000;
printf("\nAfter reversing the procedure:\n");
printf(" latitude = %0.4f, longitude = %0.4f\n", lat, lon);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"bytes"
"fmt"
)
type symbolTable string
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
}
func (symbols symbolTable) decode(seq []byte) string {
chars := make([]byte, len(seq))
pad := []byte(symbols)
for i, x := range seq {
c := pad[x]
chars[i] = c
copy(pad[1:], pad[:x])
pad[0] = c
}
return string(chars)
}
func main() {
m := symbolTable("abcdefghijklmnopqrstuvwxyz")
for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
enc := m.encode(s)
dec := m.decode(enc)
fmt.Println(s, enc, dec)
if dec != s {
panic("Whoops!")
}
}
}
| #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
int move_to_front(char *str,char c)
{
char *q,*p;
int shift=0;
p=(char *)malloc(strlen(str)+1);
strcpy(p,str);
q=strchr(p,c);
shift=q-p;
strncpy(str+1,p,shift);
str[0]=c;
free(p);
return shift;
}
void decode(int* pass,int size,char *sym)
{
int i,index;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=table[pass[i]];
index=move_to_front(table,c);
if(pass[i]!=index) printf("there is an error");
sym[i]=c;
}
sym[size]='\0';
}
void encode(char *sym,int size,int *pass)
{
int i=0;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=sym[i];
pass[i]=move_to_front(table,c);
}
}
int check(char *sym,int size,int *pass)
{
int *pass2=malloc(sizeof(int)*size);
char *sym2=malloc(sizeof(char)*size);
int i,val=1;
encode(sym,size,pass2);
i=0;
while(i<size && pass[i]==pass2[i])i++;
if(i!=size)val=0;
decode(pass,size,sym2);
if(strcmp(sym,sym2)!=0)val=0;
free(sym2);
free(pass2);
return val;
}
int main()
{
char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
int pass[MAX_SIZE]={0};
int i,len,j;
for(i=0;i<3;i++)
{
len=strlen(sym[i]);
encode(sym[i],len,pass);
printf("%s : [",sym[i]);
for(j=0;j<len;j++)
printf("%d ",pass[j]);
printf("]\n");
if(check(sym[i],len,pass))
printf("Correct :)\n");
else
printf("Incorrect :(\n");
}
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"log"
"github.com/jtblin/go-ldap-client"
)
func main() {
client := &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.example.com",
Port: 389,
GroupFilter: "(memberUid=%s)",
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect : %+v", err)
}
groups, err := client.GetGroupsOfUser("username")
if err != nil {
log.Fatalf("Error getting groups for user %s: %+v", "username", err)
}
log.Printf("Groups: %+v", groups)
}
| #include <ldap.h>
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
LDAPMessage **result;
ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE,
"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))",
NULL,
0,
result);
ldap_msgfree(*result);
ldap_unbind(ld);
|
Please provide an equivalent version of this Go code in C. | <package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
"log"
)
func matPrint(m mat.Matrix) {
fa := mat.Formatted(m, mat.Prefix(""), mat.Squeeze())
fmt.Printf("%13.10f\n", fa)
}
func main() {
var svd mat.SVD
a := mat.NewDense(2, 2, []float64{3, 0, 4, 5})
ok := svd.Factorize(a, mat.SVDFull)
if !ok {
log.Fatal("Something went wrong!")
}
u := mat.NewDense(2, 2, nil)
svd.UTo(u)
fmt.Println("U:")
matPrint(u)
values := svd.Values(nil)
sigma := mat.NewDense(2, 2, []float64{values[0], 0, 0, values[1]})
fmt.Println("\nΣ:")
matPrint(sigma)
vt := mat.NewDense(2, 2, nil)
svd.VTo(vt)
fmt.Println("\nVT:")
matPrint(vt)
}
| #include <stdio.h>
#include <gsl/gsl_linalg.h>
void gsl_matrix_print(const gsl_matrix *M) {
int rows = M->size1;
int cols = M->size2;
for (int i = 0; i < rows; i++) {
printf("|");
for (int j = 0; j < cols; j++) {
printf("% 12.10f ", gsl_matrix_get(M, i, j));
}
printf("\b|\n");
}
printf("\n");
}
int main(){
double a[] = {3, 0, 4, 5};
gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);
gsl_matrix *V = gsl_matrix_alloc(2, 2);
gsl_vector *S = gsl_vector_alloc(2);
gsl_vector *work = gsl_vector_alloc(2);
gsl_linalg_SV_decomp(&A.matrix, V, S, work);
gsl_matrix_transpose(V);
double s[] = {S->data[0], 0, 0, S->data[1]};
gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);
printf("U:\n");
gsl_matrix_print(&A.matrix);
printf("S:\n");
gsl_matrix_print(&SM.matrix);
printf("VT:\n");
gsl_matrix_print(V);
gsl_matrix_free(V);
gsl_vector_free(S);
gsl_vector_free(work);
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"rcu"
)
func main() {
fmt.Println("Cumulative sums of the first 50 cubes:")
sum := 0
for n := 0; n < 50; n++ {
sum += n * n * n
fmt.Printf("%9s ", rcu.Commatize(sum))
if n%10 == 9 {
fmt.Println()
}
}
fmt.Println()
| #include <stdio.h>
int main() {
for (int i = 0, sum = 0; i < 50; ++i) {
sum += i * i * i;
printf("%7d%c", sum, (i + 1) % 5 == 0 ? '\n' : ' ');
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"fmt"
"io"
"log"
"os"
"sync/atomic"
"syscall"
)
const (
inputFifo = "/tmp/in.fifo"
outputFifo = "/tmp/out.fifo"
readsize = 64 << 10
)
func openFifo(path string, oflag int) (f *os.File, err error) {
err = syscall.Mkfifo(path, 0660)
if err != nil && !os.IsExist(err) {
return
}
f, err = os.OpenFile(path, oflag, 0660)
if err != nil {
return
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
if fi.Mode()&os.ModeType != os.ModeNamedPipe {
f.Close()
return nil, os.ErrExist
}
return
}
func main() {
var byteCount int64
go func() {
var delta int
var err error
buf := make([]byte, readsize)
for {
input, err := openFifo(inputFifo, os.O_RDONLY)
if err != nil {
break
}
for err == nil {
delta, err = input.Read(buf)
atomic.AddInt64(&byteCount, int64(delta))
}
input.Close()
if err != io.EOF {
break
}
}
log.Fatal(err)
}()
for {
output, err := openFifo(outputFifo, os.O_WRONLY)
if err != nil {
log.Fatal(err)
}
cnt := atomic.LoadInt64(&byteCount)
fmt.Fprintln(output, cnt)
output.Close()
}
}
| #include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#define WILL_BLOCK_EVERYTHING 0
#if WILL_BLOCK_EVERYTHING
#include <poll.h>
#endif
size_t tally = 0;
void* write_loop(void *a)
{
int fd;
char buf[32];
while (1) {
#if WILL_BLOCK_EVERYTHING
fd = open("out", O_WRONLY|O_NONBLOCK);
if (fd < 0) {
usleep(200000);
continue;
}
#else
fd = open("out", O_WRONLY);
#endif
write(fd, buf, snprintf(buf, 32, "%d\n", tally));
close(fd);
usleep(10000);
}
}
void read_loop()
{
int fd;
size_t len;
char buf[PIPE_BUF];
#if WILL_BLOCK_EVERYTHING
struct pollfd pfd;
pfd.events = POLLIN;
#endif
while (1) {
#if WILL_BLOCK_EVERYTHING
fd = pfd.fd = open("in", O_RDONLY|O_NONBLOCK);
fcntl(fd, F_SETFL, 0);
poll(&pfd, 1, INFTIM);
#else
fd = open("in", O_RDONLY);
#endif
while ((len = read(fd, buf, PIPE_BUF)) > 0) tally += len;
close(fd);
}
}
int main()
{
pthread_t pid;
mkfifo("in", 0666);
mkfifo("out", 0666);
pthread_create(&pid, 0, write_loop, 0);
read_loop();
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
)
func Float64IsInt(f float64) bool {
_, frac := math.Modf(f)
return frac == 0
}
func Float32IsInt(f float32) bool {
return Float64IsInt(float64(f))
}
func Complex128IsInt(c complex128) bool {
return imag(c) == 0 && Float64IsInt(real(c))
}
func Complex64IsInt(c complex64) bool {
return imag(c) == 0 && Float64IsInt(float64(real(c)))
}
type hasIsInt interface {
IsInt() bool
}
var bigIntT = reflect.TypeOf((*big.Int)(nil))
func IsInt(i interface{}) bool {
if ci, ok := i.(hasIsInt); ok {
return ci.IsInt()
}
switch v := reflect.ValueOf(i); v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return true
case reflect.Float32, reflect.Float64:
return Float64IsInt(v.Float())
case reflect.Complex64, reflect.Complex128:
return Complex128IsInt(v.Complex())
case reflect.String:
if r, ok := new(big.Rat).SetString(v.String()); ok {
return r.IsInt()
}
case reflect.Ptr:
if v.Type() == bigIntT {
return true
}
}
return false
}
type intbased int16
type complexbased complex64
type customIntegerType struct {
}
func (customIntegerType) IsInt() bool { return true }
func (customIntegerType) String() string { return "<…>" }
func main() {
hdr := fmt.Sprintf("%27s %-6s %s\n", "Input", "IsInt", "Type")
show2 := func(t bool, i interface{}, args ...interface{}) {
istr := fmt.Sprint(i)
fmt.Printf("%27s %-6t %T ", istr, t, i)
fmt.Println(args...)
}
show := func(i interface{}, args ...interface{}) {
show2(IsInt(i), i, args...)
}
fmt.Print("Using Float64IsInt with float64:\n", hdr)
neg1 := -1.
for _, f := range []float64{
0, neg1 * 0, -2, -2.000000000000001, 10. / 2, 22. / 3,
math.Pi,
math.MinInt64, math.MaxUint64,
math.SmallestNonzeroFloat64, math.MaxFloat64,
math.NaN(), math.Inf(1), math.Inf(-1),
} {
show2(Float64IsInt(f), f)
}
fmt.Print("\nUsing Complex128IsInt with complex128:\n", hdr)
for _, c := range []complex128{
3, 1i, 0i, 3.4,
} {
show2(Complex128IsInt(c), c)
}
fmt.Println("\nUsing reflection:")
fmt.Print(hdr)
show("hello")
show(math.MaxFloat64)
show("9e100")
f := new(big.Float)
show(f)
f.SetString("1e-3000")
show(f)
show("(4+0i)", "(complex strings not parsed)")
show(4 + 0i)
show(rune('§'), "or rune")
show(byte('A'), "or byte")
var t1 intbased = 5200
var t2a, t2b complexbased = 5 + 0i, 5 + 1i
show(t1)
show(t2a)
show(t2b)
x := uintptr(unsafe.Pointer(&t2b))
show(x)
show(math.MinInt32)
show(uint64(math.MaxUint64))
b, _ := new(big.Int).SetString(strings.Repeat("9", 25), 0)
show(b)
r := new(big.Rat)
show(r)
r.SetString("2/3")
show(r)
show(r.SetFrac(b, new(big.Int).SetInt64(9)))
show("12345/5")
show(new(customIntegerType))
}
| #include <stdio.h>
#include <complex.h>
#include <math.h>
#define FMTSPEC(arg) _Generic((arg), \
float: "%f", double: "%f", \
long double: "%Lf", unsigned int: "%u", \
unsigned long: "%lu", unsigned long long: "%llu", \
int: "%d", long: "%ld", long long: "%lld", \
default: "(invalid type (%p)")
#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \
I * (long double)(y)))
#define TEST_CMPL(i, j)\
printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \
printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false"))
#define TEST_REAL(i)\
printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false"))
static inline int isint(long double complex n)
{
return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);
}
int main(void)
{
TEST_REAL(0);
TEST_REAL(-0);
TEST_REAL(-2);
TEST_REAL(-2.00000000000001);
TEST_REAL(5);
TEST_REAL(7.3333333333333);
TEST_REAL(3.141592653589);
TEST_REAL(-9.223372036854776e18);
TEST_REAL(5e-324);
TEST_REAL(NAN);
TEST_CMPL(6, 0);
TEST_CMPL(0, 1);
TEST_CMPL(0, 0);
TEST_CMPL(3.4, 0);
double complex test1 = 5 + 0*I,
test2 = 3.4f,
test3 = 3,
test4 = 0 + 1.2*I;
printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false");
printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false");
printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false");
printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false");
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
| #include <stdlib.h>
int main()
{
system("ls");
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"fmt"
"math"
)
type vector [3]float64
type matrix [3]vector
func norm(v vector) float64 {
return math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
}
func normalize(v vector) vector {
length := norm(v)
return vector{v[0] / length, v[1] / length, v[2] / length}
}
func dotProduct(v1, v2 vector) float64 {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}
func crossProduct(v1, v2 vector) vector {
return vector{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]}
}
func getAngle(v1, v2 vector) float64 {
return math.Acos(dotProduct(v1, v2) / (norm(v1) * norm(v2)))
}
func matrixMultiply(m matrix, v vector) vector {
return vector{dotProduct(m[0], v), dotProduct(m[1], v), dotProduct(m[2], v)}
}
func aRotate(p, v vector, a float64) vector {
ca, sa := math.Cos(a), math.Sin(a)
t := 1 - ca
x, y, z := v[0], v[1], v[2]
r := matrix{
{ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},
{x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},
{z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t},
}
return matrixMultiply(r, p)
}
func main() {
v1 := vector{5, -6, 4}
v2 := vector{8, 5, -30}
a := getAngle(v1, v2)
cp := crossProduct(v1, v2)
ncp := normalize(cp)
np := aRotate(v1, ncp, a)
fmt.Println(np)
}
| #include <stdio.h>
#include <math.h>
typedef struct {
double x, y, z;
} vector;
typedef struct {
vector i, j, k;
} matrix;
double norm(vector v) {
return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
}
vector normalize(vector v){
double length = norm(v);
vector n = {v.x / length, v.y / length, v.z / length};
return n;
}
double dotProduct(vector v1, vector v2) {
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}
vector crossProduct(vector v1, vector v2) {
vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x};
return cp;
}
double getAngle(vector v1, vector v2) {
return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2)));
}
vector matrixMultiply(matrix m ,vector v) {
vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)};
return mm;
}
vector aRotate(vector p, vector v, double a) {
double ca = cos(a), sa = sin(a);
double t = 1.0 - ca;
double x = v.x, y = v.y, z = v.z;
matrix r = {
{ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa},
{x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa},
{z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t}
};
return matrixMultiply(r, p);
}
int main() {
vector v1 = {5, -6, 4}, v2 = {8, 5, -30};
double a = getAngle(v1, v2);
vector cp = crossProduct(v1, v2);
vector ncp = normalize(cp);
vector np = aRotate(v1, ncp, a);
printf("[%.13f, %.13f, %.13f]\n", np.x, np.y, np.z);
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/xsd"
"io/ioutil"
"log"
"os"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
xsdfile := "shiporder.xsd"
f, err := os.Open(xsdfile)
check(err)
defer f.Close()
buf, err := ioutil.ReadAll(f)
check(err)
s, err := xsd.Parse(buf)
check(err)
defer s.Free()
xmlfile := "shiporder.xml"
f2, err := os.Open(xmlfile)
check(err)
defer f2.Close()
buf2, err := ioutil.ReadAll(f2)
check(err)
d, err := libxml2.Parse(buf2)
check(err)
if err := s.Validate(d); err != nil {
for _, e := range err.(xsd.SchemaValidationError).Errors() {
log.Printf("error: %s", e.Error())
}
return
}
fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!")
}
| #include <libxml/xmlschemastypes.h>
int main(int argC, char** argV)
{
if (argC <= 2) {
printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]);
return 0;
}
xmlDocPtr doc;
xmlSchemaPtr schema = NULL;
xmlSchemaParserCtxtPtr ctxt;
char *XMLFileName = argV[1];
char *XSDFileName = argV[2];
int ret;
xmlLineNumbersDefault(1);
ctxt = xmlSchemaNewParserCtxt(XSDFileName);
xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
schema = xmlSchemaParse(ctxt);
xmlSchemaFreeParserCtxt(ctxt);
doc = xmlReadFile(XMLFileName, NULL, 0);
if (doc == NULL){
fprintf(stderr, "Could not parse %s\n", XMLFileName);
}
else{
xmlSchemaValidCtxtPtr ctxt;
ctxt = xmlSchemaNewValidCtxt(schema);
xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
ret = xmlSchemaValidateDoc(ctxt, doc);
if (ret == 0){
printf("%s validates\n", XMLFileName);
}
else if (ret > 0){
printf("%s fails to validate\n", XMLFileName);
}
else{
printf("%s validation generated an internal error\n", XMLFileName);
}
xmlSchemaFreeValidCtxt(ctxt);
xmlFreeDoc(doc);
}
if(schema != NULL)
xmlSchemaFree(schema);
xmlSchemaCleanupTypes();
xmlCleanupParser();
xmlMemoryDump();
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"sort"
)
type Node struct {
val int
back *Node
}
func lis (n []int) (result []int) {
var pileTops []*Node
for _, x := range n {
j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
node := &Node{ x, nil }
if j != 0 { node.back = pileTops[j-1] }
if j != len(pileTops) {
pileTops[j] = node
} else {
pileTops = append(pileTops, node)
}
}
if len(pileTops) == 0 { return []int{} }
for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
result = append(result, node.val)
}
for i := 0; i < len(result)/2; i++ {
result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
}
return
}
func main() {
for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
}
}
| #include <stdio.h>
#include <stdlib.h>
struct node {
int val, len;
struct node *next;
};
void lis(int *v, int len)
{
int i;
struct node *p, *n = calloc(len, sizeof *n);
for (i = 0; i < len; i++)
n[i].val = v[i];
for (i = len; i--; ) {
for (p = n + i; p++ < n + len; ) {
if (p->val > n[i].val && p->len >= n[i].len) {
n[i].next = p;
n[i].len = p->len + 1;
}
}
}
for (i = 0, p = n; i < len; i++)
if (n[i].len > p->len) p = n + i;
do printf(" %d", p->val); while ((p = p->next));
putchar('\n');
free(n);
}
int main(void)
{
int x[] = { 3, 2, 6, 4, 5, 1 };
int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
lis(x, sizeof(x) / sizeof(int));
lis(y, sizeof(y) / sizeof(int));
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func (v *vector) normalize() {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
type sphere struct {
cx, cy, cz int
r int
}
func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {
x -= s.cx
y -= s.cy
if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {
zsqrt := math.Sqrt(float64(zsq))
return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true
}
return 0, 0, false
}
func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {
w, h := pos.r*4, pos.r*3
bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)
img := image.NewGray(bounds)
vec := new(vector)
for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {
for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {
zb1, zb2, hit := pos.hit(x, y)
if !hit {
continue
}
zs1, zs2, hit := neg.hit(x, y)
if hit {
if zs1 > zb1 {
hit = false
} else if zs2 > zb2 {
continue
}
}
if hit {
vec[0] = float64(neg.cx - x)
vec[1] = float64(neg.cy - y)
vec[2] = float64(neg.cz) - zs2
} else {
vec[0] = float64(x - pos.cx)
vec[1] = float64(y - pos.cy)
vec[2] = zb1 - float64(pos.cz)
}
vec.normalize()
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
return img
}
func main() {
dir := &vector{20, -40, -10}
dir.normalize()
pos := &sphere{0, 0, 0, 120}
neg := &sphere{-90, -90, -30, 100}
img := deathStar(pos, neg, 1.5, .2, dir)
f, err := os.Create("dstar.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <math.h>
#include <unistd.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { -50, 0, 50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
typedef struct { double cx, cy, cz, r; } sphere_t;
sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };
int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)
{
double zsq;
x -= sph->cx;
y -= sph->cy;
zsq = sph->r * sph->r - (x * x + y * y);
if (zsq < 0) return 0;
zsq = sqrt(zsq);
*z1 = sph->cz - zsq;
*z2 = sph->cz + zsq;
return 1;
}
void draw_sphere(double k, double ambient)
{
int i, j, intensity, hit_result;
double b;
double vec[3], x, y, zb1, zb2, zs1, zs2;
for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {
y = i + .5;
for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {
x = (j - pos.cx) / 2. + .5 + pos.cx;
if (!hit_sphere(&pos, x, y, &zb1, &zb2))
hit_result = 0;
else if (!hit_sphere(&neg, x, y, &zs1, &zs2))
hit_result = 1;
else if (zs1 > zb1) hit_result = 1;
else if (zs2 > zb2) hit_result = 0;
else if (zs2 > zb1) hit_result = 2;
else hit_result = 1;
switch(hit_result) {
case 0:
putchar('+');
continue;
case 1:
vec[0] = x - pos.cx;
vec[1] = y - pos.cy;
vec[2] = zb1 - pos.cz;
break;
default:
vec[0] = neg.cx - x;
vec[1] = neg.cy - y;
vec[2] = neg.cz - zs2;
}
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
}
putchar('\n');
}
}
int main()
{
double ang = 0;
while (1) {
printf("\033[H");
light[1] = cos(ang * 2);
light[2] = cos(ang);
light[0] = sin(ang);
normalize(light);
ang += .05;
draw_sphere(2, .3);
usleep(100000);
}
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func (v *vector) normalize() {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
type sphere struct {
cx, cy, cz int
r int
}
func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {
x -= s.cx
y -= s.cy
if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {
zsqrt := math.Sqrt(float64(zsq))
return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true
}
return 0, 0, false
}
func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {
w, h := pos.r*4, pos.r*3
bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)
img := image.NewGray(bounds)
vec := new(vector)
for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {
for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {
zb1, zb2, hit := pos.hit(x, y)
if !hit {
continue
}
zs1, zs2, hit := neg.hit(x, y)
if hit {
if zs1 > zb1 {
hit = false
} else if zs2 > zb2 {
continue
}
}
if hit {
vec[0] = float64(neg.cx - x)
vec[1] = float64(neg.cy - y)
vec[2] = float64(neg.cz) - zs2
} else {
vec[0] = float64(x - pos.cx)
vec[1] = float64(y - pos.cy)
vec[2] = zb1 - float64(pos.cz)
}
vec.normalize()
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
return img
}
func main() {
dir := &vector{20, -40, -10}
dir.normalize()
pos := &sphere{0, 0, 0, 120}
neg := &sphere{-90, -90, -30, 100}
img := deathStar(pos, neg, 1.5, .2, dir)
f, err := os.Create("dstar.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <math.h>
#include <unistd.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { -50, 0, 50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
typedef struct { double cx, cy, cz, r; } sphere_t;
sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };
int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)
{
double zsq;
x -= sph->cx;
y -= sph->cy;
zsq = sph->r * sph->r - (x * x + y * y);
if (zsq < 0) return 0;
zsq = sqrt(zsq);
*z1 = sph->cz - zsq;
*z2 = sph->cz + zsq;
return 1;
}
void draw_sphere(double k, double ambient)
{
int i, j, intensity, hit_result;
double b;
double vec[3], x, y, zb1, zb2, zs1, zs2;
for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {
y = i + .5;
for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {
x = (j - pos.cx) / 2. + .5 + pos.cx;
if (!hit_sphere(&pos, x, y, &zb1, &zb2))
hit_result = 0;
else if (!hit_sphere(&neg, x, y, &zs1, &zs2))
hit_result = 1;
else if (zs1 > zb1) hit_result = 1;
else if (zs2 > zb2) hit_result = 0;
else if (zs2 > zb1) hit_result = 2;
else hit_result = 1;
switch(hit_result) {
case 0:
putchar('+');
continue;
case 1:
vec[0] = x - pos.cx;
vec[1] = y - pos.cy;
vec[2] = zb1 - pos.cz;
break;
default:
vec[0] = neg.cx - x;
vec[1] = neg.cy - y;
vec[2] = neg.cz - zs2;
}
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
}
putchar('\n');
}
}
int main()
{
double ang = 0;
while (1) {
printf("\033[H");
light[1] = cos(ang * 2);
light[2] = cos(ang);
light[0] = sin(ang);
normalize(light);
ang += .05;
draw_sphere(2, .3);
usleep(100000);
}
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
)
func hough(im image.Image, ntx, mry int) draw.Image {
nimx := im.Bounds().Max.X
mimy := im.Bounds().Max.Y
him := image.NewGray(image.Rect(0, 0, ntx, mry))
draw.Draw(him, him.Bounds(), image.NewUniform(color.White),
image.Point{}, draw.Src)
rmax := math.Hypot(float64(nimx), float64(mimy))
dr := rmax / float64(mry/2)
dth := math.Pi / float64(ntx)
for jx := 0; jx < nimx; jx++ {
for iy := 0; iy < mimy; iy++ {
col := color.GrayModel.Convert(im.At(jx, iy)).(color.Gray)
if col.Y == 255 {
continue
}
for jtx := 0; jtx < ntx; jtx++ {
th := dth * float64(jtx)
r := float64(jx)*math.Cos(th) + float64(iy)*math.Sin(th)
iry := mry/2 - int(math.Floor(r/dr+.5))
col = him.At(jtx, iry).(color.Gray)
if col.Y > 0 {
col.Y--
him.SetGray(jtx, iry, col)
}
}
}
}
return him
}
func main() {
f, err := os.Open("Pentagon.png")
if err != nil {
fmt.Println(err)
return
}
pent, err := png.Decode(f)
if err != nil {
fmt.Println(err)
return
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
h := hough(pent, 460, 360)
if f, err = os.Create("hough.png"); err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, h); err != nil {
fmt.Println(err)
}
if cErr := f.Close(); cErr != nil && err == nil {
fmt.Println(err)
}
}
| #include "SL_Generated.h"
#include "CImg.h"
using namespace cimg_library;
int main( int argc, char** argv )
{
string fileName = "Pentagon.bmp";
if(argc > 1) fileName = argv[1];
int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);
int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]);
int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]);
int threads = 0; if(argc > 5) threads = atoi(argv[5]);
char titleBuffer[200];
SLTimer t;
CImg<int> image(fileName.c_str());
int imageDimensions[] = {image.height(), image.width(), 0};
Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions);
Sequence< Sequence<int> > result;
sl_init(threads);
t.start();
sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result);
t.stop();
CImg<int> resultImage(result[1].size(), result.size());
for(int y = 0; y < result.size(); y++)
for(int x = 0; x < result[y+1].size(); x++)
resultImage(x,result.size() - 1 - y) = result[y+1][x+1];
sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0",
image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime());
resultImage.display(titleBuffer);
sl_done();
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"math"
)
type ifctn func(float64) float64
func simpson38(f ifctn, a, b float64, n int) float64 {
h := (b - a) / float64(n)
h1 := h / 3
sum := f(a) + f(b)
for j := 3*n - 1; j > 0; j-- {
if j%3 == 0 {
sum += 2 * f(a+h1*float64(j))
} else {
sum += 3 * f(a+h1*float64(j))
}
}
return h * sum / 8
}
func gammaIncQ(a, x float64) float64 {
aa1 := a - 1
var f ifctn = func(t float64) float64 {
return math.Pow(t, aa1) * math.Exp(-t)
}
y := aa1
h := 1.5e-2
for f(y)*(x-y) > 2e-8 && y < x {
y += .4
}
if y > x {
y = x
}
return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))
}
func chi2ud(ds []int) float64 {
var sum, expected float64
for _, d := range ds {
expected += float64(d)
}
expected /= float64(len(ds))
for _, d := range ds {
x := float64(d) - expected
sum += x * x
}
return sum / expected
}
func chi2p(dof int, distance float64) float64 {
return gammaIncQ(.5*float64(dof), .5*distance)
}
const sigLevel = .05
func main() {
for _, dset := range [][]int{
{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461},
} {
utest(dset)
}
}
func utest(dset []int) {
fmt.Println("Uniform distribution test")
var sum int
for _, c := range dset {
sum += c
}
fmt.Println(" dataset:", dset)
fmt.Println(" samples: ", sum)
fmt.Println(" categories: ", len(dset))
dof := len(dset) - 1
fmt.Println(" degrees of freedom: ", dof)
dist := chi2ud(dset)
fmt.Println(" chi square test statistic: ", dist)
p := chi2p(dof, dist)
fmt.Println(" p-value of test statistic: ", p)
sig := p < sigLevel
fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig)
fmt.Println(" uniform? ", !sig, "\n")
}
| #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
typedef double (* Ifctn)( double t);
double Simpson3_8( Ifctn f, double a, double b, int N)
{
int j;
double l1;
double h = (b-a)/N;
double h1 = h/3.0;
double sum = f(a) + f(b);
for (j=3*N-1; j>0; j--) {
l1 = (j%3)? 3.0 : 2.0;
sum += l1*f(a+h1*j) ;
}
return h*sum/8.0;
}
#define A 12
double Gamma_Spouge( double z )
{
int k;
static double cspace[A];
static double *coefs = NULL;
double accum;
double a = A;
if (!coefs) {
double k1_factrl = 1.0;
coefs = cspace;
coefs[0] = sqrt(2.0*M_PI);
for(k=1; k<A; k++) {
coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;
k1_factrl *= -k;
}
}
accum = coefs[0];
for (k=1; k<A; k++) {
accum += coefs[k]/(z+k);
}
accum *= exp(-(z+a)) * pow(z+a, z+0.5);
return accum/z;
}
double aa1;
double f0( double t)
{
return pow(t, aa1)*exp(-t);
}
double GammaIncomplete_Q( double a, double x)
{
double y, h = 1.5e-2;
y = aa1 = a-1;
while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4;
if (y>x) y=x;
return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"math"
)
type ifctn func(float64) float64
func simpson38(f ifctn, a, b float64, n int) float64 {
h := (b - a) / float64(n)
h1 := h / 3
sum := f(a) + f(b)
for j := 3*n - 1; j > 0; j-- {
if j%3 == 0 {
sum += 2 * f(a+h1*float64(j))
} else {
sum += 3 * f(a+h1*float64(j))
}
}
return h * sum / 8
}
func gammaIncQ(a, x float64) float64 {
aa1 := a - 1
var f ifctn = func(t float64) float64 {
return math.Pow(t, aa1) * math.Exp(-t)
}
y := aa1
h := 1.5e-2
for f(y)*(x-y) > 2e-8 && y < x {
y += .4
}
if y > x {
y = x
}
return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))
}
func chi2ud(ds []int) float64 {
var sum, expected float64
for _, d := range ds {
expected += float64(d)
}
expected /= float64(len(ds))
for _, d := range ds {
x := float64(d) - expected
sum += x * x
}
return sum / expected
}
func chi2p(dof int, distance float64) float64 {
return gammaIncQ(.5*float64(dof), .5*distance)
}
const sigLevel = .05
func main() {
for _, dset := range [][]int{
{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461},
} {
utest(dset)
}
}
func utest(dset []int) {
fmt.Println("Uniform distribution test")
var sum int
for _, c := range dset {
sum += c
}
fmt.Println(" dataset:", dset)
fmt.Println(" samples: ", sum)
fmt.Println(" categories: ", len(dset))
dof := len(dset) - 1
fmt.Println(" degrees of freedom: ", dof)
dist := chi2ud(dset)
fmt.Println(" chi square test statistic: ", dist)
p := chi2p(dof, dist)
fmt.Println(" p-value of test statistic: ", p)
sig := p < sigLevel
fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig)
fmt.Println(" uniform? ", !sig, "\n")
}
| #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
typedef double (* Ifctn)( double t);
double Simpson3_8( Ifctn f, double a, double b, int N)
{
int j;
double l1;
double h = (b-a)/N;
double h1 = h/3.0;
double sum = f(a) + f(b);
for (j=3*N-1; j>0; j--) {
l1 = (j%3)? 3.0 : 2.0;
sum += l1*f(a+h1*j) ;
}
return h*sum/8.0;
}
#define A 12
double Gamma_Spouge( double z )
{
int k;
static double cspace[A];
static double *coefs = NULL;
double accum;
double a = A;
if (!coefs) {
double k1_factrl = 1.0;
coefs = cspace;
coefs[0] = sqrt(2.0*M_PI);
for(k=1; k<A; k++) {
coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;
k1_factrl *= -k;
}
}
accum = coefs[0];
for (k=1; k<A; k++) {
accum += coefs[k]/(z+k);
}
accum *= exp(-(z+a)) * pow(z+a, z+0.5);
return accum/z;
}
double aa1;
double f0( double t)
{
return pow(t, aa1)*exp(-t);
}
double GammaIncomplete_Q( double a, double x)
{
double y, h = 1.5e-2;
y = aa1 = a-1;
while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4;
if (y>x) y=x;
return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"strings"
)
var data = `
FILE FILE DEPENDENCIES
==== =================
top1 des1 ip1 ip2
top2 des1 ip2 ip3
ip1 extra1 ip1a ipcommon
ip2 ip2a ip2b ip2c ipcommon
des1 des1a des1b des1c
des1a des1a1 des1a2
des1c des1c1 extra1`
func main() {
g, dep, err := parseLibDep(data)
if err != nil {
fmt.Println(err)
return
}
var tops []string
for n := range g {
if !dep[n] {
tops = append(tops, n)
}
}
fmt.Println("Top levels:", tops)
showOrder(g, "top1")
showOrder(g, "top2")
showOrder(g, "top1", "top2")
fmt.Println("Cycle examples:")
g, _, err = parseLibDep(data + `
des1a1 des1`)
if err != nil {
fmt.Println(err)
return
}
showOrder(g, "top1")
showOrder(g, "ip1", "ip2")
}
func showOrder(g graph, target ...string) {
order, cyclic := g.orderFrom(target...)
if cyclic == nil {
reverse(order)
fmt.Println("Target", target, "order:", order)
} else {
fmt.Println("Target", target, "cyclic dependencies:", cyclic)
}
}
func reverse(s []string) {
last := len(s) - 1
for i, e := range s[:len(s)/2] {
s[i], s[last-i] = s[last-i], e
}
}
type graph map[string][]string
type depList map[string]bool
func parseLibDep(data string) (g graph, d depList, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
d = depList{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
var deps []string
for _, dep := range libs[1:] {
g[dep] = g[dep]
if dep == lib {
continue
}
for i := 0; ; i++ {
if i == len(deps) {
deps = append(deps, dep)
d[dep] = true
break
}
if dep == deps[i] {
break
}
}
}
g[lib] = deps
}
return g, d, nil
}
func (g graph) orderFrom(start ...string) (order, cyclic []string) {
L := make([]string, len(g))
i := len(L)
temp := map[string]bool{}
perm := map[string]bool{}
var cycleFound bool
var cycleStart string
var visit func(string)
visit = func(n string) {
switch {
case temp[n]:
cycleFound = true
cycleStart = n
return
case perm[n]:
return
}
temp[n] = true
for _, m := range g[n] {
visit(m)
if cycleFound {
if cycleStart > "" {
cyclic = append(cyclic, n)
if n == cycleStart {
cycleStart = ""
}
}
return
}
}
delete(temp, n)
perm[n] = true
i--
L[i] = n
}
for _, n := range start {
if perm[n] {
continue
}
visit(n)
if cycleFound {
return nil, cyclic
}
}
return L[i:], nil
}
| char input[] = "top1 des1 ip1 ip2\n"
"top2 des1 ip2 ip3\n"
"ip1 extra1 ip1a ipcommon\n"
"ip2 ip2a ip2b ip2c ipcommon\n"
"des1 des1a des1b des1c\n"
"des1a des1a1 des1a2\n"
"des1c des1c1 extra1\n";
...
int find_name(item base, int len, const char *name)
{
int i;
for (i = 0; i < len; i++)
if (!strcmp(base[i].name, name)) return i;
return -1;
}
int depends_on(item base, int n1, int n2)
{
int i;
if (n1 == n2) return 1;
for (i = 0; i < base[n1].n_deps; i++)
if (depends_on(base, base[n1].deps[i], n2)) return 1;
return 0;
}
void compile_order(item base, int n_items, int *top, int n_top)
{
int i, j, lvl;
int d = 0;
printf("Compile order for:");
for (i = 0; i < n_top; i++) {
printf(" %s", base[top[i]].name);
if (base[top[i]].depth > d)
d = base[top[i]].depth;
}
printf("\n");
for (lvl = 1; lvl <= d; lvl ++) {
printf("level %d:", lvl);
for (i = 0; i < n_items; i++) {
if (base[i].depth != lvl) continue;
for (j = 0; j < n_top; j++) {
if (depends_on(base, top[j], i)) {
printf(" %s", base[i].name);
break;
}
}
}
printf("\n");
}
printf("\n");
}
int main()
{
int i, n, bad = -1;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
int top[3];
top[0] = find_name(items, n, "top1");
top[1] = find_name(items, n, "top2");
top[2] = find_name(items, n, "ip1");
compile_order(items, n, top, 1);
compile_order(items, n, top + 1, 1);
compile_order(items, n, top, 2);
compile_order(items, n, top + 2, 1);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"strings"
)
var data = `
FILE FILE DEPENDENCIES
==== =================
top1 des1 ip1 ip2
top2 des1 ip2 ip3
ip1 extra1 ip1a ipcommon
ip2 ip2a ip2b ip2c ipcommon
des1 des1a des1b des1c
des1a des1a1 des1a2
des1c des1c1 extra1`
func main() {
g, dep, err := parseLibDep(data)
if err != nil {
fmt.Println(err)
return
}
var tops []string
for n := range g {
if !dep[n] {
tops = append(tops, n)
}
}
fmt.Println("Top levels:", tops)
showOrder(g, "top1")
showOrder(g, "top2")
showOrder(g, "top1", "top2")
fmt.Println("Cycle examples:")
g, _, err = parseLibDep(data + `
des1a1 des1`)
if err != nil {
fmt.Println(err)
return
}
showOrder(g, "top1")
showOrder(g, "ip1", "ip2")
}
func showOrder(g graph, target ...string) {
order, cyclic := g.orderFrom(target...)
if cyclic == nil {
reverse(order)
fmt.Println("Target", target, "order:", order)
} else {
fmt.Println("Target", target, "cyclic dependencies:", cyclic)
}
}
func reverse(s []string) {
last := len(s) - 1
for i, e := range s[:len(s)/2] {
s[i], s[last-i] = s[last-i], e
}
}
type graph map[string][]string
type depList map[string]bool
func parseLibDep(data string) (g graph, d depList, err error) {
lines := strings.Split(data, "\n")
if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
return nil, nil, fmt.Errorf("data format")
}
lines = lines[3:]
g = graph{}
d = depList{}
for _, line := range lines {
libs := strings.Fields(line)
if len(libs) == 0 {
continue
}
lib := libs[0]
var deps []string
for _, dep := range libs[1:] {
g[dep] = g[dep]
if dep == lib {
continue
}
for i := 0; ; i++ {
if i == len(deps) {
deps = append(deps, dep)
d[dep] = true
break
}
if dep == deps[i] {
break
}
}
}
g[lib] = deps
}
return g, d, nil
}
func (g graph) orderFrom(start ...string) (order, cyclic []string) {
L := make([]string, len(g))
i := len(L)
temp := map[string]bool{}
perm := map[string]bool{}
var cycleFound bool
var cycleStart string
var visit func(string)
visit = func(n string) {
switch {
case temp[n]:
cycleFound = true
cycleStart = n
return
case perm[n]:
return
}
temp[n] = true
for _, m := range g[n] {
visit(m)
if cycleFound {
if cycleStart > "" {
cyclic = append(cyclic, n)
if n == cycleStart {
cycleStart = ""
}
}
return
}
}
delete(temp, n)
perm[n] = true
i--
L[i] = n
}
for _, n := range start {
if perm[n] {
continue
}
visit(n)
if cycleFound {
return nil, cyclic
}
}
return L[i:], nil
}
| char input[] = "top1 des1 ip1 ip2\n"
"top2 des1 ip2 ip3\n"
"ip1 extra1 ip1a ipcommon\n"
"ip2 ip2a ip2b ip2c ipcommon\n"
"des1 des1a des1b des1c\n"
"des1a des1a1 des1a2\n"
"des1c des1c1 extra1\n";
...
int find_name(item base, int len, const char *name)
{
int i;
for (i = 0; i < len; i++)
if (!strcmp(base[i].name, name)) return i;
return -1;
}
int depends_on(item base, int n1, int n2)
{
int i;
if (n1 == n2) return 1;
for (i = 0; i < base[n1].n_deps; i++)
if (depends_on(base, base[n1].deps[i], n2)) return 1;
return 0;
}
void compile_order(item base, int n_items, int *top, int n_top)
{
int i, j, lvl;
int d = 0;
printf("Compile order for:");
for (i = 0; i < n_top; i++) {
printf(" %s", base[top[i]].name);
if (base[top[i]].depth > d)
d = base[top[i]].depth;
}
printf("\n");
for (lvl = 1; lvl <= d; lvl ++) {
printf("level %d:", lvl);
for (i = 0; i < n_items; i++) {
if (base[i].depth != lvl) continue;
for (j = 0; j < n_top; j++) {
if (depends_on(base, top[j], i)) {
printf(" %s", base[i].name);
break;
}
}
}
printf("\n");
}
printf("\n");
}
int main()
{
int i, n, bad = -1;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
int top[3];
top[0] = find_name(items, n, "top1");
top[1] = find_name(items, n, "top2");
top[2] = find_name(items, n, "ip1");
compile_order(items, n, top, 1);
compile_order(items, n, top + 1, 1);
compile_order(items, n, top, 2);
compile_order(items, n, top + 2, 1);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package expand
type Expander interface {
Expand() []string
}
type Text string
func (t Text) Expand() []string { return []string{string(t)} }
type Alternation []Expander
func (alt Alternation) Expand() []string {
var out []string
for _, e := range alt {
out = append(out, e.Expand()...)
}
return out
}
type Sequence []Expander
func (seq Sequence) Expand() []string {
if len(seq) == 0 {
return nil
}
out := seq[0].Expand()
for _, e := range seq[1:] {
out = combine(out, e.Expand())
}
return out
}
func combine(al, bl []string) []string {
out := make([]string, 0, len(al)*len(bl))
for _, a := range al {
for _, b := range bl {
out = append(out, a+b)
}
}
return out
}
const (
escape = '\\'
altStart = '{'
altEnd = '}'
altSep = ','
)
type piT struct{ pos, cnt, depth int }
type Brace string
func Expand(s string) []string { return Brace(s).Expand() }
func (b Brace) Expand() []string { return b.Expander().Expand() }
func (b Brace) Expander() Expander {
s := string(b)
var posInfo []piT
var stack []int
removePosInfo := func(i int) {
end := len(posInfo) - 1
copy(posInfo[i:end], posInfo[i+1:])
posInfo = posInfo[:end]
}
inEscape := false
for i, r := range s {
if inEscape {
inEscape = false
continue
}
switch r {
case escape:
inEscape = true
case altStart:
stack = append(stack, len(posInfo))
posInfo = append(posInfo, piT{i, 0, len(stack)})
case altEnd:
if len(stack) == 0 {
continue
}
si := len(stack) - 1
pi := stack[si]
if posInfo[pi].cnt == 0 {
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == len(stack) {
removePosInfo(pi)
} else {
pi++
}
}
} else {
posInfo = append(posInfo, piT{i, -2, len(stack)})
}
stack = stack[:si]
case altSep:
if len(stack) == 0 {
continue
}
posInfo = append(posInfo, piT{i, -1, len(stack)})
posInfo[stack[len(stack)-1]].cnt++
}
}
for len(stack) > 0 {
si := len(stack) - 1
pi := stack[si]
depth := posInfo[pi].depth
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == depth {
removePosInfo(pi)
} else {
pi++
}
}
stack = stack[:si]
}
return buildExp(s, 0, posInfo)
}
func buildExp(s string, off int, info []piT) Expander {
if len(info) == 0 {
return Text(s)
}
var seq Sequence
i := 0
var dj, j, depth int
for dk, piK := range info {
k := piK.pos - off
switch s[k] {
case altStart:
if depth == 0 {
dj = dk
j = k
depth = piK.depth
}
case altEnd:
if piK.depth != depth {
continue
}
if j > i {
seq = append(seq, Text(s[i:j]))
}
alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])
seq = append(seq, alt)
i = k + 1
depth = 0
}
}
if j := len(s); j > i {
seq = append(seq, Text(s[i:j]))
}
if len(seq) == 1 {
return seq[0]
}
return seq
}
func buildAlt(s string, depth, off int, info []piT) Alternation {
var alt Alternation
i := 0
var di int
for dk, piK := range info {
if piK.depth != depth {
continue
}
if k := piK.pos - off; s[k] == altSep {
sub := buildExp(s[i:k], i+off, info[di:dk])
alt = append(alt, sub)
i = k + 1
di = dk + 1
}
}
sub := buildExp(s[i:], i+off, info[di:])
alt = append(alt, sub)
return alt
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 128
typedef unsigned char character;
typedef character *string;
typedef struct node_t node;
struct node_t {
enum tag_t {
NODE_LEAF,
NODE_TREE,
NODE_SEQ,
} tag;
union {
string str;
node *root;
} data;
node *next;
};
node *allocate_node(enum tag_t tag) {
node *n = malloc(sizeof(node));
if (n == NULL) {
fprintf(stderr, "Failed to allocate node for tag: %d\n", tag);
exit(1);
}
n->tag = tag;
n->next = NULL;
return n;
}
node *make_leaf(string str) {
node *n = allocate_node(NODE_LEAF);
n->data.str = str;
return n;
}
node *make_tree() {
node *n = allocate_node(NODE_TREE);
n->data.root = NULL;
return n;
}
node *make_seq() {
node *n = allocate_node(NODE_SEQ);
n->data.root = NULL;
return n;
}
void deallocate_node(node *n) {
if (n == NULL) {
return;
}
deallocate_node(n->next);
n->next = NULL;
if (n->tag == NODE_LEAF) {
free(n->data.str);
n->data.str = NULL;
} else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {
deallocate_node(n->data.root);
n->data.root = NULL;
} else {
fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag);
exit(1);
}
free(n);
}
void append(node *root, node *elem) {
if (root == NULL) {
fprintf(stderr, "Cannot append to uninitialized node.");
exit(1);
}
if (elem == NULL) {
return;
}
if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {
if (root->data.root == NULL) {
root->data.root = elem;
} else {
node *it = root->data.root;
while (it->next != NULL) {
it = it->next;
}
it->next = elem;
}
} else {
fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag);
exit(1);
}
}
size_t count(node *n) {
if (n == NULL) {
return 0;
}
if (n->tag == NODE_LEAF) {
return 1;
}
if (n->tag == NODE_TREE) {
size_t sum = 0;
node *it = n->data.root;
while (it != NULL) {
sum += count(it);
it = it->next;
}
return sum;
}
if (n->tag == NODE_SEQ) {
size_t prod = 1;
node *it = n->data.root;
while (it != NULL) {
prod *= count(it);
it = it->next;
}
return prod;
}
fprintf(stderr, "Cannot count node with tag: %d\n", n->tag);
exit(1);
}
void expand(node *n, size_t pos) {
if (n == NULL) {
return;
}
if (n->tag == NODE_LEAF) {
printf(n->data.str);
} else if (n->tag == NODE_TREE) {
node *it = n->data.root;
while (true) {
size_t cnt = count(it);
if (pos < cnt) {
expand(it, pos);
break;
}
pos -= cnt;
it = it->next;
}
} else if (n->tag == NODE_SEQ) {
size_t prod = pos;
node *it = n->data.root;
while (it != NULL) {
size_t cnt = count(it);
size_t rem = prod % cnt;
expand(it, rem);
it = it->next;
}
} else {
fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag);
exit(1);
}
}
string allocate_string(string src) {
size_t len = strlen(src);
string out = calloc(len + 1, sizeof(character));
if (out == NULL) {
fprintf(stderr, "Failed to allocate a copy of the string.");
exit(1);
}
strcpy(out, src);
return out;
}
node *parse_seq(string input, size_t *pos);
node *parse_tree(string input, size_t *pos) {
node *root = make_tree();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
size_t depth = 0;
bool asSeq = false;
bool allow = false;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = '\\';
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
asSeq = true;
depth++;
} else if (c == '}') {
if (depth-- > 0) {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
} else {
append(root, make_leaf(allocate_string(buffer)));
}
break;
}
} else if (c == ',') {
if (depth == 0) {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
bufpos = 0;
buffer[bufpos] = 0;
asSeq = false;
} else {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
return root;
}
node *parse_seq(string input, size_t *pos) {
node *root = make_seq();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
node *tree = parse_tree(input, pos);
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
append(root, tree);
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
return root;
}
void test(string input) {
size_t pos = 0;
node *n = parse_seq(input, &pos);
size_t cnt = count(n);
size_t i;
printf("Pattern: %s\n", input);
for (i = 0; i < cnt; i++) {
expand(n, i);
printf("\n");
}
printf("\n");
deallocate_node(n);
}
int main() {
test("~/{Downloads,Pictures}/*.{jpg,gif,png}");
test("It{{em,alic}iz,erat}e{d,}, please.");
test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!");
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
|
f();
g(1, 2, 3);
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
}
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
h(1, 2, 3, 4, "abcd", (void*)0);
struct v_args {
int arg1;
int arg2;
char _sentinel;
};
void _v(struct v_args args)
{
printf("%d, %d\n", args.arg1, args.arg2);
}
#define v(...) _v((struct v_args){__VA_ARGS__})
v(.arg2 = 5, .arg1 = 17);
v(.arg2=1);
v();
printf("%p", f);
double a = asin(1);
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
|
f();
g(1, 2, 3);
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
}
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
h(1, 2, 3, 4, "abcd", (void*)0);
struct v_args {
int arg1;
int arg2;
char _sentinel;
};
void _v(struct v_args args)
{
printf("%d, %d\n", args.arg1, args.arg2);
}
#define v(...) _v((struct v_args){__VA_ARGS__})
v(.arg2 = 5, .arg1 = 17);
v(.arg2=1);
v();
printf("%p", f);
double a = asin(1);
|
Translate this program into C but keep the logic exactly as in Go. | import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
|
f();
g(1, 2, 3);
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
}
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
h(1, 2, 3, 4, "abcd", (void*)0);
struct v_args {
int arg1;
int arg2;
char _sentinel;
};
void _v(struct v_args args)
{
printf("%d, %d\n", args.arg1, args.arg2);
}
#define v(...) _v((struct v_args){__VA_ARGS__})
v(.arg2 = 5, .arg1 = 17);
v(.arg2=1);
v();
printf("%p", f);
double a = asin(1);
|
Write the same code in C as shown below in Go. | package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
)
func factSum(n int) int {
s := 0
for x, f := 0, 1; x < n; {
x++
f *= x
s += f
}
return s
}
func r(n int) bool {
if n == 0 {
return false
}
c := super[pos-n]
cnt[n]--
if cnt[n] == 0 {
cnt[n] = n
if !r(n - 1) {
return false
}
}
super[pos] = c
pos++
return true
}
func superperm(n int) {
pos = n
le := factSum(n)
super = make([]byte, le)
for i := 0; i <= n; i++ {
cnt[i] = i
}
for i := 1; i <= n; i++ {
super[i-1] = byte(i) + '0'
}
for r(n) {
}
}
func main() {
for n := 0; n < max; n++ {
fmt.Printf("superperm(%2d) ", n)
superperm(n)
fmt.Printf("len = %d\n", len(super))
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 12
char *super = 0;
int pos, cnt[MAX];
int fact_sum(int n)
{
int s, x, f;
for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);
return s;
}
int r(int n)
{
if (!n) return 0;
char c = super[pos - n];
if (!--cnt[n]) {
cnt[n] = n;
if (!r(n-1)) return 0;
}
super[pos++] = c;
return 1;
}
void superperm(int n)
{
int i, len;
pos = n;
len = fact_sum(n);
super = realloc(super, len + 1);
super[len] = '\0';
for (i = 0; i <= n; i++) cnt[i] = i;
for (i = 1; i <= n; i++) super[i - 1] = i + '0';
while (r(n));
}
int main(void)
{
int n;
for (n = 0; n < MAX; n++) {
printf("superperm(%2d) ", n);
superperm(n);
printf("len = %d", (int)strlen(super));
putchar('\n');
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.