Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Maintain the same structure and functionality when rewriting this code in C. | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
|
#include <stdio.h>
#include <math.h>
void pascal(int a, int b, int mid, int top, int* x, int* y, int* z)
{
double ytemp = (top - 4 * (a + b)) / 7.;
if(fmod(ytemp, 1.) >= 0.0001)
{
x = 0;
return;
}
*y = ytemp;
*x = mid - 2 * a - *y;
*z = *y - *x;
}
int main()
{
int a = 11, b = 4, mid = 40, top = 151;
int x, y, z;
pascal(a, b, mid, top, &x, &y, &z);
if(x != 0)
printf("x: %d, y: %d, z: %d\n", x, y, z);
else printf("No solution\n");
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
|
#include <stdio.h>
#include <math.h>
void pascal(int a, int b, int mid, int top, int* x, int* y, int* z)
{
double ytemp = (top - 4 * (a + b)) / 7.;
if(fmod(ytemp, 1.) >= 0.0001)
{
x = 0;
return;
}
*y = ytemp;
*x = mid - 2 * a - *y;
*z = *y - *x;
}
int main()
{
int a = 11, b = 4, mid = 40, top = 151;
int x, y, z;
pascal(a, b, mid, top, &x, &y, &z);
if(x != 0)
printf("x: %d, y: %d, z: %d\n", x, y, z);
else printf("No solution\n");
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"math/big"
)
var (
zero = new(big.Int)
prod = new(big.Int)
fact = new(big.Int)
)
func ccFactors(n, m uint64) (*big.Int, bool) {
prod.SetUint64(6*m + 1)
if !prod.ProbablyPrime(0) {
return zero, false
}
fact.SetUint64(12*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
for i := uint64(1); i <= n-2; i++ {
fact.SetUint64((1<<i)*9*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
}
return prod, true
}
func ccNumbers(start, end uint64) {
for n := start; n <= end; n++ {
m := uint64(1)
if n > 4 {
m = 1 << (n - 4)
}
for {
num, ok := ccFactors(n, m)
if ok {
fmt.Printf("a(%d) = %d\n", n, num)
break
}
if n <= 4 {
m++
} else {
m += 1 << (n - 4)
}
}
}
}
func main() {
ccNumbers(3, 9)
}
| #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
typedef unsigned long long int u64;
#define TRUE 1
#define FALSE 0
int primality_pretest(u64 k) {
if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23);
return TRUE;
}
int probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
int is_chernick(int n, u64 m, mpz_t z) {
u64 t = 9 * m;
if (primality_pretest(6 * m + 1) == FALSE) return FALSE;
if (primality_pretest(12 * m + 1) == FALSE) return FALSE;
for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE;
if (probprime(6 * m + 1, z) == FALSE) return FALSE;
if (probprime(12 * m + 1, z) == FALSE) return FALSE;
for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE;
return TRUE;
}
int main(int argc, char const *argv[]) {
mpz_t z;
mpz_inits(z, NULL);
for (int n = 3; n <= 10; n ++) {
u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;
if (n > 5) multiplier *= 5;
for (u64 k = 1; ; k++) {
u64 m = k * multiplier;
if (is_chernick(n, m, z) == TRUE) {
printf("a(%d) has m = %llu\n", n, m);
break;
}
}
}
return 0;
}
|
Convert this Go block to C, preserving its control flow and logic. | package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
const double EPS = 0.001;
const double EPS_SQUARE = 0.000001;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = min(x1, min(x2, x3)) - EPS;
double xMax = max(x1, max(x2, x3)) + EPS;
double yMin = min(y1, min(y2, y3)) - EPS;
double yMax = max(y1, max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
printf("(%f, %f)", x, y);
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
printf("Triangle is [");
printPoint(x1, y1);
printf(", ");
printPoint(x2, y2);
printf(", ");
printPoint(x3, y3);
printf("] \n");
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
printf("Point ");
printPoint(x, y);
printf(" is within triangle? ");
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
printf("true\n");
} else {
printf("false\n");
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
printf("\n");
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
printf("\n");
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
printf("\n");
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
const double EPS = 0.001;
const double EPS_SQUARE = 0.000001;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = min(x1, min(x2, x3)) - EPS;
double xMax = max(x1, max(x2, x3)) + EPS;
double yMin = min(y1, min(y2, y3)) - EPS;
double yMax = max(y1, max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
printf("(%f, %f)", x, y);
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
printf("Triangle is [");
printPoint(x1, y1);
printf(", ");
printPoint(x2, y2);
printf(", ");
printPoint(x3, y3);
printf("] \n");
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
printf("Point ");
printPoint(x, y);
printf(" is within triangle? ");
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
printf("true\n");
} else {
printf("false\n");
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
printf("\n");
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
printf("\n");
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
printf("\n");
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
| #include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
int main() {
const unsigned int limit = 100;
unsigned int n;
printf("Count of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%3d", divisor_count(n));
if (n % 20 == 0) {
printf("\n");
}
}
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
| #include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
int main() {
const unsigned int limit = 100;
unsigned int n;
printf("Count of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%3d", divisor_count(n));
if (n % 20 == 0) {
printf("\n");
}
}
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import(
"fmt"
"unsafe"
"reflect"
)
func pointer() {
fmt.Printf("Pointer:\n")
var i int
p := &i
fmt.Printf("Before:\n\t%v: %v, %v\n", p, *p, i)
*p = 3
fmt.Printf("After:\n\t%v: %v, %v\n", p, *p, i)
}
func slice() {
fmt.Printf("Slice:\n")
var a [10]byte
var h reflect.SliceHeader
h.Data = uintptr(unsafe.Pointer(&a))
h.Len = len(a)
h.Cap = len(a)
s := *(*[]byte)(unsafe.Pointer(&h))
fmt.Printf("Before:\n\ts: %v\n\ta: %v\n", s, a)
copy(s, "A string.")
fmt.Printf("After:\n\ts: %v\n\ta: %v\n", s, a)
}
func main() {
pointer()
fmt.Println()
slice()
}
| #include <stdio.h>
int main()
{
int intspace;
int *address;
address = &intspace;
*address = 65535;
printf("%p: %08x (=%08x)\n", address, *address, intspace);
*((char*)address) = 0x00;
*((char*)address+1) = 0x00;
*((char*)address+2) = 0xff;
*((char*)address+3) = 0xff;
printf("%p: %08x (=%08x)\n", address, *address, intspace);
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
pm := big.NewInt(1)
var px, nx int
var pb big.Int
primes(4000, func(p int64) bool {
pm.Mul(pm, pb.SetInt64(p))
px++
if pb.Add(pm, one).ProbablyPrime(0) ||
pb.Sub(pm, one).ProbablyPrime(0) {
fmt.Print(px, " ")
nx++
if nx == 20 {
fmt.Println()
return false
}
}
return true
})
}
func primes(limit int, f func(int64) bool) {
c := make([]bool, limit)
c[0] = true
c[1] = true
lm := int64(limit)
p := int64(2)
for {
f(p)
p2 := p * p
if p2 >= lm {
break
}
for i := p2; i < lm; i += p {
c[i] = true
}
for {
p++
if !c[p] {
break
}
}
}
for p++; p < lm; p++ {
if !c[p] && !f(p) {
break
}
}
}
| #include <gmp.h>
int main(void)
{
mpz_t p, s;
mpz_init_set_ui(p, 1);
mpz_init_set_ui(s, 1);
for (int n = 1, i = 0; i < 20; n++) {
mpz_nextprime(s, s);
mpz_mul(p, p, s);
mpz_add_ui(p, p, 1);
if (mpz_probab_prime_p(p, 25)) {
mpz_sub_ui(p, p, 1);
gmp_printf("%d\n", n);
i++;
continue;
}
mpz_sub_ui(p, p, 2);
if (mpz_probab_prime_p(p, 25)) {
mpz_add_ui(p, p, 1);
gmp_printf("%d\n", n);
i++;
continue;
}
mpz_add_ui(p, p, 1);
}
mpz_clear(s);
mpz_clear(p);
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct genome{
char* strand;
int length;
struct genome* next;
}genome;
genome* genomeData;
int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;
int numDigits(int num){
int len = 1;
while(num>10){
num = num/10;
len++;
}
return len;
}
void buildGenome(char str[100]){
int len = strlen(str),i;
genome *genomeIterator, *newGenome;
totalLength += len;
for(i=0;i<len;i++){
switch(str[i]){
case 'A': Adenine++;
break;
case 'T': Thymine++;
break;
case 'C': Cytosine++;
break;
case 'G': Guanine++;
break;
};
}
if(genomeData==NULL){
genomeData = (genome*)malloc(sizeof(genome));
genomeData->strand = (char*)malloc(len*sizeof(char));
strcpy(genomeData->strand,str);
genomeData->length = len;
genomeData->next = NULL;
}
else{
genomeIterator = genomeData;
while(genomeIterator->next!=NULL)
genomeIterator = genomeIterator->next;
newGenome = (genome*)malloc(sizeof(genome));
newGenome->strand = (char*)malloc(len*sizeof(char));
strcpy(newGenome->strand,str);
newGenome->length = len;
newGenome->next = NULL;
genomeIterator->next = newGenome;
}
}
void printGenome(){
genome* genomeIterator = genomeData;
int width = numDigits(totalLength), len = 0;
printf("Sequence:\n");
while(genomeIterator!=NULL){
printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand);
len += genomeIterator->length;
genomeIterator = genomeIterator->next;
}
printf("\n\nBase Count\n----------\n\n");
printf("%3c%3s%*d\n",'A',":",width+1,Adenine);
printf("%3c%3s%*d\n",'T',":",width+1,Thymine);
printf("%3c%3s%*d\n",'C',":",width+1,Cytosine);
printf("%3c%3s%*d\n",'G',":",width+1,Guanine);
printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine);
free(genomeData);
}
int main(int argc,char** argv)
{
char str[100];
int counter = 0, len;
if(argc!=2){
printf("Usage : %s <Gene file name>\n",argv[0]);
return 0;
}
FILE *fp = fopen(argv[1],"r");
while(fscanf(fp,"%s",str)!=EOF)
buildGenome(str);
fclose(fp);
printGenome();
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct genome{
char* strand;
int length;
struct genome* next;
}genome;
genome* genomeData;
int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0;
int numDigits(int num){
int len = 1;
while(num>10){
num = num/10;
len++;
}
return len;
}
void buildGenome(char str[100]){
int len = strlen(str),i;
genome *genomeIterator, *newGenome;
totalLength += len;
for(i=0;i<len;i++){
switch(str[i]){
case 'A': Adenine++;
break;
case 'T': Thymine++;
break;
case 'C': Cytosine++;
break;
case 'G': Guanine++;
break;
};
}
if(genomeData==NULL){
genomeData = (genome*)malloc(sizeof(genome));
genomeData->strand = (char*)malloc(len*sizeof(char));
strcpy(genomeData->strand,str);
genomeData->length = len;
genomeData->next = NULL;
}
else{
genomeIterator = genomeData;
while(genomeIterator->next!=NULL)
genomeIterator = genomeIterator->next;
newGenome = (genome*)malloc(sizeof(genome));
newGenome->strand = (char*)malloc(len*sizeof(char));
strcpy(newGenome->strand,str);
newGenome->length = len;
newGenome->next = NULL;
genomeIterator->next = newGenome;
}
}
void printGenome(){
genome* genomeIterator = genomeData;
int width = numDigits(totalLength), len = 0;
printf("Sequence:\n");
while(genomeIterator!=NULL){
printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand);
len += genomeIterator->length;
genomeIterator = genomeIterator->next;
}
printf("\n\nBase Count\n----------\n\n");
printf("%3c%3s%*d\n",'A',":",width+1,Adenine);
printf("%3c%3s%*d\n",'T',":",width+1,Thymine);
printf("%3c%3s%*d\n",'C',":",width+1,Cytosine);
printf("%3c%3s%*d\n",'G',":",width+1,Guanine);
printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine);
free(genomeData);
}
int main(int argc,char** argv)
{
char str[100];
int counter = 0, len;
if(argc!=2){
printf("Usage : %s <Gene file name>\n",argv[0]);
return 0;
}
FILE *fp = fopen(argv[1],"r");
while(fscanf(fp,"%s",str)!=EOF)
buildGenome(str);
fclose(fp);
printGenome();
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"hash/fnv"
"log"
"math/rand"
"os"
"time"
)
var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
const hunger = 3
const think = time.Second / 100
const eat = time.Second / 100
var fmt = log.New(os.Stdout, "", 0)
var done = make(chan bool)
type fork byte
func philosopher(phName string,
dominantHand, otherHand chan fork, done chan bool) {
fmt.Println(phName, "seated")
h := fnv.New64a()
h.Write([]byte(phName))
rg := rand.New(rand.NewSource(int64(h.Sum64())))
rSleep := func(t time.Duration) {
time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))
}
for h := hunger; h > 0; h-- {
fmt.Println(phName, "hungry")
<-dominantHand
<-otherHand
fmt.Println(phName, "eating")
rSleep(eat)
dominantHand <- 'f'
otherHand <- 'f'
fmt.Println(phName, "thinking")
rSleep(think)
}
fmt.Println(phName, "satisfied")
done <- true
fmt.Println(phName, "left the table")
}
func main() {
fmt.Println("table empty")
place0 := make(chan fork, 1)
place0 <- 'f'
placeLeft := place0
for i := 1; i < len(ph); i++ {
placeRight := make(chan fork, 1)
placeRight <- 'f'
go philosopher(ph[i], placeLeft, placeRight, done)
placeLeft = placeRight
}
go philosopher(ph[0], place0, placeLeft, done)
for range ph {
<-done
}
fmt.Println("table empty")
}
| #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#define N 5
const char *names[N] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" };
pthread_mutex_t forks[N];
#define M 5
const char *topic[M] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" };
#define lock pthread_mutex_lock
#define unlock pthread_mutex_unlock
#define xy(x, y) printf("\033[%d;%dH", x, y)
#define clear_eol(x) print(x, 12, "\033[K")
void print(int y, int x, const char *fmt, ...)
{
static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;
va_list ap;
va_start(ap, fmt);
lock(&screen);
xy(y + 1, x), vprintf(fmt, ap);
xy(N + 1, 1), fflush(stdout);
unlock(&screen);
}
void eat(int id)
{
int f[2], ration, i;
f[0] = f[1] = id;
f[id & 1] = (id + 1) % N;
clear_eol(id);
print(id, 12, "..oO (forks, need forks)");
for (i = 0; i < 2; i++) {
lock(forks + f[i]);
if (!i) clear_eol(id);
print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]);
sleep(1);
}
for (i = 0, ration = 3 + rand() % 8; i < ration; i++)
print(id, 24 + i * 4, "nom"), sleep(1);
for (i = 0; i < 2; i++) unlock(forks + f[i]);
}
void think(int id)
{
int i, t;
char buf[64] = {0};
do {
clear_eol(id);
sprintf(buf, "..oO (%s)", topic[t = rand() % M]);
for (i = 0; buf[i]; i++) {
print(id, i+12, "%c", buf[i]);
if (i < 5) usleep(200000);
}
usleep(500000 + rand() % 1000000);
} while (t);
}
void* philosophize(void *a)
{
int id = *(int*)a;
print(id, 1, "%10s", names[id]);
while(1) think(id), eat(id);
}
int main()
{
int i, id[N];
pthread_t tid[N];
for (i = 0; i < N; i++)
pthread_mutex_init(forks + (id[i] = i), 0);
for (i = 0; i < N; i++)
pthread_create(tid + i, 0, philosophize, id + i);
return pthread_join(tid[0], 0);
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
| #include <stdio.h>
int main() {
int n, b, d;
unsigned long long i, j, sum, fact[12];
fact[0] = 1;
for (n = 1; n < 12; ++n) {
fact[n] = fact[n-1] * n;
}
for (b = 9; b <= 12; ++b) {
printf("The factorions for base %d are:\n", b);
for (i = 1; i < 1500000; ++i) {
sum = 0;
j = i;
while (j > 0) {
d = j % b;
sum += fact[d];
j /= b;
}
if (sum == i) printf("%llu ", i);
}
printf("\n\n");
}
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
| #include <stdio.h>
int main() {
int n, b, d;
unsigned long long i, j, sum, fact[12];
fact[0] = 1;
for (n = 1; n < 12; ++n) {
fact[n] = fact[n-1] * n;
}
for (b = 9; b <= 12; ++b) {
printf("The factorions for base %d are:\n", b);
for (i = 1; i < 1500000; ++i) {
sum = 0;
j = i;
while (j > 0) {
d = j % b;
sum += fact[d];
j /= b;
}
if (sum == i) printf("%llu ", i);
}
printf("\n\n");
}
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"github.com/maorshutman/lm"
"log"
"math"
)
const (
K = 7_800_000_000
n0 = 27
)
var y = []float64{
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,
2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,
24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,
60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,
76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,
85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,
105824, 109695, 114232, 118610, 125497, 133852, 143227,
151367, 167418, 180096, 194836, 213150, 242364, 271106,
305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054,
1174652,
}
func f(dst, p []float64) {
for i := 0; i < len(y); i++ {
t := float64(i)
dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]
}
}
func main() {
j := lm.NumJac{Func: f}
prob := lm.LMProblem{
Dim: 1,
Size: len(y),
Func: f,
Jac: j.Jac,
InitParams: []float64{0.5},
Tau: 1e-6,
Eps1: 1e-8,
Eps2: 1e-8,
}
res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})
if err != nil {
log.Fatal(err)
}
r := res.X[0]
fmt.Printf("The logistic curve r for the world data is %.8f\n", r)
fmt.Printf("R0 is then approximately equal to %.7f\n", math.Exp(12*r))
}
| #include <math.h>
#include <stdio.h>
const double K = 7.8e9;
const int n0 = 27;
const double actual[] = {
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820,
4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273,
31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103,
69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339,
80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077,
95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497,
133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364,
271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652
};
const size_t actual_size = sizeof(actual) / sizeof(double);
double f(double r) {
double sq = 0;
size_t i;
for (i = 0; i < actual_size; ++i) {
double eri = exp(r * i);
double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K);
double diff = guess - actual[i];
sq += diff * diff;
}
return sq;
}
double solve(double (*fn)(double), double guess, double epsilon) {
double delta, f0, factor;
for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2;
delta > epsilon && guess != guess - delta;
delta *= factor) {
double nf = (*fn)(guess - delta);
if (nf < f0) {
f0 = nf;
guess -= delta;
} else {
nf = fn(guess + delta);
if (nf < f0) {
f0 = nf;
guess += delta;
} else {
factor = 0.5;
}
}
}
return guess;
}
double solve_default(double (*fn)(double)) {
return solve(fn, 0.5, 0);
}
int main() {
double r = solve_default(f);
double R0 = exp(12 * r);
printf("r = %f, R0 = %f\n", r, R0);
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import "fmt"
type link struct {
int
next *link
}
func linkInts(s []int) *link {
if len(s) == 0 {
return nil
}
return &link{s[0], linkInts(s[1:])}
}
func (l *link) String() string {
if l == nil {
return "nil"
}
r := fmt.Sprintf("[%d", l.int)
for l = l.next; l != nil; l = l.next {
r = fmt.Sprintf("%s %d", r, l.int)
}
return r + "]"
}
func main() {
a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})
fmt.Println("before:", a)
b := strandSort(a)
fmt.Println("after: ", b)
}
func strandSort(a *link) (result *link) {
for a != nil {
sublist := a
a = a.next
sTail := sublist
for p, pPrev := a, a; p != nil; p = p.next {
if p.int > sTail.int {
sTail.next = p
sTail = p
if p == a {
a = p.next
} else {
pPrev.next = p.next
}
} else {
pPrev = p
}
}
sTail.next = nil
if result == nil {
result = sublist
continue
}
var m, rr *link
if sublist.int < result.int {
m = sublist
sublist = m.next
rr = result
} else {
m = result
rr = m.next
}
result = m
for {
if sublist == nil {
m.next = rr
break
}
if rr == nil {
m.next = sublist
break
}
if sublist.int < rr.int {
m.next = sublist
m = sublist
sublist = m.next
} else {
m.next = rr
m = rr
rr = m.next
}
}
}
return
}
| #include <stdio.h>
typedef struct node_t *node, node_t;
struct node_t { int v; node next; };
typedef struct { node head, tail; } slist;
void push(slist *l, node e) {
if (!l->head) l->head = e;
if (l->tail) l->tail->next = e;
l->tail = e;
}
node removehead(slist *l) {
node e = l->head;
if (e) {
l->head = e->next;
e->next = 0;
}
return e;
}
void join(slist *a, slist *b) {
push(a, b->head);
a->tail = b->tail;
}
void merge(slist *a, slist *b) {
slist r = {0};
while (a->head && b->head)
push(&r, removehead(a->head->v <= b->head->v ? a : b));
join(&r, a->head ? a : b);
*a = r;
b->head = b->tail = 0;
}
void sort(int *ar, int len)
{
node_t all[len];
for (int i = 0; i < len; i++)
all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;
slist list = {all, all + len - 1}, rem, strand = {0}, res = {0};
for (node e = 0; list.head; list = rem) {
rem.head = rem.tail = 0;
while ((e = removehead(&list)))
push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);
merge(&res, &strand);
}
for (int i = 0; res.head; i++, res.head = res.head->next)
ar[i] = res.head->v;
}
void show(const char *title, int *x, int len)
{
printf("%s ", title);
for (int i = 0; i < len; i++)
printf("%3d ", x[i]);
putchar('\n');
}
int main(void)
{
int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};
# define SIZE sizeof(x)/sizeof(int)
show("before sort:", x, SIZE);
sort(x, sizeof(x)/sizeof(int));
show("after sort: ", x, SIZE);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func main() {
fmt.Println("Additive primes less than 500:")
i := 2
count := 0
for {
if isPrime(i) && isPrime(sumDigits(i)) {
count++
fmt.Printf("%3d ", i)
if count%10 == 0 {
fmt.Println()
}
}
if i > 2 {
i += 2
} else {
i++
}
if i > 499 {
break
}
}
fmt.Printf("\n\n%d additive primes found.\n", count)
}
| #include <stdbool.h>
#include <stdio.h>
#include <string.h>
void memoizeIsPrime( bool * result, const int N )
{
result[2] = true;
result[3] = true;
int prime[N];
prime[0] = 3;
int end = 1;
for (int n = 5; n < N; n += 2)
{
bool n_is_prime = true;
for (int i = 0; i < end; ++i)
{
const int PRIME = prime[i];
if (n % PRIME == 0)
{
n_is_prime = false;
break;
}
if (PRIME * PRIME > n)
{
break;
}
}
if (n_is_prime)
{
prime[end++] = n;
result[n] = true;
}
}
}
int sumOfDecimalDigits( int n )
{
int sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
int main( void )
{
const int N = 500;
printf( "Rosetta Code: additive primes less than %d:\n", N );
bool is_prime[N];
memset( is_prime, 0, sizeof(is_prime) );
memoizeIsPrime( is_prime, N );
printf( " 2" );
int count = 1;
for (int i = 3; i < N; i += 2)
{
if (is_prime[i] && is_prime[sumOfDecimalDigits( i )])
{
printf( "%4d", i );
++count;
if ((count % 10) == 0)
{
printf( "\n" );
}
}
}
printf( "\nThose were %d additive primes.\n", count );
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
if raining {
needUmbrella = true
}
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
raining = false
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
| #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
printf("%d\n", a);
exit(0);
}
|
Write the same code in C as shown below in Go. | package main
import "fmt"
type ibool bool
const itrue ibool = true
func (ib ibool) iif(cond bool) bool {
if cond {
return bool(ib)
}
return bool(!ib)
}
func main() {
var needUmbrella bool
raining := true
if raining {
needUmbrella = true
}
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
raining = false
needUmbrella = itrue.iif(raining)
fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella)
}
| #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
printf("%d\n", a);
exit(0);
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| #include<stdlib.h>
#include<stdio.h>
long totient(long n){
long tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
long* perfectTotients(long n){
long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;
for(m=1;count<n;m++){
tot = m;
sum = 0;
while(tot != 1){
tot = totient(tot);
sum += tot;
}
if(sum == m)
ptList[count++] = m;
}
return ptList;
}
long main(long argC, char* argV[])
{
long *ptList,i,n;
if(argC!=2)
printf("Usage : %s <number of perfect Totient numbers required>",argV[0]);
else{
n = atoi(argV[1]);
ptList = perfectTotients(n);
printf("The first %d perfect Totient numbers are : \n[",n);
for(i=0;i<n;i++)
printf(" %d,",ptList[i]);
printf("\b]");
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| #include<stdlib.h>
#include<stdio.h>
long totient(long n){
long tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
long* perfectTotients(long n){
long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;
for(m=1;count<n;m++){
tot = m;
sum = 0;
while(tot != 1){
tot = totient(tot);
sum += tot;
}
if(sum == m)
ptList[count++] = m;
}
return ptList;
}
long main(long argC, char* argV[])
{
long *ptList,i,n;
if(argC!=2)
printf("Usage : %s <number of perfect Totient numbers required>",argV[0]);
else{
n = atoi(argV[1]);
ptList = perfectTotients(n);
printf("The first %d perfect Totient numbers are : \n[",n);
for(i=0;i<n;i++)
printf(" %d,",ptList[i]);
printf("\b]");
}
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import "fmt"
type Delegator struct {
delegate interface{}
}
type Thingable interface {
thing() string
}
func (self Delegator) operation() string {
if v, ok := self.delegate.(Thingable); ok {
return v.thing()
}
return "default implementation"
}
type Delegate int
func (Delegate) thing() string {
return "delegate implementation"
}
func main() {
a := Delegator{}
fmt.Println(a.operation())
a.delegate = "A delegate may be any object"
fmt.Println(a.operation())
var d Delegate
a.delegate = d
fmt.Println(a.operation())
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef const char * (*Responder)( int p1);
typedef struct sDelegate {
Responder operation;
} *Delegate;
Delegate NewDelegate( Responder rspndr )
{
Delegate dl = malloc(sizeof(struct sDelegate));
dl->operation = rspndr;
return dl;
}
const char *DelegateThing(Delegate dl, int p1)
{
return (dl->operation)? (*dl->operation)(p1) : NULL;
}
typedef struct sDelegator {
int param;
char *phrase;
Delegate delegate;
} *Delegator;
const char * defaultResponse( int p1)
{
return "default implementation";
}
static struct sDelegate defaultDel = { &defaultResponse };
Delegator NewDelegator( int p, char *phrase)
{
Delegator d = malloc(sizeof(struct sDelegator));
d->param = p;
d->phrase = phrase;
d->delegate = &defaultDel;
return d;
}
const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
const char *rtn;
if (delroy) {
rtn = DelegateThing(delroy, p1);
if (!rtn) {
rtn = DelegateThing(theDelegator->delegate, p1);
}
}
else
rtn = DelegateThing(theDelegator->delegate, p1);
printf("%s\n", theDelegator->phrase );
return rtn;
}
const char *thing1( int p1)
{
printf("We're in thing1 with value %d\n" , p1);
return "delegate implementation";
}
int main()
{
Delegate del1 = NewDelegate(&thing1);
Delegate del2 = NewDelegate(NULL);
Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, NULL));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del1));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del2));
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
| #include <stdio.h>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
unsigned int p;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
int main() {
const unsigned int limit = 100;
unsigned int n;
printf("Sum of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%4d", divisor_sum(n));
if (n % 10 == 0) {
printf("\n");
}
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
| #include <stdio.h>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
unsigned int p;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
int main() {
const unsigned int limit = 100;
unsigned int n;
printf("Sum of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%4d", divisor_sum(n));
if (n % 10 == 0) {
printf("\n");
}
}
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
| #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
size_t get_min_length(const char* str, size_t n) {
size_t len = 0;
while (len < n && isupper((unsigned char)str[len]))
++len;
return len;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = get_min_length(word, word_len);
new_cmd->cmd = uppercase(word, word_len);
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
| #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
size_t get_min_length(const char* str, size_t n) {
size_t len = 0;
while (len < n && isupper((unsigned char)str[len]))
++len;
return len;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = get_min_length(word, word_len);
new_cmd->cmd = uppercase(word, word_len);
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
func main() {
s := "immutable"
s[0] = 'a'
}
| #define PI 3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
type point struct {
x, y float32
}
var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}
var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}
func main() {
var cp1, cp2, s, e point
inside := func(p point) bool {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
}
intersection := func() (p point) {
dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y
dpx, dpy := s.x-e.x, s.y-e.y
n1 := cp1.x*cp2.y - cp1.y*cp2.x
n2 := s.x*e.y - s.y*e.x
n3 := 1 / (dcx*dpy - dcy*dpx)
p.x = (n1*dpx - n2*dcx) * n3
p.y = (n1*dpy - n2*dcy) * n3
return
}
outputList := subjectPolygon
cp1 = clipPolygon[len(clipPolygon)-1]
for _, cp2 = range clipPolygon {
inputList := outputList
outputList = nil
s = inputList[len(inputList)-1]
for _, e = range inputList {
if inside(e) {
if !inside(s) {
outputList = append(outputList, intersection())
}
outputList = append(outputList, e)
} else if inside(s) {
outputList = append(outputList, intersection())
}
s = e
}
cp1 = cp2
}
fmt.Println(outputList)
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { double x, y; } vec_t, *vec;
inline double dot(vec a, vec b)
{
return a->x * b->x + a->y * b->y;
}
inline double cross(vec a, vec b)
{
return a->x * b->y - a->y * b->x;
}
inline vec vsub(vec a, vec b, vec res)
{
res->x = a->x - b->x;
res->y = a->y - b->y;
return res;
}
int left_of(vec a, vec b, vec c)
{
vec_t tmp1, tmp2;
double x;
vsub(b, a, &tmp1);
vsub(c, b, &tmp2);
x = cross(&tmp1, &tmp2);
return x < 0 ? -1 : x > 0;
}
int line_sect(vec x0, vec x1, vec y0, vec y1, vec res)
{
vec_t dx, dy, d;
vsub(x1, x0, &dx);
vsub(y1, y0, &dy);
vsub(x0, y0, &d);
double dyx = cross(&dy, &dx);
if (!dyx) return 0;
dyx = cross(&d, &dx) / dyx;
if (dyx <= 0 || dyx >= 1) return 0;
res->x = y0->x + dyx * dy.x;
res->y = y0->y + dyx * dy.y;
return 1;
}
typedef struct { int len, alloc; vec v; } poly_t, *poly;
poly poly_new()
{
return (poly)calloc(1, sizeof(poly_t));
}
void poly_free(poly p)
{
free(p->v);
free(p);
}
void poly_append(poly p, vec v)
{
if (p->len >= p->alloc) {
p->alloc *= 2;
if (!p->alloc) p->alloc = 4;
p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);
}
p->v[p->len++] = *v;
}
int poly_winding(poly p)
{
return left_of(p->v, p->v + 1, p->v + 2);
}
void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)
{
int i, side0, side1;
vec_t tmp;
vec v0 = sub->v + sub->len - 1, v1;
res->len = 0;
side0 = left_of(x0, x1, v0);
if (side0 != -left) poly_append(res, v0);
for (i = 0; i < sub->len; i++) {
v1 = sub->v + i;
side1 = left_of(x0, x1, v1);
if (side0 + side1 == 0 && side0)
if (line_sect(x0, x1, v0, v1, &tmp))
poly_append(res, &tmp);
if (i == sub->len - 1) break;
if (side1 != -left) poly_append(res, v1);
v0 = v1;
side0 = side1;
}
}
poly poly_clip(poly sub, poly clip)
{
int i;
poly p1 = poly_new(), p2 = poly_new(), tmp;
int dir = poly_winding(clip);
poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);
for (i = 0; i < clip->len - 1; i++) {
tmp = p2; p2 = p1; p1 = tmp;
if(p1->len == 0) {
p2->len = 0;
break;
}
poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);
}
poly_free(p1);
return p2;
}
int main()
{
int i;
vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};
vec_t s[] = { {50,150}, {200,50}, {350,150},
{350,300},{250,300},{200,250},
{150,350},{100,250},{100,200}};
#define clen (sizeof(c)/sizeof(vec_t))
#define slen (sizeof(s)/sizeof(vec_t))
poly_t clipper = {clen, 0, c};
poly_t subject = {slen, 0, s};
poly res = poly_clip(&subject, &clipper);
for (i = 0; i < res->len; i++)
printf("%g %g\n", res->v[i].x, res->v[i].y);
FILE * eps = fopen("test.eps", "w");
fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n"
"/l {lineto} def /m{moveto} def /s{setrgbcolor} def"
"/c {closepath} def /gs {fill grestore stroke} def\n");
fprintf(eps, "0 setlinewidth %g %g m ", c[0].x, c[0].y);
for (i = 1; i < clen; i++)
fprintf(eps, "%g %g l ", c[i].x, c[i].y);
fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n");
fprintf(eps, "%g %g m ", s[0].x, s[0].y);
for (i = 1; i < slen; i++)
fprintf(eps, "%g %g l ", s[i].x, s[i].y);
fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n");
fprintf(eps, "2 setlinewidth [10 8] 0 setdash %g %g m ",
res->v[0].x, res->v[0].y);
for (i = 1; i < res->len; i++)
fprintf(eps, "%g %g l ", res->v[i].x, res->v[i].y);
fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n");
fprintf(eps, "%%%%EOF");
fclose(eps);
printf("test.eps written\n");
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *codes[] = {
"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA",
"AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA",
"ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB", "BBAAA",
"BBAAB", "BBBAA"
};
char *get_code(const char c) {
if (c >= 97 && c <= 122) return codes[c - 97];
return codes[26];
}
char get_char(const char *code) {
int i;
if (!strcmp(codes[26], code)) return ' ';
for (i = 0; i < 26; ++i) {
if (strcmp(codes[i], code) == 0) return 97 + i;
}
printf("\nCode \"%s\" is invalid\n", code);
exit(1);
}
void str_tolower(char s[]) {
int i;
for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}
char *bacon_encode(char plain_text[], char message[]) {
int i, count;
int plen = strlen(plain_text), mlen = strlen(message);
int elen = 5 * plen;
char c;
char *p, *et, *mt;
et = malloc(elen + 1);
str_tolower(plain_text);
for (i = 0, p = et; i < plen; ++i, p += 5) {
c = plain_text[i];
strncpy(p, get_code(c), 5);
}
*++p = '\0';
str_tolower(message);
mt = calloc(mlen + 1, 1);
for (i = 0, count = 0; i < mlen; ++i) {
c = message[i];
if (c >= 'a' && c <= 'z') {
if (et[count] == 'A')
mt[i] = c;
else
mt[i] = c - 32;
if (++count == elen) break;
}
else mt[i] = c;
}
free(et);
return mt;
}
char *bacon_decode(char cipher_text[]) {
int i, count, clen = strlen(cipher_text);
int plen;
char *p, *ct, *pt;
char c, quintet[6];
ct = calloc(clen + 1, 1);
for (i = 0, count = 0; i < clen; ++i) {
c = cipher_text[i];
if (c >= 'a' && c <= 'z')
ct[count++] = 'A';
else if (c >= 'A' && c <= 'Z')
ct[count++] = 'B';
}
plen = strlen(ct) / 5;
pt = malloc(plen + 1);
for (i = 0, p = ct; i < plen; ++i, p += 5) {
strncpy(quintet, p, 5);
quintet[5] = '\0';
pt[i] = get_char(quintet);
}
pt[plen] = '\0';
free(ct);
return pt;
}
int main() {
char plain_text[] = "the quick brown fox jumps over the lazy dog";
char message[] = "bacon's cipher is a method of steganography created by francis bacon."
"this task is to implement a program for encryption and decryption of "
"plaintext using the simple alphabet of the baconian cipher or some "
"other kind of representation of this alphabet (make anything signify anything). "
"the baconian alphabet may optionally be extended to encode all lower "
"case characters individually and/or adding a few punctuation characters "
"such as the space.";
char *cipher_text, *hidden_text;
cipher_text = bacon_encode(plain_text, message);
printf("Cipher text ->\n\n%s\n", cipher_text);
hidden_text = bacon_decode(cipher_text);
printf("\nHidden text ->\n\n%s\n", hidden_text);
free(cipher_text);
free(hidden_text);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import(
"fmt"
"strings"
)
var codes = map[rune]string {
'a' : "AAAAA", 'b' : "AAAAB", 'c' : "AAABA", 'd' : "AAABB", 'e' : "AABAA",
'f' : "AABAB", 'g' : "AABBA", 'h' : "AABBB", 'i' : "ABAAA", 'j' : "ABAAB",
'k' : "ABABA", 'l' : "ABABB", 'm' : "ABBAA", 'n' : "ABBAB", 'o' : "ABBBA",
'p' : "ABBBB", 'q' : "BAAAA", 'r' : "BAAAB", 's' : "BAABA", 't' : "BAABB",
'u' : "BABAA", 'v' : "BABAB", 'w' : "BABBA", 'x' : "BABBB", 'y' : "BBAAA",
'z' : "BBAAB", ' ' : "BBBAA",
}
func baconEncode(plainText string, message string) string {
pt := strings.ToLower(plainText)
var sb []byte
for _, c := range pt {
if c >= 'a' && c <= 'z' {
sb = append(sb, codes[c]...)
} else {
sb = append(sb, codes[' ']...)
}
}
et := string(sb)
mg := strings.ToLower(message)
sb = nil
var count = 0
for _, c := range mg {
if c >= 'a' && c <= 'z' {
if et[count] == 'A' {
sb = append(sb, byte(c))
} else {
sb = append(sb, byte(c - 32))
}
count++
if count == len(et) { break }
} else {
sb = append(sb, byte(c))
}
}
return string(sb)
}
func baconDecode(message string) string {
var sb []byte
for _, c := range message {
if c >= 'a' && c <= 'z' {
sb = append(sb, 'A')
} else if c >= 'A' && c <= 'Z' {
sb = append(sb, 'B')
}
}
et := string(sb)
sb = nil
for i := 0; i < len(et); i += 5 {
quintet := et[i : i + 5]
for k, v := range codes {
if v == quintet {
sb = append(sb, byte(k))
break
}
}
}
return string(sb)
}
func main() {
plainText := "the quick brown fox jumps over the lazy dog"
message := "bacon's cipher is a method of steganography created by francis bacon." +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipherText := baconEncode(plainText, message)
fmt.Printf("Cipher text ->\n\n%s\n", cipherText)
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *codes[] = {
"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA",
"AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA",
"ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB", "BBAAA",
"BBAAB", "BBBAA"
};
char *get_code(const char c) {
if (c >= 97 && c <= 122) return codes[c - 97];
return codes[26];
}
char get_char(const char *code) {
int i;
if (!strcmp(codes[26], code)) return ' ';
for (i = 0; i < 26; ++i) {
if (strcmp(codes[i], code) == 0) return 97 + i;
}
printf("\nCode \"%s\" is invalid\n", code);
exit(1);
}
void str_tolower(char s[]) {
int i;
for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}
char *bacon_encode(char plain_text[], char message[]) {
int i, count;
int plen = strlen(plain_text), mlen = strlen(message);
int elen = 5 * plen;
char c;
char *p, *et, *mt;
et = malloc(elen + 1);
str_tolower(plain_text);
for (i = 0, p = et; i < plen; ++i, p += 5) {
c = plain_text[i];
strncpy(p, get_code(c), 5);
}
*++p = '\0';
str_tolower(message);
mt = calloc(mlen + 1, 1);
for (i = 0, count = 0; i < mlen; ++i) {
c = message[i];
if (c >= 'a' && c <= 'z') {
if (et[count] == 'A')
mt[i] = c;
else
mt[i] = c - 32;
if (++count == elen) break;
}
else mt[i] = c;
}
free(et);
return mt;
}
char *bacon_decode(char cipher_text[]) {
int i, count, clen = strlen(cipher_text);
int plen;
char *p, *ct, *pt;
char c, quintet[6];
ct = calloc(clen + 1, 1);
for (i = 0, count = 0; i < clen; ++i) {
c = cipher_text[i];
if (c >= 'a' && c <= 'z')
ct[count++] = 'A';
else if (c >= 'A' && c <= 'Z')
ct[count++] = 'B';
}
plen = strlen(ct) / 5;
pt = malloc(plen + 1);
for (i = 0, p = ct; i < plen; ++i, p += 5) {
strncpy(quintet, p, 5);
quintet[5] = '\0';
pt[i] = get_char(quintet);
}
pt[plen] = '\0';
free(ct);
return pt;
}
int main() {
char plain_text[] = "the quick brown fox jumps over the lazy dog";
char message[] = "bacon's cipher is a method of steganography created by francis bacon."
"this task is to implement a program for encryption and decryption of "
"plaintext using the simple alphabet of the baconian cipher or some "
"other kind of representation of this alphabet (make anything signify anything). "
"the baconian alphabet may optionally be extended to encode all lower "
"case characters individually and/or adding a few punctuation characters "
"such as the space.";
char *cipher_text, *hidden_text;
cipher_text = bacon_encode(plain_text, message);
printf("Cipher text ->\n\n%s\n", cipher_text);
hidden_text = bacon_decode(cipher_text);
printf("\nHidden text ->\n\n%s\n", hidden_text);
free(cipher_text);
free(hidden_text);
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"strconv"
)
var n = 5
func main() {
if n < 1 {
return
}
top, left, bottom, right := 0, 0, n-1, n-1
sz := n * n
a := make([]int, sz)
i := 0
for left < right {
for c := left; c <= right; c++ {
a[top*n+c] = i
i++
}
top++
for r := top; r <= bottom; r++ {
a[r*n+right] = i
i++
}
right--
if top == bottom {
break
}
for c := right; c >= left; c-- {
a[bottom*n+c] = i
i++
}
bottom--
for r := bottom; r >= top; r-- {
a[r*n+left] = i
i++
}
left++
}
a[top*n+left] = i
w := len(strconv.Itoa(n*n - 1))
for i, e := range a {
fmt.Printf("%*d ", w, e)
if i%n == n-1 {
fmt.Println("")
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
int i, j, m = 0, n = 0;
if (c >= 2) m = atoi(v[1]);
if (c >= 3) n = atoi(v[2]);
if (m <= 0) m = 5;
if (n <= 0) n = m;
int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
s[0] = (int*)(s + m);
for (i = 1; i < m; i++) s[i] = s[i - 1] + n;
int dx = 1, dy = 0, val = 0, t;
for (i = j = 0; valid(i, j); i += dy, j += dx ) {
for (; valid(i, j); j += dx, i += dy)
s[i][j] = ++val;
j -= dx; i -= dy;
t = dy; dy = dx; dx = -t;
}
for (t = 2; val /= 10; t++);
for(i = 0; i < m; i++)
for(j = 0; j < n || !putchar('\n'); j++)
printf("%*d", t, s[i][j]);
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | type cell string
type spec struct {
less func(cell, cell) bool
column int
reverse bool
}
func newSpec() (s spec) {
return
}
t.sort(newSpec())
s := newSpec
s.reverse = true
t.sort(s)
| #include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef const char * String;
typedef struct sTable {
String * *rows;
int n_rows,n_cols;
} *Table;
typedef int (*CompareFctn)(String a, String b);
struct {
CompareFctn compare;
int column;
int reversed;
} sortSpec;
int CmprRows( const void *aa, const void *bb)
{
String *rA = *(String *const *)aa;
String *rB = *(String *const *)bb;
int sortCol = sortSpec.column;
String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];
String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];
return sortSpec.compare( left, right );
}
int sortTable(Table tbl, const char* argSpec,... )
{
va_list vl;
const char *p;
int c;
sortSpec.compare = &strcmp;
sortSpec.column = 0;
sortSpec.reversed = 0;
va_start(vl, argSpec);
if (argSpec)
for (p=argSpec; *p; p++) {
switch (*p) {
case 'o':
sortSpec.compare = va_arg(vl,CompareFctn);
break;
case 'c':
c = va_arg(vl,int);
if ( 0<=c && c<tbl->n_cols)
sortSpec.column = c;
break;
case 'r':
sortSpec.reversed = (0!=va_arg(vl,int));
break;
}
}
va_end(vl);
qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);
return 0;
}
void printTable( Table tbl, FILE *fout, const char *colFmts[])
{
int row, col;
for (row=0; row<tbl->n_rows; row++) {
fprintf(fout, " ");
for(col=0; col<tbl->n_cols; col++) {
fprintf(fout, colFmts[col], tbl->rows[row][col]);
}
fprintf(fout, "\n");
}
fprintf(fout, "\n");
}
int ord(char v)
{
return v-'0';
}
int cmprStrgs(String s1, String s2)
{
const char *p1 = s1;
const char *p2 = s2;
const char *mrk1, *mrk2;
while ((tolower(*p1) == tolower(*p2)) && *p1) {
p1++; p2++;
}
if (isdigit(*p1) && isdigit(*p2)) {
long v1, v2;
if ((*p1 == '0') ||(*p2 == '0')) {
while (p1 > s1) {
p1--; p2--;
if (*p1 != '0') break;
}
if (!isdigit(*p1)) {
p1++; p2++;
}
}
mrk1 = p1; mrk2 = p2;
v1 = 0;
while(isdigit(*p1)) {
v1 = 10*v1+ord(*p1);
p1++;
}
v2 = 0;
while(isdigit(*p2)) {
v2 = 10*v2+ord(*p2);
p2++;
}
if (v1 == v2)
return(p2-mrk2)-(p1-mrk1);
return v1 - v2;
}
if (tolower(*p1) != tolower(*p2))
return (tolower(*p1) - tolower(*p2));
for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);
return (*p1 -*p2);
}
int main()
{
const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"};
String r1[] = { "a101", "red", "Java" };
String r2[] = { "ab40", "gren", "Smalltalk" };
String r3[] = { "ab9", "blue", "Fortran" };
String r4[] = { "ab09", "ylow", "Python" };
String r5[] = { "ab1a", "blak", "Factor" };
String r6[] = { "ab1b", "brwn", "C Sharp" };
String r7[] = { "Ab1b", "pink", "Ruby" };
String r8[] = { "ab1", "orng", "Scheme" };
String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };
struct sTable table;
table.rows = rows;
table.n_rows = 8;
table.n_cols = 3;
sortTable(&table, "");
printf("sort on col 0, ascending\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "ro", 1, &cmprStrgs);
printf("sort on col 0, reverse.special\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "c", 1);
printf("sort on col 1, ascending\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "cr", 2, 1);
printf("sort on col 2, reverse\n");
printTable(&table, stdout, colFmts);
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | type cell string
type spec struct {
less func(cell, cell) bool
column int
reverse bool
}
func newSpec() (s spec) {
return
}
t.sort(newSpec())
s := newSpec
s.reverse = true
t.sort(s)
| #include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef const char * String;
typedef struct sTable {
String * *rows;
int n_rows,n_cols;
} *Table;
typedef int (*CompareFctn)(String a, String b);
struct {
CompareFctn compare;
int column;
int reversed;
} sortSpec;
int CmprRows( const void *aa, const void *bb)
{
String *rA = *(String *const *)aa;
String *rB = *(String *const *)bb;
int sortCol = sortSpec.column;
String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];
String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];
return sortSpec.compare( left, right );
}
int sortTable(Table tbl, const char* argSpec,... )
{
va_list vl;
const char *p;
int c;
sortSpec.compare = &strcmp;
sortSpec.column = 0;
sortSpec.reversed = 0;
va_start(vl, argSpec);
if (argSpec)
for (p=argSpec; *p; p++) {
switch (*p) {
case 'o':
sortSpec.compare = va_arg(vl,CompareFctn);
break;
case 'c':
c = va_arg(vl,int);
if ( 0<=c && c<tbl->n_cols)
sortSpec.column = c;
break;
case 'r':
sortSpec.reversed = (0!=va_arg(vl,int));
break;
}
}
va_end(vl);
qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);
return 0;
}
void printTable( Table tbl, FILE *fout, const char *colFmts[])
{
int row, col;
for (row=0; row<tbl->n_rows; row++) {
fprintf(fout, " ");
for(col=0; col<tbl->n_cols; col++) {
fprintf(fout, colFmts[col], tbl->rows[row][col]);
}
fprintf(fout, "\n");
}
fprintf(fout, "\n");
}
int ord(char v)
{
return v-'0';
}
int cmprStrgs(String s1, String s2)
{
const char *p1 = s1;
const char *p2 = s2;
const char *mrk1, *mrk2;
while ((tolower(*p1) == tolower(*p2)) && *p1) {
p1++; p2++;
}
if (isdigit(*p1) && isdigit(*p2)) {
long v1, v2;
if ((*p1 == '0') ||(*p2 == '0')) {
while (p1 > s1) {
p1--; p2--;
if (*p1 != '0') break;
}
if (!isdigit(*p1)) {
p1++; p2++;
}
}
mrk1 = p1; mrk2 = p2;
v1 = 0;
while(isdigit(*p1)) {
v1 = 10*v1+ord(*p1);
p1++;
}
v2 = 0;
while(isdigit(*p2)) {
v2 = 10*v2+ord(*p2);
p2++;
}
if (v1 == v2)
return(p2-mrk2)-(p1-mrk1);
return v1 - v2;
}
if (tolower(*p1) != tolower(*p2))
return (tolower(*p1) - tolower(*p2));
for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);
return (*p1 -*p2);
}
int main()
{
const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"};
String r1[] = { "a101", "red", "Java" };
String r2[] = { "ab40", "gren", "Smalltalk" };
String r3[] = { "ab9", "blue", "Fortran" };
String r4[] = { "ab09", "ylow", "Python" };
String r5[] = { "ab1a", "blak", "Factor" };
String r6[] = { "ab1b", "brwn", "C Sharp" };
String r7[] = { "Ab1b", "pink", "Ruby" };
String r8[] = { "ab1", "orng", "Scheme" };
String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };
struct sTable table;
table.rows = rows;
table.n_rows = 8;
table.n_cols = 3;
sortTable(&table, "");
printf("sort on col 0, ascending\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "ro", 1, &cmprStrgs);
printf("sort on col 0, reverse.special\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "c", 1);
printf("sort on col 1, ascending\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "cr", 2, 1);
printf("sort on col 2, reverse\n");
printTable(&table, stdout, colFmts);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
int k, ret = 0;
double d, dist = 0;
for_k {
d = sq2(x - site[k][0], y - site[k][1]);
if (!k || d < dist) {
dist = d, ret = k;
}
}
return ret;
}
int at_edge(int *color, int y, int x)
{
int i, j, c = color[y * size_x + x];
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = x - 1; j <= x + 1; j++) {
if (j < 0 || j >= size_x) continue;
if (color[i * size_x + j] != c) return 1;
}
}
return 0;
}
#define AA_RES 4
void aa_color(unsigned char *pix, int y, int x)
{
int i, j, n;
double r = 0, g = 0, b = 0, xx, yy;
for (i = 0; i < AA_RES; i++) {
yy = y + 1. / AA_RES * i + .5;
for (j = 0; j < AA_RES; j++) {
xx = x + 1. / AA_RES * j + .5;
n = nearest_site(xx, yy);
r += rgb[n][0];
g += rgb[n][1];
b += rgb[n][2];
}
}
pix[0] = r / (AA_RES * AA_RES);
pix[1] = g / (AA_RES * AA_RES);
pix[2] = b / (AA_RES * AA_RES);
}
#define for_i for (i = 0; i < size_y; i++)
#define for_j for (j = 0; j < size_x; j++)
void gen_map()
{
int i, j, k;
int *nearest = malloc(sizeof(int) * size_y * size_x);
unsigned char *ptr, *buf, color;
ptr = buf = malloc(3 * size_x * size_y);
for_i for_j nearest[i * size_x + j] = nearest_site(j, i);
for_i for_j {
if (!at_edge(nearest, i, j))
memcpy(ptr, rgb[nearest[i * size_x + j]], 3);
else
aa_color(ptr, i, j);
ptr += 3;
}
for (k = 0; k < N_SITES; k++) {
color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;
for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {
if (j < 0 || j >= size_x) continue;
ptr = buf + 3 * (i * size_x + j);
ptr[0] = ptr[1] = ptr[2] = color;
}
}
}
printf("P6\n%d %d\n255\n", size_x, size_y);
fflush(stdout);
fwrite(buf, size_y * size_x * 3, 1, stdout);
}
#define frand(x) (rand() / (1. + RAND_MAX) * x)
int main()
{
int k;
for_k {
site[k][0] = frand(size_x);
site[k][1] = frand(size_y);
rgb [k][0] = frand(256);
rgb [k][1] = frand(256);
rgb [k][2] = frand(256);
}
gen_map();
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math/rand"
"os"
"time"
)
const (
imageWidth = 300
imageHeight = 200
nSites = 10
)
func main() {
writePngFile(generateVoronoi(randomSites()))
}
func generateVoronoi(sx, sy []int) image.Image {
sc := make([]color.NRGBA, nSites)
for i := range sx {
sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)),
uint8(rand.Intn(256)), 255}
}
img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight))
for x := 0; x < imageWidth; x++ {
for y := 0; y < imageHeight; y++ {
dMin := dot(imageWidth, imageHeight)
var sMin int
for s := 0; s < nSites; s++ {
if d := dot(sx[s]-x, sy[s]-y); d < dMin {
sMin = s
dMin = d
}
}
img.SetNRGBA(x, y, sc[sMin])
}
}
black := image.NewUniform(color.Black)
for s := 0; s < nSites; s++ {
draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2),
black, image.ZP, draw.Src)
}
return img
}
func dot(x, y int) int {
return x*x + y*y
}
func randomSites() (sx, sy []int) {
rand.Seed(time.Now().Unix())
sx = make([]int, nSites)
sy = make([]int, nSites)
for i := range sx {
sx[i] = rand.Intn(imageWidth)
sy[i] = rand.Intn(imageHeight)
}
return
}
func writePngFile(img image.Image) {
f, err := os.Create("voronoi.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
int k, ret = 0;
double d, dist = 0;
for_k {
d = sq2(x - site[k][0], y - site[k][1]);
if (!k || d < dist) {
dist = d, ret = k;
}
}
return ret;
}
int at_edge(int *color, int y, int x)
{
int i, j, c = color[y * size_x + x];
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = x - 1; j <= x + 1; j++) {
if (j < 0 || j >= size_x) continue;
if (color[i * size_x + j] != c) return 1;
}
}
return 0;
}
#define AA_RES 4
void aa_color(unsigned char *pix, int y, int x)
{
int i, j, n;
double r = 0, g = 0, b = 0, xx, yy;
for (i = 0; i < AA_RES; i++) {
yy = y + 1. / AA_RES * i + .5;
for (j = 0; j < AA_RES; j++) {
xx = x + 1. / AA_RES * j + .5;
n = nearest_site(xx, yy);
r += rgb[n][0];
g += rgb[n][1];
b += rgb[n][2];
}
}
pix[0] = r / (AA_RES * AA_RES);
pix[1] = g / (AA_RES * AA_RES);
pix[2] = b / (AA_RES * AA_RES);
}
#define for_i for (i = 0; i < size_y; i++)
#define for_j for (j = 0; j < size_x; j++)
void gen_map()
{
int i, j, k;
int *nearest = malloc(sizeof(int) * size_y * size_x);
unsigned char *ptr, *buf, color;
ptr = buf = malloc(3 * size_x * size_y);
for_i for_j nearest[i * size_x + j] = nearest_site(j, i);
for_i for_j {
if (!at_edge(nearest, i, j))
memcpy(ptr, rgb[nearest[i * size_x + j]], 3);
else
aa_color(ptr, i, j);
ptr += 3;
}
for (k = 0; k < N_SITES; k++) {
color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;
for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {
if (j < 0 || j >= size_x) continue;
ptr = buf + 3 * (i * size_x + j);
ptr[0] = ptr[1] = ptr[2] = color;
}
}
}
printf("P6\n%d %d\n255\n", size_x, size_y);
fflush(stdout);
fwrite(buf, size_y * size_x * 3, 1, stdout);
}
#define frand(x) (rand() / (1. + RAND_MAX) * x)
int main()
{
int k;
for_k {
site[k][0] = frand(size_x);
site[k][1] = frand(size_y);
rgb [k][0] = frand(256);
rgb [k][1] = frand(256);
rgb [k][2] = frand(256);
}
gen_map();
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import "C"
import (
"fmt"
"unsafe"
)
func main() {
go1 := "hello C"
c1 := C.CString(go1)
go1 = ""
c2 := C.strdup(c1)
C.free(unsafe.Pointer(c1))
go2 := C.GoString(c2)
C.free(unsafe.Pointer(c2))
fmt.Println(go2)
}
|
#include <stdio.h>
void sayHello(char* name){
printf("Hello %s!\n", name);
}
int doubleNum(int num){
return num * 2;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import "C"
import (
"fmt"
"unsafe"
)
func main() {
go1 := "hello C"
c1 := C.CString(go1)
go1 = ""
c2 := C.strdup(c1)
C.free(unsafe.Pointer(c1))
go2 := C.GoString(c2)
C.free(unsafe.Pointer(c2))
fmt.Println(go2)
}
|
#include <stdio.h>
void sayHello(char* name){
printf("Hello %s!\n", name);
}
int doubleNum(int num){
return num * 2;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"fmt"
"math/big"
)
func bernoulli(n uint) *big.Rat {
a := make([]big.Rat, n+1)
z := new(big.Rat)
for m := range a {
a[m].SetFrac64(1, int64(m+1))
for j := m; j >= 1; j-- {
d := &a[j-1]
d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j]))
}
}
if n != 1 {
return &a[0]
}
a[0].Neg(&a[0])
return &a[0]
}
func binomial(n, k int) int64 {
if n <= 0 || k <= 0 || n < k {
return 1
}
var num, den int64 = 1, 1
for i := k + 1; i <= n; i++ {
num *= int64(i)
}
for i := 2; i <= n-k; i++ {
den *= int64(i)
}
return num / den
}
func faulhaberTriangle(p int) []big.Rat {
coeffs := make([]big.Rat, p+1)
q := big.NewRat(1, int64(p)+1)
t := new(big.Rat)
u := new(big.Rat)
sign := -1
for j := range coeffs {
sign *= -1
d := &coeffs[p-j]
t.SetInt64(int64(sign))
u.SetInt64(binomial(p+1, j))
d.Mul(q, t)
d.Mul(d, u)
d.Mul(d, bernoulli(uint(j)))
}
return coeffs
}
func main() {
for i := 0; i < 10; i++ {
coeffs := faulhaberTriangle(i)
for _, coeff := range coeffs {
fmt.Printf("%5s ", coeff.RatString())
}
fmt.Println()
}
fmt.Println()
k := 17
cc := faulhaberTriangle(k)
n := int64(1000)
nn := big.NewRat(n, 1)
np := big.NewRat(1, 1)
sum := new(big.Rat)
tmp := new(big.Rat)
for _, c := range cc {
np.Mul(np, nn)
tmp.Set(np)
tmp.Mul(tmp, &c)
sum.Add(sum, tmp)
}
fmt.Println(sum.RatString())
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int binomial(int n, int k) {
int num, denom, i;
if (n < 0 || k < 0 || n < k) return -1;
if (n == 0 || k == 0) return 1;
num = 1;
for (i = k + 1; i <= n; ++i) {
num = num * i;
}
denom = 1;
for (i = 2; i <= n - k; ++i) {
denom *= i;
}
return num / denom;
}
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
typedef struct tFrac {
int num, denom;
} Frac;
Frac makeFrac(int n, int d) {
Frac result;
int g;
if (d == 0) {
result.num = 0;
result.denom = 0;
return result;
}
if (n == 0) {
d = 1;
} else if (d < 0) {
n = -n;
d = -d;
}
g = abs(gcd(n, d));
if (g > 1) {
n = n / g;
d = d / g;
}
result.num = n;
result.denom = d;
return result;
}
Frac negateFrac(Frac f) {
return makeFrac(-f.num, f.denom);
}
Frac subFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
Frac multFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
bool equalFrac(Frac lhs, Frac rhs) {
return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);
}
bool lessFrac(Frac lhs, Frac rhs) {
return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);
}
void printFrac(Frac f) {
char buffer[7];
int len;
if (f.denom != 1) {
snprintf(buffer, 7, "%d/%d", f.num, f.denom);
} else {
snprintf(buffer, 7, "%d", f.num);
}
len = 7 - strlen(buffer);
while (len-- > 0) {
putc(' ', stdout);
}
printf(buffer);
}
Frac bernoulli(int n) {
Frac a[16];
int j, m;
if (n < 0) {
a[0].num = 0;
a[0].denom = 0;
return a[0];
}
for (m = 0; m <= n; ++m) {
a[m] = makeFrac(1, m + 1);
for (j = m; j >= 1; --j) {
a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));
}
}
if (n != 1) {
return a[0];
}
return negateFrac(a[0]);
}
void faulhaber(int p) {
Frac q, *coeffs;
int j, sign;
coeffs = malloc(sizeof(Frac)*(p + 1));
q = makeFrac(1, p + 1);
sign = -1;
for (j = 0; j <= p; ++j) {
sign = -1 * sign;
coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));
}
for (j = 0; j <= p; ++j) {
printFrac(coeffs[j]);
}
printf("\n");
free(coeffs);
}
int main() {
int i;
for (i = 0; i < 10; ++i) {
faulhaber(i);
}
return 0;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
letters := "deegklnow"
wordsAll := bytes.Split(b, []byte{'\n'})
var words [][]byte
for _, word := range wordsAll {
word = bytes.TrimSpace(word)
le := len(word)
if le > 2 && le < 10 {
words = append(words, word)
}
}
var found []string
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, 'k') >= 0 {
lets := letters
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = append(found, string(word))
}
}
}
fmt.Println("The following", len(found), "words are the solutions to the puzzle:")
fmt.Println(strings.Join(found, "\n"))
mostFound := 0
var mostWords9 []string
var mostLetters []byte
var words9 [][]byte
for _, word := range words {
if len(word) == 9 {
words9 = append(words9, word)
}
}
for _, word9 := range words9 {
letterBytes := make([]byte, len(word9))
copy(letterBytes, word9)
sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] })
distinctBytes := []byte{letterBytes[0]}
for _, b := range letterBytes[1:] {
if b != distinctBytes[len(distinctBytes)-1] {
distinctBytes = append(distinctBytes, b)
}
}
distinctLetters := string(distinctBytes)
for _, letter := range distinctLetters {
found := 0
letterByte := byte(letter)
for _, word := range words {
le := len(word)
if bytes.IndexByte(word, letterByte) >= 0 {
lets := string(letterBytes)
ok := true
for i := 0; i < le; i++ {
c := word[i]
ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c })
if ix < len(lets) && lets[ix] == c {
lets = lets[0:ix] + lets[ix+1:]
} else {
ok = false
break
}
}
if ok {
found = found + 1
}
}
}
if found > mostFound {
mostFound = found
mostWords9 = []string{string(word9)}
mostLetters = []byte{letterByte}
} else if found == mostFound {
mostWords9 = append(mostWords9, string(word9))
mostLetters = append(mostLetters, letterByte)
}
}
}
fmt.Println("\nMost words found =", mostFound)
fmt.Println("Nine letter words producing this total:")
for i := 0; i < len(mostWords9); i++ {
fmt.Println(mostWords9[i], "with central letter", string(mostLetters[i]))
}
}
| #include <stdbool.h>
#include <stdio.h>
#define MAX_WORD 80
#define LETTERS 26
bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
int index(char c) { return c - 'a'; }
void word_wheel(const char* letters, char central, int min_length, FILE* dict) {
int max_count[LETTERS] = { 0 };
for (const char* p = letters; *p; ++p) {
char c = *p;
if (is_letter(c))
++max_count[index(c)];
}
char word[MAX_WORD + 1] = { 0 };
while (fgets(word, MAX_WORD, dict)) {
int count[LETTERS] = { 0 };
for (const char* p = word; *p; ++p) {
char c = *p;
if (c == '\n') {
if (p >= word + min_length && count[index(central)] > 0)
printf("%s", word);
} else if (is_letter(c)) {
int i = index(c);
if (++count[i] > max_count[i]) {
break;
}
} else {
break;
}
}
}
}
int main(int argc, char** argv) {
const char* dict = argc == 2 ? argv[1] : "unixdict.txt";
FILE* in = fopen(dict, "r");
if (in == NULL) {
perror(dict);
return 1;
}
word_wheel("ndeokgelw", 'k', 3, in);
fclose(in);
return 0;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{7, 12, 60}
c := append(a, b...)
fmt.Println(c)
i := []interface{}{1, 2, 3}
j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
k := append(i, j...)
fmt.Println(k)
l := [...]int{1, 2, 3}
m := [...]int{7, 12, 60}
var n [len(l) + len(m)]int
copy(n[:], l[:])
copy(n[len(l):], m[:])
fmt.Println(n)
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));
void *array_concat(const void *a, size_t an,
const void *b, size_t bn, size_t s)
{
char *p = malloc(s * (an + bn));
memcpy(p, a, an*s);
memcpy(p + an*s, b, bn*s);
return p;
}
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };
int main(void)
{
unsigned int i;
int *c = ARRAY_CONCAT(int, a, 5, b, 5);
for(i = 0; i < 10; i++)
printf("%d\n", c[i]);
free(c);
return EXIT_SUCCCESS;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
}
| #include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[BUFSIZ];
puts("Enter a string: ");
fgets(str, sizeof(str), stdin);
long num;
char buf[BUFSIZ];
do
{
puts("Enter 75000: ");
fgets(buf, sizeof(buf), stdin);
num = strtol(buf, NULL, 10);
} while (num != 75000);
return EXIT_SUCCESS;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
| #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,sequence[i].key/12.0));
delay(sequence[i].key%12==0?500:1000);
i = (i+1)%8;
i==0?printf("\n"):printf("");
}
nosound();
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"encoding/binary"
"log"
"math"
"os"
"strings"
)
func main() {
const (
sampleRate = 44100
duration = 8
dataLength = sampleRate * duration
hdrSize = 44
fileLen = dataLength + hdrSize - 8
)
buf1 := make([]byte, 1)
buf2 := make([]byte, 2)
buf4 := make([]byte, 4)
var sb strings.Builder
sb.WriteString("RIFF")
binary.LittleEndian.PutUint32(buf4, fileLen)
sb.Write(buf4)
sb.WriteString("WAVE")
sb.WriteString("fmt ")
binary.LittleEndian.PutUint32(buf4, 16)
sb.Write(buf4)
binary.LittleEndian.PutUint16(buf2, 1)
sb.Write(buf2)
sb.Write(buf2)
binary.LittleEndian.PutUint32(buf4, sampleRate)
sb.Write(buf4)
sb.Write(buf4)
sb.Write(buf2)
binary.LittleEndian.PutUint16(buf2, 8)
sb.Write(buf2)
sb.WriteString("data")
binary.LittleEndian.PutUint32(buf4, dataLength)
sb.Write(buf4)
wavhdr := []byte(sb.String())
f, err := os.Create("notes.wav")
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(wavhdr)
freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3}
for j := 0; j < duration; j++ {
freq := freqs[j]
omega := 2 * math.Pi * freq
for i := 0; i < dataLength/duration; i++ {
y := 32 * math.Sin(omega*float64(i)/float64(sampleRate))
buf1[0] = byte(math.Round(y))
f.Write(buf1)
}
}
}
| #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,sequence[i].key/12.0));
delay(sequence[i].key%12==0?500:1000);
i = (i+1)%8;
i==0?printf("\n"):printf("");
}
nosound();
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
type item struct {
string
w, v int
}
var wants = []item{
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
}
const maxWt = 400
func main() {
items, w, v := m(len(wants)-1, maxWt)
fmt.Println(items)
fmt.Println("weight:", w)
fmt.Println("value:", v)
}
func m(i, w int) ([]string, int, int) {
if i < 0 || w == 0 {
return nil, 0, 0
} else if wants[i].w > w {
return m(i-1, w)
}
i0, w0, v0 := m(i-1, w)
i1, w1, v1 := m(i-1, w-wants[i].w)
v1 += wants[i].v
if v1 > v0 {
return append(i1, wants[i].string), w1 + wants[i].w, v1
}
return i0, w0, v0
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
} item_t;
item_t items[] = {
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
};
int *knapsack (item_t *items, int n, int w) {
int i, j, a, b, *mm, **m, *s;
mm = calloc((n + 1) * (w + 1), sizeof (int));
m = malloc((n + 1) * sizeof (int *));
m[0] = mm;
for (i = 1; i <= n; i++) {
m[i] = &mm[i * (w + 1)];
for (j = 0; j <= w; j++) {
if (items[i - 1].weight > j) {
m[i][j] = m[i - 1][j];
}
else {
a = m[i - 1][j];
b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;
m[i][j] = a > b ? a : b;
}
}
}
s = calloc(n, sizeof (int));
for (i = n, j = w; i > 0; i--) {
if (m[i][j] > m[i - 1][j]) {
s[i - 1] = 1;
j -= items[i - 1].weight;
}
}
free(mm);
free(m);
return s;
}
int main () {
int i, n, tw = 0, tv = 0, *s;
n = sizeof (items) / sizeof (item_t);
s = knapsack(items, n, 400);
for (i = 0; i < n; i++) {
if (s[i]) {
printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value);
tw += items[i].weight;
tv += items[i].value;
}
}
printf("%-22s %5d %5d\n", "totals:", tw, tv);
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"sort"
)
func getPrimes(max int) []int {
if max < 2 {
return []int{}
}
lprimes := []int{2}
outer:
for x := 3; x <= max; x += 2 {
for _, p := range lprimes {
if x%p == 0 {
continue outer
}
}
lprimes = append(lprimes, x)
}
return lprimes
}
func main() {
const maxSum = 99
descendants := make([][]int64, maxSum+1)
ancestors := make([][]int, maxSum+1)
for i := 0; i <= maxSum; i++ {
descendants[i] = []int64{}
ancestors[i] = []int{}
}
primes := getPrimes(maxSum)
for _, p := range primes {
descendants[p] = append(descendants[p], int64(p))
for s := 1; s < len(descendants)-p; s++ {
temp := make([]int64, len(descendants[s]))
for i := 0; i < len(descendants[s]); i++ {
temp[i] = int64(p) * descendants[s][i]
}
descendants[s+p] = append(descendants[s+p], temp...)
}
}
for _, p := range append(primes, 4) {
le := len(descendants[p])
if le == 0 {
continue
}
descendants[p][le-1] = 0
descendants[p] = descendants[p][:le-1]
}
total := 0
for s := 1; s <= maxSum; s++ {
x := descendants[s]
sort.Slice(x, func(i, j int) bool {
return x[i] < x[j]
})
total += len(descendants[s])
index := 0
for ; index < len(descendants[s]); index++ {
if descendants[s][index] > int64(maxSum) {
break
}
}
for _, d := range descendants[s][:index] {
ancestors[d] = append(ancestors[s], s)
}
if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) {
continue
}
temp := fmt.Sprintf("%v", ancestors[s])
fmt.Printf("%2d: %d Ancestor(s): %-14s", s, len(ancestors[s]), temp)
le := len(descendants[s])
if le <= 10 {
fmt.Printf("%5d Descendant(s): %v\n", le, descendants[s])
} else {
fmt.Printf("%5d Descendant(s): %v\b ...]\n", le, descendants[s][:10])
}
}
fmt.Println("\nTotal descendants", total)
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXPRIME 99
#define MAXPARENT 99
#define NBRPRIMES 30
#define NBRANCESTORS 10
FILE *FileOut;
char format[] = ", %lld";
int Primes[NBRPRIMES];
int iPrimes;
short Ancestors[NBRANCESTORS];
struct Children {
long long Child;
struct Children *pNext;
};
struct Children *Parents[MAXPARENT+1][2];
int CptDescendants[MAXPARENT+1];
long long MaxDescendant = (long long) pow(3.0, 33.0);
short GetParent(long long child);
struct Children *AppendChild(struct Children *node, long long child);
short GetAncestors(short child);
void PrintDescendants(struct Children *node);
int GetPrimes(int primes[], int maxPrime);
int main()
{
long long Child;
short i, Parent, Level;
int TotDesc = 0;
if ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)
return 1;
for (Child = 1; Child <= MaxDescendant; Child++)
{
if (Parent = GetParent(Child))
{
Parents[Parent][1] = AppendChild(Parents[Parent][1], Child);
if (Parents[Parent][0] == NULL)
Parents[Parent][0] = Parents[Parent][1];
CptDescendants[Parent]++;
}
}
if (MAXPARENT > MAXPRIME)
if (GetPrimes(Primes, MAXPARENT) < 0)
return 1;
if (fopen_s(&FileOut, "Ancestors.txt", "w"))
return 1;
for (Parent = 1; Parent <= MAXPARENT; Parent++)
{
Level = GetAncestors(Parent);
fprintf(FileOut, "[%d] Level: %d\n", Parent, Level);
if (Level)
{
fprintf(FileOut, "Ancestors: %d", Ancestors[0]);
for (i = 1; i < Level; i++)
fprintf(FileOut, ", %d", Ancestors[i]);
}
else
fprintf(FileOut, "Ancestors: None");
if (CptDescendants[Parent])
{
fprintf(FileOut, "\nDescendants: %d\n", CptDescendants[Parent]);
strcpy_s(format, "%lld");
PrintDescendants(Parents[Parent][0]);
fprintf(FileOut, "\n");
}
else
fprintf(FileOut, "\nDescendants: None\n");
fprintf(FileOut, "\n");
TotDesc += CptDescendants[Parent];
}
fprintf(FileOut, "Total descendants %d\n\n", TotDesc);
if (fclose(FileOut))
return 1;
return 0;
}
short GetParent(long long child)
{
long long Child = child;
short Parent = 0;
short Index = 0;
while (Child > 1 && Parent <= MAXPARENT)
{
if (Index > iPrimes)
return 0;
while (Child % Primes[Index] == 0)
{
Child /= Primes[Index];
Parent += Primes[Index];
}
Index++;
}
if (Parent == child || Parent > MAXPARENT || child == 1)
return 0;
return Parent;
}
struct Children *AppendChild(struct Children *node, long long child)
{
static struct Children *NodeNew;
if (NodeNew = (struct Children *) malloc(sizeof(struct Children)))
{
NodeNew->Child = child;
NodeNew->pNext = NULL;
if (node != NULL)
node->pNext = NodeNew;
}
return NodeNew;
}
short GetAncestors(short child)
{
short Child = child;
short Parent = 0;
short Index = 0;
while (Child > 1)
{
while (Child % Primes[Index] == 0)
{
Child /= Primes[Index];
Parent += Primes[Index];
}
Index++;
}
if (Parent == child || child == 1)
return 0;
Index = GetAncestors(Parent);
Ancestors[Index] = Parent;
return ++Index;
}
void PrintDescendants(struct Children *node)
{
static struct Children *NodeCurr;
static struct Children *NodePrev;
NodeCurr = node;
NodePrev = NULL;
while (NodeCurr)
{
fprintf(FileOut, format, NodeCurr->Child);
strcpy_s(format, ", %lld");
NodePrev = NodeCurr;
NodeCurr = NodeCurr->pNext;
free(NodePrev);
}
return;
}
int GetPrimes(int primes[], int maxPrime)
{
if (maxPrime < 2)
return -1;
int Index = 0, Value = 1;
int Max, i;
primes[0] = 2;
while ((Value += 2) <= maxPrime)
{
Max = (int) floor(sqrt((double) Value));
for (i = 0; i <= Index; i++)
{
if (primes[i] > Max)
{
if (++Index >= NBRPRIMES)
return -1;
primes[Index] = Value;
break;
}
if (Value % primes[i] == 0)
break;
}
}
return Index;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import "fmt"
type pair [2]int
func cart2(a, b []int) []pair {
p := make([]pair, len(a)*len(b))
i := 0
for _, a := range a {
for _, b := range b {
p[i] = pair{a, b}
i++
}
}
return p
}
func main() {
fmt.Println(cart2([]int{1, 2}, []int{3, 4}))
fmt.Println(cart2([]int{3, 4}, []int{1, 2}))
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import "math"
import "fmt"
func cube(x float64) float64 { return math.Pow(x, 3) }
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
funclist := []ffType{math.Sin, math.Cos, cube}
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}
| #include <stdlib.h>
#include <stdio.h>
#include <math.h>
typedef double (*Class2Func)(double);
double functionA( double v)
{
return v*v*v;
}
double functionB(double v)
{
return exp(log(v)/3);
}
double Function1( Class2Func f2, double val )
{
return f2(val);
}
Class2Func WhichFunc( int idx)
{
return (idx < 4) ? &functionA : &functionB;
}
Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };
double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
return f1(f2(val));
}
typedef struct sComposition {
Class2Func f1;
Class2Func f2;
} *Composition;
Composition Compose( Class2Func f1, Class2Func f2)
{
Composition comp = malloc(sizeof(struct sComposition));
comp->f1 = f1;
comp->f2 = f2;
return comp;
}
double CallComposed( Composition comp, double val )
{
return comp->f1( comp->f2(val) );
}
int main(int argc, char *argv[])
{
int ix;
Composition c;
printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));
for (ix=0; ix<4; ix++) {
c = Compose(funcListA[ix], funcListB[ix]);
printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
}
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"strconv"
)
func listProperDivisors(limit int) {
if limit < 1 {
return
}
width := len(strconv.Itoa(limit))
for i := 1; i <= limit; i++ {
fmt.Printf("%*d -> ", width, i)
if i == 1 {
fmt.Println("(None)")
continue
}
for j := 1; j <= i/2; j++ {
if i%j == 0 {
fmt.Printf(" %d", j)
}
}
fmt.Println()
}
}
func countProperDivisors(n int) int {
if n < 2 {
return 0
}
count := 0
for i := 1; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
fmt.Println()
maxCount := 0
most := []int{1}
for n := 2; n <= 20000; n++ {
count := countProperDivisors(n)
if count == maxCount {
most = append(most, n)
} else if count > maxCount {
maxCount = count
most = most[0:1]
most[0] = n
}
}
fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
fmt.Println("namely", maxCount, "\b\n")
for _, n := range most {
fmt.Println(n)
}
}
| #include <stdio.h>
#include <stdbool.h>
int proper_divisors(const int n, bool print_flag)
{
int count = 0;
for (int i = 1; i < n; ++i) {
if (n % i == 0) {
count++;
if (print_flag)
printf("%d ", i);
}
}
if (print_flag)
printf("\n");
return count;
}
int main(void)
{
for (int i = 1; i <= 10; ++i) {
printf("%d: ", i);
proper_divisors(i, true);
}
int max = 0;
int max_i = 1;
for (int i = 1; i <= 20000; ++i) {
int v = proper_divisors(i, false);
if (v >= max) {
max = v;
max_i = i;
}
}
printf("%d with %d divisors\n", max_i, max);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Go version. | package main
import (
"encoding/xml"
"fmt"
)
func xRemarks(r CharacterRemarks) (string, error) {
b, err := xml.MarshalIndent(r, "", " ")
return string(b), err
}
type CharacterRemarks struct {
Character []crm
}
type crm struct {
Name string `xml:"name,attr"`
Remark string `xml:",chardata"`
}
func main() {
x, err := xRemarks(CharacterRemarks{[]crm{
{`April`, `Bubbly: I'm > Tam and <= Emily`},
{`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
{`Emily`, `Short & shrift`},
}})
if err != nil {
x = err.Error()
}
fmt.Println(x)
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
const char *names[] = {
"April", "Tam O'Shanter", "Emily", NULL
};
const char *remarks[] = {
"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift", NULL
};
int main()
{
xmlDoc *doc = NULL;
xmlNode *root = NULL, *node;
const char **next;
int a;
doc = xmlNewDoc("1.0");
root = xmlNewNode(NULL, "CharacterRemarks");
xmlDocSetRootElement(doc, root);
for(next = names, a = 0; *next != NULL; next++, a++) {
node = xmlNewNode(NULL, "Character");
(void)xmlNewProp(node, "name", *next);
xmlAddChild(node, xmlNewText(remarks[a]));
xmlAddChild(root, node);
}
xmlElemDump(stdout, doc, root);
xmlFreeDoc(doc);
xmlCleanupParser();
return EXIT_SUCCESS;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <plot.h>
#define NP 10
double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
void minmax(double *x, double *y,
double *minx, double *maxx,
double *miny, double *maxy, int n)
{
int i;
*minx = *maxx = x[0];
*miny = *maxy = y[0];
for(i=1; i < n; i++) {
if ( x[i] < *minx ) *minx = x[i];
if ( x[i] > *maxx ) *maxx = x[i];
if ( y[i] < *miny ) *miny = y[i];
if ( y[i] > *maxy ) *maxy = y[i];
}
}
#define YLAB_HEIGHT_F 0.1
#define XLAB_WIDTH_F 0.2
#define XDIV (NP*1.0)
#define YDIV (NP*1.0)
#define EXTRA_W 0.01
#define EXTRA_H 0.01
#define DOTSCALE (1.0/150.0)
#define MAXLABLEN 32
#define PUSHSCALE(X,Y) pl_fscale((X),(Y))
#define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y))
#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)
int main()
{
int plotter, i;
double minx, miny, maxx, maxy;
double lx, ly;
double xticstep, yticstep, nx, ny;
double sx, sy;
char labs[MAXLABLEN+1];
plotter = pl_newpl("png", NULL, stdout, NULL);
if ( plotter < 0 ) exit(1);
pl_selectpl(plotter);
if ( pl_openpl() < 0 ) exit(1);
minmax(x, y, &minx, &maxx, &miny, &maxy, NP);
lx = maxx - minx;
ly = maxy - miny;
pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,
ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);
xticstep = (ceil(maxx) - floor(minx)) / XDIV;
yticstep = (ceil(maxy) - floor(miny)) / YDIV;
pl_flinewidth(0.25);
if ( lx < ly ) {
sx = lx/ly;
sy = 1.0;
} else {
sx = 1.0;
sy = ly/lx;
}
pl_erase();
pl_fbox(floor(minx), floor(miny),
ceil(maxx), ceil(maxy));
pl_fontname("HersheySerif");
for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {
pl_fline(floor(minx), ny, ceil(maxx), ny);
snprintf(labs, MAXLABLEN, "%6.2lf", ny);
FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);
PUSHSCALE(sx,sy);
pl_label(labs);
POPSCALE(sx,sy);
}
for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {
pl_fline(nx, floor(miny), nx, ceil(maxy));
snprintf(labs, MAXLABLEN, "%6.2lf", nx);
FMOVESCALE(nx, floor(miny));
PUSHSCALE(sx,sy);
pl_ftextangle(-90);
pl_alabel('l', 'b', labs);
POPSCALE(sx,sy);
}
pl_fillcolorname("red");
pl_filltype(1);
for(i=0; i < NP; i++)
{
pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,
x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);
}
pl_flushpl();
pl_closepl();
}
|
Rewrite the snippet below in C so it works the same as the original Go code. | package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <plot.h>
#define NP 10
double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
void minmax(double *x, double *y,
double *minx, double *maxx,
double *miny, double *maxy, int n)
{
int i;
*minx = *maxx = x[0];
*miny = *maxy = y[0];
for(i=1; i < n; i++) {
if ( x[i] < *minx ) *minx = x[i];
if ( x[i] > *maxx ) *maxx = x[i];
if ( y[i] < *miny ) *miny = y[i];
if ( y[i] > *maxy ) *maxy = y[i];
}
}
#define YLAB_HEIGHT_F 0.1
#define XLAB_WIDTH_F 0.2
#define XDIV (NP*1.0)
#define YDIV (NP*1.0)
#define EXTRA_W 0.01
#define EXTRA_H 0.01
#define DOTSCALE (1.0/150.0)
#define MAXLABLEN 32
#define PUSHSCALE(X,Y) pl_fscale((X),(Y))
#define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y))
#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)
int main()
{
int plotter, i;
double minx, miny, maxx, maxy;
double lx, ly;
double xticstep, yticstep, nx, ny;
double sx, sy;
char labs[MAXLABLEN+1];
plotter = pl_newpl("png", NULL, stdout, NULL);
if ( plotter < 0 ) exit(1);
pl_selectpl(plotter);
if ( pl_openpl() < 0 ) exit(1);
minmax(x, y, &minx, &maxx, &miny, &maxy, NP);
lx = maxx - minx;
ly = maxy - miny;
pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,
ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);
xticstep = (ceil(maxx) - floor(minx)) / XDIV;
yticstep = (ceil(maxy) - floor(miny)) / YDIV;
pl_flinewidth(0.25);
if ( lx < ly ) {
sx = lx/ly;
sy = 1.0;
} else {
sx = 1.0;
sy = ly/lx;
}
pl_erase();
pl_fbox(floor(minx), floor(miny),
ceil(maxx), ceil(maxy));
pl_fontname("HersheySerif");
for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {
pl_fline(floor(minx), ny, ceil(maxx), ny);
snprintf(labs, MAXLABLEN, "%6.2lf", ny);
FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);
PUSHSCALE(sx,sy);
pl_label(labs);
POPSCALE(sx,sy);
}
for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {
pl_fline(nx, floor(miny), nx, ceil(maxy));
snprintf(labs, MAXLABLEN, "%6.2lf", nx);
FMOVESCALE(nx, floor(miny));
PUSHSCALE(sx,sy);
pl_ftextangle(-90);
pl_alabel('l', 'b', labs);
POPSCALE(sx,sy);
}
pl_fillcolorname("red");
pl_filltype(1);
for(i=0; i < NP; i++)
{
pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,
x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);
}
pl_flushpl();
pl_closepl();
}
|
Transform the following Go implementation into C, maintaining the same output and logic. | package main
import "fmt"
import "regexp"
func main() {
str := "I am the original string"
matched, _ := regexp.MatchString(".*string$", str)
if matched { fmt.Println("ends with 'string'") }
pattern := regexp.MustCompile("original")
result := pattern.ReplaceAllString(str, "modified")
fmt.Println(result)
}
| #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>
int main()
{
regex_t preg;
regmatch_t substmatch[1];
const char *tp = "string$";
const char *t1 = "this is a matching string";
const char *t2 = "this is not a matching string!";
const char *ss = "istyfied";
regcomp(&preg, "string$", REG_EXTENDED);
printf("'%s' %smatched with '%s'\n", t1,
(regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp);
printf("'%s' %smatched with '%s'\n", t2,
(regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp);
regfree(&preg);
regcomp(&preg, "a[a-z]+", REG_EXTENDED);
if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )
{
char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +
(strlen(t1) - substmatch[0].rm_eo) + 2);
memcpy(ns, t1, substmatch[0].rm_so+1);
memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));
memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],
strlen(&t1[substmatch[0].rm_eo]));
ns[ substmatch[0].rm_so + strlen(ss) +
strlen(&t1[substmatch[0].rm_eo]) ] = 0;
printf("mod string: '%s'\n", ns);
free(ns);
} else {
printf("the string '%s' is the same: no matching!\n", t1);
}
regfree(&preg);
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"sort"
)
func main() {
lower, upper := 0, 100
fmt.Printf(`Instructions:
Think of integer number from %d (inclusive) to %d (exclusive) and
I will guess it. After each guess, I will ask you if it is less than
or equal to some number, and you will respond with "yes" or "no".
`, lower, upper)
answer := sort.Search(upper-lower, func (i int) bool {
fmt.Printf("Is your number less than or equal to %d? ", lower+i)
s := ""
fmt.Scanf("%s", &s)
return s != "" && s[0] == 'y'
})
fmt.Printf("Your number is %d.\n", lower+answer)
}
| #include <stdio.h>
int main(){
int bounds[ 2 ] = {1, 100};
char input[ 2 ] = " ";
int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );
do{
switch( input[ 0 ] ){
case 'H':
bounds[ 1 ] = choice;
break;
case 'L':
bounds[ 0 ] = choice;
break;
case 'Y':
printf( "\nAwwwright\n" );
return 0;
}
choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Is the number %d? (Y/H/L) ", choice );
}while( scanf( "%1s", input ) == 1 );
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KeyType const char *
#define ValType int
#define HASH_SIZE 4096
unsigned strhashkey( const char * key, int max)
{
unsigned h=0;
unsigned hl, hr;
while(*key) {
h += *key;
hl= 0x5C5 ^ (h&0xfff00000 )>>18;
hr =(h&0x000fffff );
h = hl ^ hr ^ *key++;
}
return h % max;
}
typedef struct sHme {
KeyType key;
ValType value;
struct sHme *link;
} *MapEntry;
typedef struct he {
MapEntry first, last;
} HashElement;
HashElement hash[HASH_SIZE];
typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);
void HashAddH( KeyType key, ValType value,
KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
(*copyVal)(&m_ent->value, value);
}
else {
MapEntry last;
MapEntry hme = malloc(sizeof(struct sHme));
(*copyKey)(&hme->key, key);
(*copyVal)(&hme->value, value);
hme->link = NULL;
last = hash[hix].last;
if (last) {
last->link = hme;
}
else
hash[hix].first = hme;
hash[hix].last = hme;
}
}
int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
*val = m_ent->value;
}
return (m_ent != NULL);
}
void copyStr(const char**dest, const char *src)
{
*dest = strdup(src);
}
void copyInt( int *dest, int src)
{
*dest = src;
}
int strCompare( const char *key1, const char *key2)
{
return strcmp(key1, key2) == 0;
}
void HashAdd( KeyType key, ValType value )
{
HashAddH( key, value, ©Str, ©Int, &strhashkey, &strCompare);
}
int HashGet(ValType *val, KeyType key)
{
return HashGetH( val, key, &strhashkey, &strCompare);
}
int main()
{
static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
static int valuList[] = {1,43,640, 747, 42, 42};
int ix;
for (ix=0; ix<6; ix++) {
HashAdd(keyList[ix], valuList[ix]);
}
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"sort"
)
func getBins(limits, data []int) []int {
n := len(limits)
bins := make([]int, n+1)
for _, d := range data {
index := sort.SearchInts(limits, d)
if index < len(limits) && d == limits[index] {
index++
}
bins[index]++
}
return bins
}
func printBins(limits, bins []int) {
n := len(limits)
fmt.Printf(" < %3d = %2d\n", limits[0], bins[0])
for i := 1; i < n; i++ {
fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
}
fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n])
fmt.Println()
}
func main() {
limitsList := [][]int{
{23, 37, 43, 53, 67, 83},
{14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
}
dataList := [][]int{
{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
},
{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933,
416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247,
346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97,
854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395,
787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237,
605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749,
},
}
for i := 0; i < len(limitsList); i++ {
fmt.Println("Example", i+1, "\b\n")
bins := getBins(limitsList[i], dataList[i])
printBins(limitsList[i], bins)
}
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import (
"math"
"raster"
)
const (
width = 400
height = 300
depth = 8
angle = 12
length = 50
frac = .8
)
func main() {
g := raster.NewGrmap(width, height)
ftree(g, width/2, height*9/10, length, 0, depth)
g.Bitmap().WritePpmFile("ftree.ppm")
}
func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {
x2 := x + distance*math.Sin(direction*math.Pi/180)
y2 := y - distance*math.Cos(direction*math.Pi/180)
g.AaLine(x, y, x2, y2)
if depth > 0 {
ftree(g, x2, y2, distance*frac, direction-angle, depth-1)
ftree(g, x2, y2, distance*frac, direction+angle, depth-1)
}
}
| #include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif
#define SIZE 800
#define SCALE 5
#define BRANCHES 14
#define ROTATION_SCALE 0.75
#define INITIAL_LENGTH 50
double rand_fl(){
return (double)rand() / (double)RAND_MAX;
}
void draw_tree(SDL_Surface * surface, double offsetx, double offsety,
double directionx, double directiony, double size,
double rotation, int depth) {
#ifdef WITH_CAIRO
cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,
CAIRO_FORMAT_RGB24,
surface->w, surface->h,
surface->pitch );
cairo_t *ct = cairo_create(surf);
cairo_set_line_width(ct, 1);
cairo_set_source_rgba(ct, 0,0,0,1);
cairo_move_to(ct, (int)offsetx, (int)offsety);
cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));
cairo_stroke(ct);
#else
sge_AALine(surface,
(int)offsetx, (int)offsety,
(int)(offsetx + directionx * size), (int)(offsety + directiony * size),
SDL_MapRGB(surface->format, 0, 0, 0));
#endif
if (depth > 0){
draw_tree(surface,
offsetx + directionx * size,
offsety + directiony * size,
directionx * cos(rotation) + directiony * sin(rotation),
directionx * -sin(rotation) + directiony * cos(rotation),
size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
rotation * ROTATION_SCALE,
depth - 1);
draw_tree(surface,
offsetx + directionx * size,
offsety + directiony * size,
directionx * cos(-rotation) + directiony * sin(-rotation),
directionx * -sin(-rotation) + directiony * cos(-rotation),
size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
rotation * ROTATION_SCALE,
depth - 1);
}
}
void render(SDL_Surface * surface){
SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
draw_tree(surface,
surface->w / 2.0,
surface->h - 10.0,
0.0, -1.0,
INITIAL_LENGTH,
PI / 8,
BRANCHES);
SDL_UpdateRect(surface, 0, 0, 0, 0);
}
int main(){
SDL_Surface * screen;
SDL_Event evt;
SDL_Init(SDL_INIT_VIDEO);
srand((unsigned)time(NULL));
screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);
render(screen);
while(1){
if (SDL_PollEvent(&evt)){
if(evt.type == SDL_QUIT) break;
}
SDL_Delay(1);
}
SDL_Quit();
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C. | package main
import "github.com/fogleman/gg"
var palette = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func pinstripe(dc *gg.Context) {
w := dc.Width()
h := dc.Height() / 4
for b := 1; b <= 4; b++ {
for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
dc.SetHexColor(palette[ci%8])
y := h * (b - 1)
dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
dc.Fill()
}
}
}
func main() {
dc := gg.NewContext(900, 600)
pinstripe(dc)
dc.SavePNG("color_pinstripe.png")
}
| #include<graphics.h>
#include<conio.h>
#define sections 4
int main()
{
int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;
initgraph(&d,&m,"c:/turboc3/bgi");
maxX = getmaxx();
maxY = getmaxy();
for(y=0;y<maxY;y+=maxY/sections)
{
for(x=0;x<maxX;x+=increment)
{
setfillstyle(SOLID_FILL,(colour++)%16);
bar(x,y,x+increment,y+maxY/sections);
}
increment++;
colour = 0;
}
getch();
closegraph();
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| #include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
} Date;
bool leap(uint16_t year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const char *weekday(Date date) {
static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const char *days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
unsigned c = date.year/100, r = date.year%100;
unsigned s = r/12, t = r%12;
unsigned c_anchor = (5 * (c%4) + 2) % 7;
unsigned doom = (s + t + (t/4) + c_anchor) % 7;
unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const char *past = "was", *future = "will be";
const char *months[] = { "",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
int i;
for (i=0; i < sizeof(dates)/sizeof(Date); i++) {
printf("%s %d, %d %s on a %s.\n",
months[dates[i].month], dates[i].day, dates[i].year,
dates[i].year > 2021 ? future : past,
weekday(dates[i]));
}
return 0;
}
|
Write the same code in C as shown below in Go. | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| #include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
} Date;
bool leap(uint16_t year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const char *weekday(Date date) {
static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const char *days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
unsigned c = date.year/100, r = date.year%100;
unsigned s = r/12, t = r%12;
unsigned c_anchor = (5 * (c%4) + 2) % 7;
unsigned doom = (s + t + (t/4) + c_anchor) % 7;
unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const char *past = "was", *future = "will be";
const char *months[] = { "",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
int i;
for (i=0; i < sizeof(dates)/sizeof(Date); i++) {
printf("%s %d, %d %s on a %s.\n",
months[dates[i].month], dates[i].day, dates[i].year,
dates[i].year > 2021 ? future : past,
weekday(dates[i]));
}
return 0;
}
|
Generate an equivalent C version of this Go code. | package main
import (
"fmt"
"math/rand"
"time"
)
func cocktailShakerSort(a []int) {
var begin = 0
var end = len(a) - 2
for begin <= end {
newBegin := end
newEnd := begin
for i := begin; i <= end; i++ {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newEnd = i
}
}
end = newEnd - 1
for i := end; i >= begin; i-- {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i], a[i+1]
newBegin = i
}
}
begin = newBegin + 1
}
}
func cocktailSort(a []int) {
last := len(a) - 1
for {
swapped := false
for i := 0; i < last; i++ {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
swapped = false
for i := last - 1; i >= 0; i-- {
if a[i] > a[i+1] {
a[i], a[i+1] = a[i+1], a[i]
swapped = true
}
}
if !swapped {
return
}
}
}
func main() {
a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170}
fmt.Println("Original array:", a)
b := make([]int, len(a))
copy(b, a)
cocktailSort(a)
fmt.Println("Cocktail sort :", a)
cocktailShakerSort(b)
fmt.Println("C/Shaker sort :", b)
rand.Seed(time.Now().UnixNano())
fmt.Println("\nRelative speed of the two sorts")
fmt.Println(" N x faster (CSS v CS)")
fmt.Println("----- -------------------")
const runs = 10
for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} {
sum := 0.0
for i := 1; i <= runs; i++ {
nums := make([]int, n)
for i := 0; i < n; i++ {
rn := rand.Intn(100000)
if i%2 == 1 {
rn = -rn
}
nums[i] = rn
}
nums2 := make([]int, n)
copy(nums2, nums)
start := time.Now()
cocktailSort(nums)
elapsed := time.Since(start)
start2 := time.Now()
cocktailShakerSort(nums2)
elapsed2 := time.Since(start2)
sum += float64(elapsed) / float64(elapsed2)
}
fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs)
}
}
| #include <stdio.h>
#include <string.h>
void swap(char* p1, char* p2, size_t size) {
for (; size-- > 0; ++p1, ++p2) {
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
}
void cocktail_shaker_sort(void* base, size_t count, size_t size,
int (*cmp)(const void*, const void*)) {
char* begin = base;
char* end = base + size * count;
if (end == begin)
return;
for (end -= size; begin < end; ) {
char* new_begin = end;
char* new_end = begin;
for (char* p = begin; p < end; p += size) {
char* q = p + size;
if (cmp(p, q) > 0) {
swap(p, q, size);
new_end = p;
}
}
end = new_end;
for (char* p = end; p > begin; p -= size) {
char* q = p - size;
if (cmp(q, p) > 0) {
swap(p, q, size);
new_begin = p;
}
}
begin = new_begin;
}
}
int string_compare(const void* p1, const void* p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
void print(const char** a, size_t len) {
for (size_t i = 0; i < len; ++i)
printf("%s ", a[i]);
printf("\n");
}
int main() {
const char* a[] = { "one", "two", "three", "four", "five",
"six", "seven", "eight" };
const size_t len = sizeof(a)/sizeof(a[0]);
printf("before: ");
print(a, len);
cocktail_shaker_sort(a, len, sizeof(char*), string_compare);
printf("after: ");
print(a, len);
return 0;
}
|
Generate a C translation of this Go snippet without changing its computational steps. | package main
import (
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/math"
"github.com/google/gxui/themes/dark"
omath "math"
"time"
)
const (
ANIMATION_WIDTH int = 480
ANIMATION_HEIGHT int = 320
BALL_RADIUS float32 = 25.0
METER_PER_PIXEL float64 = 1.0 / 20.0
PHI_ZERO float64 = omath.Pi * 0.5
)
var (
l float64 = float64(ANIMATION_HEIGHT) * 0.5
freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))
)
type Pendulum interface {
GetPhi() float64
}
type mathematicalPendulum struct {
start time.Time
}
func (p *mathematicalPendulum) GetPhi() float64 {
if (p.start == time.Time{}) {
p.start = time.Now()
}
t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)
return PHI_ZERO * omath.Cos(t*freq)
}
type numericalPendulum struct {
currentPhi float64
angAcc float64
angVel float64
lastTime time.Time
}
func (p *numericalPendulum) GetPhi() float64 {
dt := 0.0
if (p.lastTime != time.Time{}) {
dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)
}
p.lastTime = time.Now()
p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)
p.angVel += p.angAcc * dt
p.currentPhi += p.angVel * dt
return p.currentPhi
}
func draw(p Pendulum, canvas gxui.Canvas, x, y int) {
attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}
phi := p.GetPhi()
ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}
line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}
canvas.DrawLines(line, gxui.DefaultPen)
m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}
rect := math.Rect{ball.Sub(m), ball.Add(m)}
canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))
}
func appMain(driver gxui.Driver) {
theme := dark.CreateTheme(driver)
window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum")
window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))
image := theme.CreateImage()
ticker := time.NewTicker(time.Millisecond * 15)
pendulum := &mathematicalPendulum{}
pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}
go func() {
for _ = range ticker.C {
canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})
canvas.Clear(gxui.White)
draw(pendulum, canvas, 0, 0)
draw(pendulum2, canvas, 0, ANIMATION_HEIGHT)
canvas.Complete()
driver.Call(func() {
image.SetCanvas(canvas)
})
}
}()
window.AddChild(image)
window.OnClose(ticker.Stop)
window.OnClose(driver.Terminate)
}
func main() {
gl.StartDriver(appMain)
}
| #include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>
#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow("Pendulum");
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| int gray_encode(int n) {
return n ^ (n >> 1);
}
int gray_decode(int n) {
int p = n;
while (n >>= 1) p ^= n;
return p;
}
|
Change the programming language of this snippet from Go to C without modifying what it does. | package main
import "fmt"
func enc(b int) int {
return b ^ b>>1
}
func dec(g int) (b int) {
for ; g != 0; g >>= 1 {
b ^= g
}
return
}
func main() {
fmt.Println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d)
}
}
| int gray_encode(int n) {
return n ^ (n >> 1);
}
int gray_decode(int n) {
int p = n;
while (n >>= 1) p ^= n;
return p;
}
|
Convert the following code from Go to C, ensuring the logic remains intact. | package main
import (
"archive/tar"
"compress/gzip"
"flag"
"io"
"log"
"os"
"time"
)
func main() {
filename := flag.String("file", "TAPE.FILE", "filename within TAR")
data := flag.String("data", "", "data for file")
outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
gzipFlag := flag.Bool("gzip", false, "use gzip compression")
flag.Parse()
var w io.Writer = os.Stdout
if *outfile != "" {
f, err := os.Create(*outfile)
if err != nil {
log.Fatalf("opening/creating %q: %v", *outfile, err)
}
defer f.Close()
w = f
}
if *gzipFlag {
zw := gzip.NewWriter(w)
defer zw.Close()
w = zw
}
tw := tar.NewWriter(w)
defer tw.Close()
w = tw
tw.WriteHeader(&tar.Header{
Name: *filename,
Mode: 0660,
Size: int64(len(*data)),
ModTime: time.Now(),
Typeflag: tar.TypeReg,
Uname: "guest",
Gname: "guest",
})
_, err := w.Write([]byte(*data))
if err != nil {
log.Fatal("writing data:", err)
}
}
| #include<stdio.h>
int main()
{
FILE* fp = fopen("TAPE.FILE","w");
fprintf(fp,"This code should be able to write a file to magnetic tape.\n");
fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n");
fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n");
fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n");
fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n");
fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n");
fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n");
fprintf(fp,"EOF");
fclose(fp);
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"sort"
"container/heap"
"fmt"
)
type HeapHelper struct {
container sort.Interface
length int
}
func (self HeapHelper) Len() int { return self.length }
func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) }
func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) }
func (self *HeapHelper) Push(x interface{}) { panic("impossible") }
func (self *HeapHelper) Pop() interface{} {
self.length--
return nil
}
func heapSort(a sort.Interface) {
helper := HeapHelper{ a, a.Len() }
heap.Init(&helper)
for helper.length > 0 {
heap.Pop(&helper)
}
}
func main() {
a := []int{170, 45, 75, -90, -802, 24, 2, 66}
fmt.Println("before:", a)
heapSort(sort.IntSlice(a))
fmt.Println("after: ", a)
}
| #include <stdio.h>
int max (int *a, int n, int i, int j, int k) {
int m = i;
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
void downheap (int *a, int n, int i) {
while (1) {
int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
if (j == i) {
break;
}
int t = a[i];
a[i] = a[j];
a[j] = t;
i = j;
}
}
void heapsort (int *a, int n) {
int i;
for (i = (n - 2) / 2; i >= 0; i--) {
downheap(a, n, i);
}
for (i = 0; i < n; i++) {
int t = a[n - i - 1];
a[n - i - 1] = a[0];
a[0] = t;
downheap(a, n - i - 1, 0);
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
heapsort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Five Rank = 5
Six Rank = 6
Seven Rank = 7
Eight Rank = 8
Nine Rank = 9
Ten Rank = 10
Jack Rank = 11
Queen Rank = 12
King Rank = 13
)
func (r Rank) String() string {
const ranks = "A23456789TJQK"
return ranks[r-1 : r]
}
type Card uint8
func NewCard(r Rank, s Suit) Card {
return Card(13*uint8(s) + uint8(r-1))
}
func (c Card) RankSuit() (Rank, Suit) {
return Rank(c%13 + 1), Suit(c / 13)
}
func (c Card) Rank() Rank {
return Rank(c%13 + 1)
}
func (c Card) Suit() Suit {
return Suit(c / 13)
}
func (c Card) String() string {
return c.Rank().String() + c.Suit().String()
}
type Deck []Card
func NewDeck() Deck {
d := make(Deck, 52)
for i := range d {
d[i] = Card(i)
}
return d
}
func (d Deck) String() string {
s := ""
for i, c := range d {
switch {
case i == 0:
case i%13 == 0:
s += "\n"
default:
s += " "
}
s += c.String()
}
return s
}
func (d Deck) Shuffle() {
for i := range d {
j := rand.Intn(i + 1)
d[i], d[j] = d[j], d[i]
}
}
func (d Deck) Contains(tc Card) bool {
for _, c := range d {
if c == tc {
return true
}
}
return false
}
func (d *Deck) AddDeck(decks ...Deck) {
for _, o := range decks {
*d = append(*d, o...)
}
}
func (d *Deck) AddCard(c Card) {
*d = append(*d, c)
}
func (d *Deck) Draw(n int) Deck {
old := *d
*d = old[n:]
return old[:n:n]
}
func (d *Deck) DrawCard() (Card, bool) {
if len(*d) == 0 {
return 0, false
}
old := *d
*d = old[1:]
return old[0], true
}
func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {
for i := 0; i < cards; i++ {
for j := range hands {
if len(*d) == 0 {
return hands, false
}
hands[j] = append(hands[j], (*d)[0])
*d = (*d)[1:]
}
}
return hands, true
}
| #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int locale_ok = 0;
wchar_t s_suits[] = L"♠♥♦♣";
const char *s_suits_ascii[] = { "S", "H", "D", "C" };
const char *s_nums[] = { "WHAT",
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K",
"OVERFLOW"
};
typedef struct { int suit, number, _s; } card_t, *card;
typedef struct { int n; card_t cards[52]; } deck_t, *deck;
void show_card(card c)
{
if (locale_ok)
printf(" %lc%s", s_suits[c->suit], s_nums[c->number]);
else
printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]);
}
deck new_deck()
{
int i, j, k;
deck d = malloc(sizeof(deck_t));
d->n = 52;
for (i = k = 0; i < 4; i++)
for (j = 1; j <= 13; j++, k++) {
d->cards[k].suit = i;
d->cards[k].number = j;
}
return d;
}
void show_deck(deck d)
{
int i;
printf("%d cards:", d->n);
for (i = 0; i < d->n; i++)
show_card(d->cards + i);
printf("\n");
}
int cmp_card(const void *a, const void *b)
{
int x = ((card)a)->_s, y = ((card)b)->_s;
return x < y ? -1 : x > y;
}
card deal_card(deck d)
{
if (!d->n) return 0;
return d->cards + --d->n;
}
void shuffle_deck(deck d)
{
int i;
for (i = 0; i < d->n; i++)
d->cards[i]._s = rand();
qsort(d->cards, d->n, sizeof(card_t), cmp_card);
}
int main()
{
int i, j;
deck d = new_deck();
locale_ok = (0 != setlocale(LC_CTYPE, ""));
printf("New deck, "); show_deck(d);
printf("\nShuffle and deal to three players:\n");
shuffle_deck(d);
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++)
show_card(deal_card(d));
printf("\n");
}
printf("Left in deck "); show_deck(d);
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import (
"fmt"
)
func main() {
var a [5]int
fmt.Println("len(a) =", len(a))
fmt.Println("a =", a)
a[0] = 3
fmt.Println("a =", a)
fmt.Println("a[0] =", a[0])
s := a[:4]
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
s = s[:5]
fmt.Println("s =", s)
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
}
| char foo()
{
char array[5] = {3,6,9,12,15};
return array[2];
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
}
| #include <stdio.h>
int main()
{
int i, j, dim, d;
int depth = 3;
for (i = 0, dim = 1; i < depth; i++, dim *= 3);
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
for (d = dim / 3; d; d /= 3)
if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
break;
printf(d ? " " : "##");
}
printf("\n");
}
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
rand.Seed(time.Now().UnixNano())
fmt.Println("unsorted:", list)
temp := make([]int, len(list))
copy(temp, list)
for !sort.IntsAreSorted(temp) {
for i, v := range rand.Perm(len(list)) {
temp[i] = list[v]
}
}
fmt.Println("sorted! ", temp)
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool is_sorted(int *a, int n)
{
while ( --n >= 1 ) {
if ( a[n] < a[n-1] ) return false;
}
return true;
}
void shuffle(int *a, int n)
{
int i, t, r;
for(i=0; i < n; i++) {
t = a[i];
r = rand() % n;
a[i] = a[r];
a[r] = t;
}
}
void bogosort(int *a, int n)
{
while ( !is_sorted(a, n) ) shuffle(a, n);
}
int main()
{
int numbers[] = { 1, 10, 9, 7, 3, 0 };
int i;
bogosort(numbers, 6);
for (i=0; i < 6; i++) printf("%d ", numbers[i]);
printf("\n");
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math"
"sort"
)
type Patient struct {
id int
lastName string
}
var patientDir = make(map[int]string)
var patientIds []int
func patientNew(id int, lastName string) Patient {
patientDir[id] = lastName
patientIds = append(patientIds, id)
sort.Ints(patientIds)
return Patient{id, lastName}
}
type DS struct {
dates []string
scores []float64
}
type Visit struct {
id int
date string
score float64
}
var visitDir = make(map[int]DS)
func visitNew(id int, date string, score float64) Visit {
if date == "" {
date = "0000-00-00"
}
v, ok := visitDir[id]
if ok {
v.dates = append(v.dates, date)
v.scores = append(v.scores, score)
visitDir[id] = DS{v.dates, v.scores}
} else {
visitDir[id] = DS{[]string{date}, []float64{score}}
}
return Visit{id, date, score}
}
type Merge struct{ id int }
func (m Merge) lastName() string { return patientDir[m.id] }
func (m Merge) dates() []string { return visitDir[m.id].dates }
func (m Merge) scores() []float64 { return visitDir[m.id].scores }
func (m Merge) lastVisit() string {
dates := m.dates()
dates2 := make([]string, len(dates))
copy(dates2, dates)
sort.Strings(dates2)
return dates2[len(dates2)-1]
}
func (m Merge) scoreSum() float64 {
sum := 0.0
for _, score := range m.scores() {
if score != -1 {
sum += score
}
}
return sum
}
func (m Merge) scoreAvg() float64 {
count := 0
for _, score := range m.scores() {
if score != -1 {
count++
}
}
return m.scoreSum() / float64(count)
}
func mergePrint(merges []Merge) {
fmt.Println("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |")
f := "| %d | %-7s | %s | %4s | %4s |\n"
for _, m := range merges {
_, ok := visitDir[m.id]
if ok {
lv := m.lastVisit()
if lv == "0000-00-00" {
lv = " "
}
scoreSum := m.scoreSum()
ss := fmt.Sprintf("%4.1f", scoreSum)
if scoreSum == 0 {
ss = " "
}
scoreAvg := m.scoreAvg()
sa := " "
if !math.IsNaN(scoreAvg) {
sa = fmt.Sprintf("%4.2f", scoreAvg)
}
fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)
} else {
fmt.Printf(f, m.id, m.lastName(), " ", " ", " ")
}
}
}
func main() {
patientNew(1001, "Hopper")
patientNew(4004, "Wirth")
patientNew(3003, "Kemeny")
patientNew(2002, "Gosling")
patientNew(5005, "Kurtz")
visitNew(2002, "2020-09-10", 6.8)
visitNew(1001, "2020-09-17", 5.5)
visitNew(4004, "2020-09-24", 8.4)
visitNew(2002, "2020-10-08", -1)
visitNew(1001, "", 6.6)
visitNew(3003, "2020-11-12", -1)
visitNew(4004, "2020-11-05", 7.0)
visitNew(1001, "2020-11-19", 5.3)
merges := make([]Merge, len(patientIds))
for i, id := range patientIds {
merges[i] = Merge{id}
}
mergePrint(merges)
}
|
#include <ctime>
#include <cstdint>
extern "C" {
int64_t from date(const char* string) {
struct tm tmInfo = {0};
strptime(string, "%Y-%m-%d", &tmInfo);
return mktime(&tmInfo);
}
}
|
Convert this Go snippet to C and keep its semantics consistent. | package main
import (
"fmt"
"math"
)
type fdy func(float64, float64) float64
func eulerStep(f fdy, x, y, h float64) float64 {
return y + h*f(x, y)
}
func newCoolingRate(k float64) func(float64) float64 {
return func(deltaTemp float64) float64 {
return -k * deltaTemp
}
}
func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {
return func(time float64) float64 {
return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)
}
}
func newCoolingRateDy(k, ambientTemp float64) fdy {
crf := newCoolingRate(k)
return func(_, objectTemp float64) float64 {
return crf(objectTemp - ambientTemp)
}
}
func main() {
k := .07
tempRoom := 20.
tempObject := 100.
fcr := newCoolingRateDy(k, tempRoom)
analytic := newTempFunc(k, tempRoom, tempObject)
for _, deltaTime := range []float64{2, 5, 10} {
fmt.Printf("Step size = %.1f\n", deltaTime)
fmt.Println(" Time Euler's Analytic")
temp := tempObject
for time := 0.; time <= 100; time += deltaTime {
fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time))
temp = eulerStep(fcr, time, temp, deltaTime)
}
fmt.Println()
}
}
| #include <stdio.h>
#include <math.h>
typedef double (*deriv_f)(double, double);
#define FMT " %7.3f"
void ivp_euler(deriv_f f, double y, int step, int end_t)
{
int t = 0;
printf(" Step %2d: ", (int)step);
do {
if (t % 10 == 0) printf(FMT, y);
y += step * f(t, y);
} while ((t += step) <= end_t);
printf("\n");
}
void analytic()
{
double t;
printf(" Time: ");
for (t = 0; t <= 100; t += 10) printf(" %7g", t);
printf("\nAnalytic: ");
for (t = 0; t <= 100; t += 10)
printf(FMT, 20 + 80 * exp(-0.07 * t));
printf("\n");
}
double cooling(double t, double temp)
{
return -0.07 * (temp - 20);
}
int main()
{
analytic();
ivp_euler(cooling, 100, 2, 100);
ivp_euler(cooling, 100, 5, 100);
ivp_euler(cooling, 100, 10, 100);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
| #include <math.h>
#include <stdio.h>
#include <assert.h>
int nonsqr(int n) {
return n + (int)(0.5 + sqrt(n));
}
int main() {
int i;
for (i = 1; i < 23; i++)
printf("%d ", nonsqr(i));
printf("\n");
for (i = 1; i < 1000000; i++) {
double j = sqrt(nonsqr(i));
assert(j != floor(j));
}
return 0;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
| #include <math.h>
#include <stdio.h>
#include <assert.h>
int nonsqr(int n) {
return n + (int)(0.5 + sqrt(n));
}
int main() {
int i;
for (i = 1; i < 23; i++)
printf("%d ", nonsqr(i));
printf("\n");
for (i = 1; i < 1000000; i++) {
double j = sqrt(nonsqr(i));
assert(j != floor(j));
}
return 0;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void putm(char* string, size_t m)
{
while(*string && m--)
putchar(*string++);
}
int main(void)
{
char string[] =
"Programs for other encodings (such as 8-bit ASCII, or EUC-JP)."
int n = 3;
int m = 4;
char knownCharacter = '(';
char knownSubstring[] = "encodings";
putm(string+n-1, m ); putchar('\n');
puts(string+n+1); putchar('\n');
putm(string, strlen(string)-1); putchar('\n');
putm(strchr(string, knownCharacter), m ); putchar('\n');
putm(strstr(string, knownSubstring), m ); putchar('\n');
return EXIT_SUCCESS;
}
|
Please provide an equivalent version of this Go code in C. | package main
import (
"log"
"sort"
)
func main() {
log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4}))
log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))
log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))
log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))
}
func jortSort(a []int) bool {
c := make([]int, len(a))
copy(c, a)
sort.Ints(a)
for k, v := range c {
if v == a[k] {
continue
} else {
return false
}
}
return true
}
| #include <stdio.h>
#include <stdlib.h>
int number_of_digits(int x){
int NumberOfDigits;
for(NumberOfDigits=0;x!=0;NumberOfDigits++){
x=x/10;
}
return NumberOfDigits;
}
int* convert_array(char array[], int NumberOfElements)
{
int *convertedArray=malloc(NumberOfElements*sizeof(int));
int originalElement, convertedElement;
for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)
{
convertedArray[convertedElement]=atoi(&array[originalElement]);
originalElement+=number_of_digits(convertedArray[convertedElement])+1;
}
return convertedArray;
}
int isSorted(int array[], int numberOfElements){
int sorted=1;
for(int counter=0;counter<numberOfElements;counter++){
if(counter!=0 && array[counter-1]>array[counter]) sorted--;
}
return sorted;
}
int main(int argc, char* argv[])
{
int* convertedArray;
convertedArray=convert_array(*(argv+1), argc-1);
if(isSorted(convertedArray, argc-1)==1) printf("Did you forgot to turn on your brain?! This array is already sorted!\n");
else if(argc-1<=10) printf("Am I really supposed to sort this? Sort it by yourself!\n");
else printf("Am I really supposed to sort this? Bhahahaha!\n");
free(convertedArray);
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
}
| #include <stdio.h>
int is_leap_year(unsigned year)
{
return !(year & (year % 100 ? 3 : 15));
}
int main(void)
{
const unsigned test_case[] = {
1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100
};
const unsigned n = sizeof test_case / sizeof test_case[0];
for (unsigned i = 0; i != n; ++i) {
unsigned year = test_case[i];
printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not ");
}
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"math/big"
)
func main() {
var n, p int64
fmt.Printf("A sample of permutations from 1 to 12:\n")
for n = 1; n < 13; n++ {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 10 to 60:\n")
for n = 10; n < 61; n += 10 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of permutations from 5 to 15000:\n")
nArr := [...]int64{5, 50, 500, 1000, 5000, 15000}
for _, n = range nArr {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 100 to 1000:\n")
for n = 100; n < 1001; n += 100 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
}
func fact(n *big.Int) *big.Int {
if n.Sign() < 1 {
return big.NewInt(0)
}
r := big.NewInt(1)
i := big.NewInt(2)
for i.Cmp(n) < 1 {
r.Mul(r, i)
i.Add(i, big.NewInt(1))
}
return r
}
func perm(n, k *big.Int) *big.Int {
r := fact(n)
r.Div(r, fact(n.Sub(n, k)))
return r
}
func comb(n, r *big.Int) *big.Int {
if r.Cmp(n) == 1 {
return big.NewInt(0)
}
if r.Cmp(n) == 0 {
return big.NewInt(1)
}
c := fact(n)
den := fact(n.Sub(n, r))
den.Mul(den, fact(r))
c.Div(c, den)
return c
}
| #include <gmp.h>
void perm(mpz_t out, int n, int k)
{
mpz_set_ui(out, 1);
k = n - k;
while (n > k) mpz_mul_ui(out, out, n--);
}
void comb(mpz_t out, int n, int k)
{
perm(out, n, k);
while (k) mpz_divexact_ui(out, out, k--);
}
int main(void)
{
mpz_t x;
mpz_init(x);
perm(x, 1000, 969);
gmp_printf("P(1000,969) = %Zd\n", x);
comb(x, 1000, 969);
gmp_printf("C(1000,969) = %Zd\n", x);
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import (
"fmt"
"sort"
"strconv"
)
func lexOrder(n int) []int {
first, last, k := 1, n, n
if n < 1 {
first, last, k = n, 1, 2-n
}
strs := make([]string, k)
for i := first; i <= last; i++ {
strs[i-first] = strconv.Itoa(i)
}
sort.Strings(strs)
ints := make([]int, k)
for i := 0; i < k; i++ {
ints[i], _ = strconv.Atoi(strs[i])
}
return ints
}
func main() {
fmt.Println("In lexicographical order:\n")
for _, n := range []int{0, 5, 13, 21, -22} {
fmt.Printf("%3d: %v\n", n, lexOrder(n))
}
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compareStrings(const void *a, const void *b) {
const char **aa = (const char **)a;
const char **bb = (const char **)b;
return strcmp(*aa, *bb);
}
void lexOrder(int n, int *ints) {
char **strs;
int i, first = 1, last = n, k = n, len;
if (n < 1) {
first = n; last = 1; k = 2 - n;
}
strs = malloc(k * sizeof(char *));
for (i = first; i <= last; ++i) {
if (i >= 1) len = (int)log10(i) + 2;
else if (i == 0) len = 2;
else len = (int)log10(-i) + 3;
strs[i-first] = malloc(len);
sprintf(strs[i-first], "%d", i);
}
qsort(strs, k, sizeof(char *), compareStrings);
for (i = 0; i < k; ++i) {
ints[i] = atoi(strs[i]);
free(strs[i]);
}
free(strs);
}
int main() {
int i, j, k, n, *ints;
int numbers[5] = {0, 5, 13, 21, -22};
printf("In lexicographical order:\n\n");
for (i = 0; i < 5; ++i) {
k = n = numbers[i];
if (k < 1) k = 2 - k;
ints = malloc(k * sizeof(int));
lexOrder(n, ints);
printf("%3d: [", n);
for (j = 0; j < k; ++j) {
printf("%d ", ints[j]);
}
printf("\b]\n");
free(ints);
}
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
| #include <stdio.h>
#include <string.h>
const char *ones[] = { 0, "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
const char *tens[] = { 0, "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
const char *llions[] = { 0, "thousand", "million", "billion", "trillion",
};
const int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;
int say_hundred(const char *s, int len, int depth, int has_lead)
{
int c[3], i;
for (i = -3; i < 0; i++) {
if (len + i >= 0) c[i + 3] = s[len + i] - '0';
else c[i + 3] = 0;
}
if (!(c[0] + c[1] + c[2])) return 0;
if (c[0]) {
printf("%s hundred", ones[c[0]]);
has_lead = 1;
}
if (has_lead && (c[1] || c[2]))
printf((!depth || c[0]) && (!c[0] || !c[1]) ? "and " :
c[0] ? " " : "");
if (c[1] < 2) {
if (c[1] || c[2]) printf("%s", ones[c[1] * 10 + c[2]]);
} else {
if (c[1]) {
printf("%s", tens[c[1]]);
if (c[2]) putchar('-');
}
if (c[2]) printf("%s", ones[c[2]]);
}
return 1;
}
int say_maxillion(const char *s, int len, int depth, int has_lead)
{
int n = len / 3, r = len % 3;
if (!r) {
n--;
r = 3;
}
const char *e = s + r;
do {
if (say_hundred(s, r, n, has_lead) && n) {
has_lead = 1;
printf(" %s", llions[n]);
if (!depth) printf(", ");
else printf(" ");
}
s = e; e += 3;
} while (r = 3, n--);
return 1;
}
void say_number(const char *s)
{
int len, i, got_sign = 0;
while (*s == ' ') s++;
if (*s < '0' || *s > '9') {
if (*s == '-') got_sign = -1;
else if (*s == '+') got_sign = 1;
else goto nan;
s++;
} else
got_sign = 1;
while (*s == '0') {
s++;
if (*s == '\0') {
printf("zero\n");
return;
}
}
len = strlen(s);
if (!len) goto nan;
for (i = 0; i < len; i++) {
if (s[i] < '0' || s[i] > '9') {
printf("(not a number)");
return;
}
}
if (got_sign == -1) printf("minus ");
int n = len / maxillion;
int r = len % maxillion;
if (!r) {
r = maxillion;
n--;
}
const char *end = s + len - n * maxillion;
int has_lead = 0;
do {
if ((has_lead = say_maxillion(s, r, n, has_lead))) {
for (i = 0; i < n; i++)
printf(" %s", llions[maxillion / 3]);
if (n) printf(", ");
}
n--;
r = maxillion;
s = end;
end += r;
} while (n >= 0);
printf("\n");
return;
nan: printf("not a number\n");
return;
}
int main()
{
say_number("-42");
say_number("1984");
say_number("10000");
say_number("1024");
say_number("1001001001001");
say_number("123456789012345678901234567890123456789012345678900000001");
return 0;
}
|
Produce a language-to-language conversion: from Go to C, same semantics. | package main
import (
"fmt"
"os"
"sort"
)
func main() {
if len(os.Args) == 1 {
compareStrings("abcd", "123456789", "abcdef", "1234567")
} else {
strings := os.Args[1:]
compareStrings(strings...)
}
}
func compareStrings(strings ...string) {
sort.SliceStable(strings, func(i, j int) bool {
return len(strings[i]) > len(strings[j])
})
for _, s := range strings {
fmt.Printf("%d: %s\n", len(s), s)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const int* a, const int* b)
{
return *b - *a;
}
void compareAndReportStringsLength(const char* strings[], const int n)
{
if (n > 0)
{
char* has_length = "has length";
char* predicate_max = "and is the longest string";
char* predicate_min = "and is the shortest string";
char* predicate_ave = "and is neither the longest nor the shortest string";
int* si = malloc(2 * n * sizeof(int));
if (si != NULL)
{
for (int i = 0; i < n; i++)
{
si[2 * i] = strlen(strings[i]);
si[2 * i + 1] = i;
}
qsort(si, n, 2 * sizeof(int), cmp);
int max = si[0];
int min = si[2 * (n - 1)];
for (int i = 0; i < n; i++)
{
int length = si[2 * i];
char* string = strings[si[2 * i + 1]];
char* predicate;
if (length == max)
predicate = predicate_max;
else if (length == min)
predicate = predicate_min;
else
predicate = predicate_ave;
printf("\"%s\" %s %d %s\n",
string, has_length, length, predicate);
}
free(si);
}
else
{
fputs("unable allocate memory buffer", stderr);
}
}
}
int main(int argc, char* argv[])
{
char* list[] = { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(list, 4);
return EXIT_SUCCESS;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {
for i := inc; i < len(a); i++ {
j, temp := i, a[i]
for ; j >= inc && a[j-inc] > temp; j -= inc {
a[j] = a[j-inc]
}
a[j] = temp
}
}
fmt.Println("after: ", a)
}
| #include <stdio.h>
void shell_sort (int *a, int n) {
int h, i, j, t;
for (h = n; h /= 2;) {
for (i = h; i < n; i++) {
t = a[i];
for (j = i; j >= h && t < a[j - h]; j -= h) {
a[j] = a[j - h];
}
a[j] = t;
}
}
}
int main (int ac, char **av) {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
shell_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | type dlNode struct {
int
next, prev *dlNode
}
type dlList struct {
members map[*dlNode]int
head, tail **dlNode
}
|
#include <stdio.h>
#include <stdlib.h>
struct List {
struct MNode *head;
struct MNode *tail;
struct MNode *tail_pred;
};
struct MNode {
struct MNode *succ;
struct MNode *pred;
};
typedef struct MNode *NODE;
typedef struct List *LIST;
LIST newList(void);
int isEmpty(LIST);
NODE getTail(LIST);
NODE getHead(LIST);
NODE addTail(LIST, NODE);
NODE addHead(LIST, NODE);
NODE remHead(LIST);
NODE remTail(LIST);
NODE insertAfter(LIST, NODE, NODE);
NODE removeNode(LIST, NODE);
LIST newList(void)
{
LIST tl = malloc(sizeof(struct List));
if ( tl != NULL )
{
tl->tail_pred = (NODE)&tl->head;
tl->tail = NULL;
tl->head = (NODE)&tl->tail;
return tl;
}
return NULL;
}
int isEmpty(LIST l)
{
return (l->head->succ == 0);
}
NODE getHead(LIST l)
{
return l->head;
}
NODE getTail(LIST l)
{
return l->tail_pred;
}
NODE addTail(LIST l, NODE n)
{
n->succ = (NODE)&l->tail;
n->pred = l->tail_pred;
l->tail_pred->succ = n;
l->tail_pred = n;
return n;
}
NODE addHead(LIST l, NODE n)
{
n->succ = l->head;
n->pred = (NODE)&l->head;
l->head->pred = n;
l->head = n;
return n;
}
NODE remHead(LIST l)
{
NODE h;
h = l->head;
l->head = l->head->succ;
l->head->pred = (NODE)&l->head;
return h;
}
NODE remTail(LIST l)
{
NODE t;
t = l->tail_pred;
l->tail_pred = l->tail_pred->pred;
l->tail_pred->succ = (NODE)&l->tail;
return t;
}
NODE insertAfter(LIST l, NODE r, NODE n)
{
n->pred = r; n->succ = r->succ;
n->succ->pred = n; r->succ = n;
return n;
}
NODE removeNode(LIST l, NODE n)
{
n->pred->succ = n->succ;
n->succ->pred = n->pred;
return n;
}
|
Translate the given Go code snippet into C without altering its behavior. | package main
import (
"fmt"
"io/ioutil"
"sort"
"unicode"
)
const file = "unixdict.txt"
func main() {
bs, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return
}
m := make(map[rune]int)
for _, r := range string(bs) {
m[r]++
}
lfs := make(lfList, 0, len(m))
for l, f := range m {
lfs = append(lfs, &letterFreq{l, f})
}
sort.Sort(lfs)
fmt.Println("file:", file)
fmt.Println("letter frequency")
for _, lf := range lfs {
if unicode.IsGraphic(lf.rune) {
fmt.Printf(" %c %7d\n", lf.rune, lf.freq)
} else {
fmt.Printf("%U %7d\n", lf.rune, lf.freq)
}
}
}
type letterFreq struct {
rune
freq int
}
type lfList []*letterFreq
func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
switch fd := lfs[i].freq - lfs[j].freq; {
case fd < 0:
return false
case fd > 0:
return true
}
return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
lfs[i], lfs[j] = lfs[j], lfs[i]
}
|
int frequency[26];
int ch;
FILE* txt_file = fopen ("a_text_file.txt", "rt");
for (ch = 0; ch < 26; ch++)
frequency[ch] = 0;
while (1) {
ch = fgetc(txt_file);
if (ch == EOF) break;
if ('a' <= ch && ch <= 'z')
frequency[ch-'a']++;
else if ('A' <= ch && ch <= 'Z')
frequency[ch-'A']++;
}
|
Maintain the same structure and functionality when rewriting this code in C. | package main
import "fmt"
var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}
var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
func main() {
all := make([]int, len(tr)+len(ct))
copy(all, tr)
copy(all[len(tr):], ct)
var sumAll int
for _, r := range all {
sumAll += r
}
sd := func(trc []int) int {
var sumTr int
for _, x := range trc {
sumTr += all[x]
}
return sumTr*len(ct) - (sumAll-sumTr)*len(tr)
}
a := make([]int, len(tr))
for i, _ := range a {
a[i] = i
}
sdObs := sd(a)
var nLe, nGt int
comb(len(all), len(tr), func(c []int) {
if sd(c) > sdObs {
nGt++
} else {
nLe++
}
})
pc := 100 / float64(nLe+nGt)
fmt.Printf("differences <= observed: %f%%\n", float64(nLe)*pc)
fmt.Printf("differences > observed: %f%%\n", float64(nGt)*pc)
}
func comb(n, m int, emit func([]int)) {
s := make([]int, m)
last := m - 1
var rc func(int, int)
rc = func(i, next int) {
for j := next; j < n; j++ {
s[i] = j
if i == last {
emit(s)
} else {
rc(i+1, j+1)
}
}
return
}
rc(0, 0)
}
| #include <stdio.h>
int data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int pick(int at, int remain, int accu, int treat)
{
if (!remain) return (accu > treat) ? 1 : 0;
return pick(at - 1, remain - 1, accu + data[at - 1], treat) +
( at > remain ? pick(at - 1, remain, accu, treat) : 0 );
}
int main()
{
int treat = 0, i;
int le, gt;
double total = 1;
for (i = 0; i < 9; i++) treat += data[i];
for (i = 19; i > 10; i--) total *= i;
for (i = 9; i > 0; i--) total /= i;
gt = pick(19, 9, 0, treat);
le = total - gt;
printf("<= : %f%% %d\n > : %f%% %d\n",
100 * le / total, le, 100 * gt / total, gt);
return 0;
}
|
Port the provided Go code into C while preserving the original functionality. | package main
import "fmt"
func möbius(to int) []int {
if to < 1 {
to = 1
}
mobs := make([]int, to+1)
primes := []int{2}
for i := 1; i <= to; i++ {
j := i
cp := 0
spf := false
for _, p := range primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes = append(primes, i)
}
if !spf {
if cp%2 == 0 {
mobs[i] = 1
} else {
mobs[i] = -1
}
}
}
return mobs
}
func main() {
mobs := möbius(199)
fmt.Println("Möbius sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
fmt.Print(" ")
continue
}
if i%20 == 0 {
fmt.Println()
}
fmt.Printf(" % d", mobs[i])
}
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const int MU_MAX = 1000000;
int i, j;
int *mu;
int sqroot;
sqroot = (int)sqrt(MU_MAX);
mu = malloc((MU_MAX + 1) * sizeof(int));
for (i = 0; i < MU_MAX;i++) {
mu[i] = 1;
}
for (i = 2; i <= sqroot; i++) {
if (mu[i] == 1) {
for (j = i; j <= MU_MAX; j += i) {
mu[j] *= -i;
}
for (j = i * i; j <= MU_MAX; j += i * i) {
mu[j] = 0;
}
}
}
for (i = 2; i <= MU_MAX; i++) {
if (mu[i] == i) {
mu[i] = 1;
} else if (mu[i] == -i) {
mu[i] = -1;
} else if (mu[i] < 0) {
mu[i] = 1;
} else if (mu[i] > 0) {
mu[i] = -1;
}
}
printf("First 199 terms of the möbius function are as follows:\n ");
for (i = 1; i < 200; i++) {
printf("%2d ", mu[i]);
if ((i + 1) % 20 == 0) {
printf("\n");
}
}
free(mu);
return 0;
}
|
Can you help me rewrite this code in C instead of Go, keeping it the same logically? | package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * incr(char *s)
{
int i, begin, tail, len;
int neg = (*s == '-');
char tgt = neg ? '0' : '9';
if (!strcmp(s, "-1")) {
s[0] = '0', s[1] = '\0';
return s;
}
len = strlen(s);
begin = (*s == '-' || *s == '+') ? 1 : 0;
for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);
if (tail < begin && !neg) {
if (!begin) s = realloc(s, len + 2);
s[0] = '1';
for (i = 1; i <= len - begin; i++) s[i] = '0';
s[len + 1] = '\0';
} else if (tail == begin && neg && s[1] == '1') {
for (i = 1; i < len - begin; i++) s[i] = '9';
s[len - 1] = '\0';
} else {
for (i = len - 1; i > tail; i--)
s[i] = neg ? '9' : '0';
s[tail] += neg ? -1 : 1;
}
return s;
}
void string_test(const char *s)
{
char *ret = malloc(strlen(s));
strcpy(ret, s);
printf("text: %s\n", ret);
printf(" ->: %s\n", ret = incr(ret));
free(ret);
}
int main()
{
string_test("+0");
string_test("-1");
string_test("-41");
string_test("+41");
string_test("999");
string_test("+999");
string_test("109999999999999999999999999999999999999999");
string_test("-100000000000000000000000000000000000000000000");
return 0;
}
|
Write a version of this Go function in C with identical behavior. | package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}
| #include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *strip_chars(const char *string, const char *chars)
{
char * newstr = malloc(strlen(string) + 1);
int counter = 0;
for ( ; *string; string++) {
if (!strchr(chars, *string)) {
newstr[ counter ] = *string;
++ counter;
}
}
newstr[counter] = 0;
return newstr;
}
int main(void)
{
char *new = strip_chars("She was a soul stripper. She took my heart!", "aei");
printf("%s\n", new);
free(new);
return 0;
}
|
Change the following Go code into C without altering its purpose. | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
if len(a) > 1 && !recurse(len(a) - 1) {
panic("sorted permutation not found!")
}
fmt.Println("after: ", a)
}
func recurse(last int) bool {
if last <= 0 {
for i := len(a) - 1; a[i] >= a[i-1]; i-- {
if i == 1 {
return true
}
}
return false
}
for i := 0; i <= last; i++ {
a[i], a[last] = a[last], a[i]
if recurse(last - 1) {
return true
}
a[i], a[last] = a[last], a[i]
}
return false
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int(*cmp_func)(const void*, const void*);
void perm_sort(void *a, int n, size_t msize, cmp_func _cmp)
{
char *p, *q, *tmp = malloc(msize);
# define A(i) ((char *)a + msize * (i))
# define swap(a, b) {\
memcpy(tmp, a, msize);\
memcpy(a, b, msize);\
memcpy(b, tmp, msize); }
while (1) {
for (p = A(n - 1); (void*)p > a; p = q)
if (_cmp(q = p - msize, p) > 0)
break;
if ((void*)p <= a) break;
for (p = A(n - 1); p > q; p-= msize)
if (_cmp(q, p) > 0) break;
swap(p, q);
for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)
swap(p, q);
}
free(tmp);
}
int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }
int main()
{
int i;
const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" };
perm_sort(strs, 5, sizeof(*strs), scmp);
for (i = 0; i < 5; i++)
printf("%s\n", strs[i]);
return 0;
}
|
Write the same algorithm in C as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{},
[]float64{math.Inf(1), math.Inf(1)},
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}
| #include <stdio.h>
double mean(double *v, int len)
{
double sum = 0;
int i;
for (i = 0; i < len; i++)
sum += v[i];
return sum / len;
}
int main(void)
{
double v[] = {1, 2, 2.718, 3, 3.142};
int i, len;
for (len = 5; len >= 0; len--) {
printf("mean[");
for (i = 0; i < len; i++)
printf(i ? ", %g" : "%g", v[i]);
printf("] = %g\n", mean(v, len));
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Go snippet. | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
| #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = word_len;
new_cmd->cmd = uppercase(word, word_len);
if (i + 1 < count) {
char* eptr = 0;
unsigned long min_len = strtoul(words[i + 1], &eptr, 10);
if (min_len > 0 && *eptr == 0) {
free(words[i + 1]);
new_cmd->min_len = min_len;
++i;
}
}
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Go. | package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
| #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = word_len;
new_cmd->cmd = uppercase(word, word_len);
if (i + 1 < count) {
char* eptr = 0;
unsigned long min_len = strtoul(words[i + 1], &eptr, 10);
if (min_len > 0 && *eptr == 0) {
free(words[i + 1]);
new_cmd->min_len = min_len;
++i;
}
}
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
Produce a functionally identical C code for the snippet given in Go. | package main
import (
"fmt"
"math"
"strings"
)
func main(){
fmt.Println(H("1223334444"))
}
func H(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#define MAXLEN 100
int makehist(unsigned char *S,int *hist,int len){
int wherechar[256];
int i,histlen;
histlen=0;
for(i=0;i<256;i++)wherechar[i]=-1;
for(i=0;i<len;i++){
if(wherechar[(int)S[i]]==-1){
wherechar[(int)S[i]]=histlen;
histlen++;
}
hist[wherechar[(int)S[i]]]++;
}
return histlen;
}
double entropy(int *hist,int histlen,int len){
int i;
double H;
H=0;
for(i=0;i<histlen;i++){
H-=(double)hist[i]/len*log2((double)hist[i]/len);
}
return H;
}
int main(void){
unsigned char S[MAXLEN];
int len,*hist,histlen;
double H;
scanf("%[^\n]",S);
len=strlen(S);
hist=(int*)calloc(len,sizeof(int));
histlen=makehist(S,hist,len);
H=entropy(hist,histlen,len);
printf("%lf\n",H);
return 0;
}
|
Port the following code from Go to C with equivalent syntax and logic. | package main
import (
"errors"
"fmt"
)
func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
for _, r := range s {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, r)
case r == escape:
inEscape = true
case r == sep:
tokens = append(tokens, string(runes))
runes = runes[:0]
}
}
tokens = append(tokens, string(runes))
if inEscape {
err = errors.New("invalid terminal escape")
}
return tokens, err
}
func main() {
const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
const separator = '|'
const escape = '^'
fmt.Printf("Input: %q\n", sample)
tokens, err := TokenizeString(sample, separator, escape)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Printf("Tokens: %q\n", tokens)
}
}
| #include <stdlib.h>
#include <stdio.h>
#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'
typedef char* Str;
unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );
int main() {
char s[] = STR_DEMO;
unsigned int i, q;
Str *list = Tokenize( s, SEP, ESC, &q );
if( list != NULL ) {
printf( "\n Original string: %s\n\n", STR_DEMO );
printf( " %d tokens:\n\n", q );
for( i=0; i<q; ++i )
printf( " %4d. %s\n", i+1, list[i] );
free( list );
}
return 0;
}
unsigned int ElQ( const char *s, char sep, char esc ) {
unsigned int q, e;
const char *p;
for( e=0, q=1, p=s; *p; ++p ) {
if( *p == esc )
e = !e;
else if( *p == sep )
q += !e;
else e = 0;
}
return q;
}
Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
Str *list = NULL;
*q = ElQ( s, sep, esc );
list = malloc( *q * sizeof(Str) );
if( list != NULL ) {
unsigned int e, i;
char *p;
i = 0;
list[i++] = s;
for( e=0, p=s; *p; ++p ) {
if( *p == esc ) {
e = !e;
}
else if( *p == sep && !e ) {
list[i++] = p+1;
*p = '\0';
}
else {
e = 0;
}
}
}
return list;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.