Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this C function in Go with identical behavior. | #include <stdio.h>
#include <string.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
bool is_prime(ull n) {
ull d;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
d = 5;
while (d * d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
void ord(char *res, int n) {
char suffix[3];
int m = n % 100;
if (m >= 4 && m <= 20) {
sprintf(res,"%dth", n);
return;
}
switch(m % 10) {
case 1:
strcpy(suffix, "st");
break;
case 2:
strcpy(suffix, "nd");
break;
case 3:
strcpy(suffix, "rd");
break;
default:
strcpy(suffix, "th");
break;
}
sprintf(res, "%d%s", n, suffix);
}
bool is_magnanimous(ull n) {
ull p, q, r;
if (n < 10) return TRUE;
for (p = 10; ; p *= 10) {
q = n / p;
r = n % p;
if (!is_prime(q + r)) return FALSE;
if (q < 10) break;
}
return TRUE;
}
void list_mags(int from, int thru, int digs, int per_line) {
ull i = 0;
int c = 0;
char res1[13], res2[13];
if (from < 2) {
printf("\nFirst %d magnanimous numbers:\n", thru);
} else {
ord(res1, from);
ord(res2, thru);
printf("\n%s through %s magnanimous numbers:\n", res1, res2);
}
for ( ; c < thru; ++i) {
if (is_magnanimous(i)) {
if (++c >= from) {
printf("%*llu ", digs, i);
if (!(c % per_line)) printf("\n");
}
}
}
}
int main() {
list_mags(1, 45, 3, 15);
list_mags(241, 250, 1, 10);
list_mags(391, 400, 1, 10);
return 0;
}
| package main
import "fmt"
func isPrime(n uint64) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint64(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func ord(n int) string {
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%dth", n)
}
m %= 10
suffix := "th"
if m < 4 {
switch m {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
}
}
return fmt.Sprintf("%d%s", n, suffix)
}
func isMagnanimous(n uint64) bool {
if n < 10 {
return true
}
for p := uint64(10); ; p *= 10 {
q := n / p
r := n % p
if !isPrime(q + r) {
return false
}
if q < 10 {
break
}
}
return true
}
func listMags(from, thru, digs, perLine int) {
if from < 2 {
fmt.Println("\nFirst", thru, "magnanimous numbers:")
} else {
fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru))
}
for i, c := uint64(0), 0; c < thru; i++ {
if isMagnanimous(i) {
c++
if c >= from {
fmt.Printf("%*d ", digs, i)
if c%perLine == 0 {
fmt.Println()
}
}
}
}
}
func main() {
listMags(1, 45, 3, 15)
listMags(241, 250, 1, 10)
listMags(391, 400, 1, 10)
}
|
Convert the following code from C to Go, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define CHUNK_BYTES (32 << 8)
#define CHUNK_SIZE (CHUNK_BYTES << 6)
int field[CHUNK_BYTES];
#define GET(x) (field[(x)>>6] & 1<<((x)>>1&31))
#define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))
typedef unsigned uint;
typedef struct {
uint *e;
uint cap, len;
} uarray;
uarray primes, offset;
void push(uarray *a, uint n)
{
if (a->len >= a->cap) {
if (!(a->cap *= 2)) a->cap = 16;
a->e = realloc(a->e, sizeof(uint) * a->cap);
}
a->e[a->len++] = n;
}
uint low;
void init(void)
{
uint p, q;
unsigned char f[1<<16];
memset(f, 0, sizeof(f));
push(&primes, 2);
push(&offset, 0);
for (p = 3; p < 1<<16; p += 2) {
if (f[p]) continue;
for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1;
push(&primes, p);
push(&offset, q);
}
low = 1<<16;
}
void sieve(void)
{
uint i, p, q, hi, ptop;
if (!low) init();
memset(field, 0, sizeof(field));
hi = low + CHUNK_SIZE;
ptop = sqrt(hi) * 2 + 1;
for (i = 1; (p = primes.e[i]*2) < ptop; i++) {
for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p)
SET(q);
offset.e[i] = q + low;
}
for (p = 1; p < CHUNK_SIZE; p += 2)
if (!GET(p)) push(&primes, low + p);
low = hi;
}
int main(void)
{
uint i, p, c;
while (primes.len < 20) sieve();
printf("First 20:");
for (i = 0; i < 20; i++)
printf(" %u", primes.e[i]);
putchar('\n');
while (primes.e[primes.len-1] < 150) sieve();
printf("Between 100 and 150:");
for (i = 0; i < primes.len; i++) {
if ((p = primes.e[i]) >= 100 && p < 150)
printf(" %u", primes.e[i]);
}
putchar('\n');
while (primes.e[primes.len-1] < 8000) sieve();
for (i = c = 0; i < primes.len; i++)
if ((p = primes.e[i]) >= 7700 && p < 8000) c++;
printf("%u primes between 7700 and 8000\n", c);
for (c = 10; c <= 100000000; c *= 10) {
while (primes.len < c) sieve();
printf("%uth prime: %u\n", c, primes.e[c-1]);
}
return 0;
}
| package main
import (
"container/heap"
"fmt"
)
func main() {
p := newP()
fmt.Print("First twenty: ")
for i := 0; i < 20; i++ {
fmt.Print(p(), " ")
}
fmt.Print("\nBetween 100 and 150: ")
n := p()
for n <= 100 {
n = p()
}
for ; n < 150; n = p() {
fmt.Print(n, " ")
}
for n <= 7700 {
n = p()
}
c := 0
for ; n < 8000; n = p() {
c++
}
fmt.Println("\nNumber beween 7,700 and 8,000:", c)
p = newP()
for i := 1; i < 10000; i++ {
p()
}
fmt.Println("10,000th prime:", p())
}
func newP() func() int {
n := 1
var pq pQueue
top := &pMult{2, 4, 0}
return func() int {
for {
n++
if n < top.pMult {
heap.Push(&pq, &pMult{prime: n, pMult: n * n})
top = pq[0]
return n
}
for top.pMult == n {
top.pMult += top.prime
heap.Fix(&pq, 0)
top = pq[0]
}
}
}
}
type pMult struct {
prime int
pMult int
index int
}
type pQueue []*pMult
func (q pQueue) Len() int { return len(q) }
func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }
func (q pQueue) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
q[i].index = i
q[j].index = j
}
func (p *pQueue) Push(x interface{}) {
q := *p
e := x.(*pMult)
e.index = len(q)
*p = append(q, e)
}
func (p *pQueue) Pop() interface{} {
q := *p
last := len(q) - 1
e := q[last]
*p = q[:last]
return e
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <stdio.h>
#include <stdlib.h>
#define LEN 3
int rand_idx(double *p, int n)
{
double s = rand() / (RAND_MAX + 1.0);
int i;
for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
return i;
}
int main()
{
int user_action, my_action;
int user_rec[] = {0, 0, 0};
const char *names[] = { "Rock", "Paper", "Scissors" };
char str[2];
const char *winner[] = { "We tied.", "Meself winned.", "You win." };
double p[LEN] = { 1./3, 1./3, 1./3 };
while (1) {
my_action = rand_idx(p,LEN);
printf("\nYour choice [1-3]:\n"
" 1. Rock\n 2. Paper\n 3. Scissors\n> ");
if (!scanf("%d", &user_action)) {
scanf("%1s", str);
if (*str == 'q') {
printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]);
return 0;
}
continue;
}
user_action --;
if (user_action > 2 || user_action < 0) {
printf("invalid choice; again\n");
continue;
}
printf("You chose %s; I chose %s. %s\n",
names[user_action], names[my_action],
winner[(my_action - user_action + 3) % 3]);
user_rec[user_action]++;
}
}
| package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
|
Write the same algorithm in Go as shown in this C implementation. | #include <stdio.h>
#include <stdlib.h>
#define LEN 3
int rand_idx(double *p, int n)
{
double s = rand() / (RAND_MAX + 1.0);
int i;
for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
return i;
}
int main()
{
int user_action, my_action;
int user_rec[] = {0, 0, 0};
const char *names[] = { "Rock", "Paper", "Scissors" };
char str[2];
const char *winner[] = { "We tied.", "Meself winned.", "You win." };
double p[LEN] = { 1./3, 1./3, 1./3 };
while (1) {
my_action = rand_idx(p,LEN);
printf("\nYour choice [1-3]:\n"
" 1. Rock\n 2. Paper\n 3. Scissors\n> ");
if (!scanf("%d", &user_action)) {
scanf("%1s", str);
if (*str == 'q') {
printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]);
return 0;
}
continue;
}
user_action --;
if (user_action > 2 || user_action < 0) {
printf("invalid choice; again\n");
continue;
}
printf("You chose %s; I chose %s. %s\n",
names[user_action], names[my_action],
winner[(my_action - user_action + 3) % 3]);
user_rec[user_action]++;
}
}
| package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C version. | #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C version. | #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Write a version of this C function in Go with identical behavior. | #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
| package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
|
Change the programming language of this snippet from C to Go without modifying what it does. | #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
| package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG"
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ"
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS"
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT"
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST"
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH"
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV"
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW"
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO"
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR"
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX"
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB"
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA"
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK";
const double freq[] = {
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074
};
int best_match(const double *a, const double *b) {
double sum = 0, fit, d, best_fit = 1e100;
int i, rotate, best_rotate = 0;
for (i = 0; i < 26; i++)
sum += a[i];
for (rotate = 0; rotate < 26; rotate++) {
fit = 0;
for (i = 0; i < 26; i++) {
d = a[(i + rotate) % 26] / sum - b[i];
fit += d * d / b[i];
}
if (fit < best_fit) {
best_fit = fit;
best_rotate = rotate;
}
}
return best_rotate;
}
double freq_every_nth(const int *msg, int len, int interval, char *key) {
double sum, d, ret;
double out[26], accu[26] = {0};
int i, j, rot;
for (j = 0; j < interval; j++) {
for (i = 0; i < 26; i++)
out[i] = 0;
for (i = j; i < len; i += interval)
out[msg[i]]++;
key[j] = rot = best_match(out, freq);
key[j] += 'A';
for (i = 0; i < 26; i++)
accu[i] += out[(i + rot) % 26];
}
for (i = 0, sum = 0; i < 26; i++)
sum += accu[i];
for (i = 0, ret = 0; i < 26; i++) {
d = accu[i] / sum - freq[i];
ret += d * d / freq[i];
}
key[interval] = '\0';
return ret;
}
int main() {
int txt[strlen(encoded)];
int len = 0, j;
char key[100];
double fit, best_fit = 1e100;
for (j = 0; encoded[j] != '\0'; j++)
if (isupper(encoded[j]))
txt[len++] = encoded[j] - 'A';
for (j = 1; j < 30; j++) {
fit = freq_every_nth(txt, len, j, key);
printf("%f, key length: %2d, %s", fit, j, key);
if (fit < best_fit) {
best_fit = fit;
printf(" <--- best so far");
}
printf("\n");
}
return 0;
}
| package main
import (
"fmt"
"strings"
)
var encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" +
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" +
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" +
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" +
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" +
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" +
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" +
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" +
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" +
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" +
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" +
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" +
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" +
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" +
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" +
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK"
var freq = [26]float64{
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074,
}
func sum(a []float64) (sum float64) {
for _, f := range a {
sum += f
}
return
}
func bestMatch(a []float64) int {
sum := sum(a)
bestFit, bestRotate := 1e100, 0
for rotate := 0; rotate < 26; rotate++ {
fit := 0.0
for i := 0; i < 26; i++ {
d := a[(i+rotate)%26]/sum - freq[i]
fit += d * d / freq[i]
}
if fit < bestFit {
bestFit, bestRotate = fit, rotate
}
}
return bestRotate
}
func freqEveryNth(msg []int, key []byte) float64 {
l := len(msg)
interval := len(key)
out := make([]float64, 26)
accu := make([]float64, 26)
for j := 0; j < interval; j++ {
for k := 0; k < 26; k++ {
out[k] = 0.0
}
for i := j; i < l; i += interval {
out[msg[i]]++
}
rot := bestMatch(out)
key[j] = byte(rot + 65)
for i := 0; i < 26; i++ {
accu[i] += out[(i+rot)%26]
}
}
sum := sum(accu)
ret := 0.0
for i := 0; i < 26; i++ {
d := accu[i]/sum - freq[i]
ret += d * d / freq[i]
}
return ret
}
func decrypt(text, key string) string {
var sb strings.Builder
ki := 0
for _, c := range text {
if c < 'A' || c > 'Z' {
continue
}
ci := (c - rune(key[ki]) + 26) % 26
sb.WriteRune(ci + 65)
ki = (ki + 1) % len(key)
}
return sb.String()
}
func main() {
enc := strings.Replace(encoded, " ", "", -1)
txt := make([]int, len(enc))
for i := 0; i < len(txt); i++ {
txt[i] = int(enc[i] - 'A')
}
bestFit, bestKey := 1e100, ""
fmt.Println(" Fit Length Key")
for j := 1; j <= 26; j++ {
key := make([]byte, j)
fit := freqEveryNth(txt, key)
sKey := string(key)
fmt.Printf("%f %2d %s", fit, j, sKey)
if fit < bestFit {
bestFit, bestKey = fit, sKey
fmt.Print(" <--- best so far")
}
fmt.Println()
}
fmt.Println("\nBest key :", bestKey)
fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey))
}
|
Convert this C snippet to Go and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
got -= 2;
while (s[got] == '0' || s[got] == '9') got--;
printf("%.*s", (int)(got - done), s + done);
free(s);
done = got;
accu *= 2;
}
return 0;
}
| package main
import (
"fmt"
"math/big"
)
type lft struct {
q,r,s,t big.Int
}
func (t *lft) extr(x *big.Int) *big.Rat {
var n, d big.Int
var r big.Rat
return r.SetFrac(
n.Add(n.Mul(&t.q, x), &t.r),
d.Add(d.Mul(&t.s, x), &t.t))
}
var three = big.NewInt(3)
var four = big.NewInt(4)
func (t *lft) next() *big.Int {
r := t.extr(three)
var f big.Int
return f.Div(r.Num(), r.Denom())
}
func (t *lft) safe(n *big.Int) bool {
r := t.extr(four)
var f big.Int
if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
return true
}
return false
}
func (t *lft) comp(u *lft) *lft {
var r lft
var a, b big.Int
r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))
r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))
r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))
r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))
return &r
}
func (t *lft) prod(n *big.Int) *lft {
var r lft
r.q.SetInt64(10)
r.r.Mul(r.r.SetInt64(-10), n)
r.t.SetInt64(1)
return r.comp(t)
}
func main() {
z := new(lft)
z.q.SetInt64(1)
z.t.SetInt64(1)
var k int64
lfts := func() *lft {
k++
r := new(lft)
r.q.SetInt64(k)
r.r.SetInt64(4*k+2)
r.t.SetInt64(2*k+1)
return r
}
for {
y := z.next()
if z.safe(y) {
fmt.Print(y)
z = z.prod(y)
} else {
z = z.comp(lfts())
}
}
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
#define N 100000
int main()
{
int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;
q[1] = q[2] = 1;
for (i = 3; i <= N; i++)
q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
for (i = 1; i <= 10; i++)
printf("%d%c", q[i], i == 10 ? '\n' : ' ');
printf("%d\n", q[1000]);
for (flip = 0, i = 1; i < N; i++)
flip += q[i] > q[i + 1];
printf("flips: %d\n", flip);
return 0;
}
| package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
showQ(n)
}
showQ(1000)
count, p := 0, 1
for n := 2; n <= 1e5; n++ {
qn := q(n)
if qn < p {
count++
}
p = qn
}
fmt.Println("count:", count)
initMap()
showQ(1e6)
}
func showQ(n int) {
fmt.Printf("Q(%d) = %d\n", n, q(n))
}
|
Change the programming language of this snippet from C to Go without modifying what it does. | #include <stdio.h>
#include <stdlib.h>
#define N 100000
int main()
{
int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;
q[1] = q[2] = 1;
for (i = 3; i <= N; i++)
q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
for (i = 1; i <= 10; i++)
printf("%d%c", q[i], i == 10 ? '\n' : ' ');
printf("%d\n", q[1000]);
for (flip = 0, i = 1; i < N; i++)
flip += q[i] > q[i + 1];
printf("flips: %d\n", flip);
return 0;
}
| package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
showQ(n)
}
showQ(1000)
count, p := 0, 1
for n := 2; n <= 1e5; n++ {
qn := q(n)
if qn < p {
count++
}
p = qn
}
fmt.Println("count:", count)
initMap()
showQ(1e6)
}
func showQ(n int) {
fmt.Printf("Q(%d) = %d\n", n, q(n))
}
|
Translate this program into Go but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, func);
func _;
int num;
} func_t;
func new(func(*f)(func, func), func _) {
func x = malloc(sizeof(func_t));
x->fn = f;
x->_ = _;
x->num = 0;
return x;
}
func call(func f, func n) {
return f->fn(f, n);
}
func Y(func(*f)(func, func)) {
func g = new(f, 0);
g->_ = g;
return g;
}
func num(int n) {
func x = new(0, 0);
x->num = n;
return x;
}
func fac(func self, func n) {
int nn = n->num;
return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num)
: num(1);
}
func fib(func self, func n) {
int nn = n->num;
return nn > 1
? num( call(self->_, num(nn - 1))->num +
call(self->_, num(nn - 2))->num )
: num(1);
}
void show(func n) { printf(" %d", n->num); }
int main() {
int i;
func f = Y(fac);
printf("fac: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
f = Y(fib);
printf("fib: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
return 0;
}
| package main
import "fmt"
type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func
func main() {
fac := Y(almost_fac)
fib := Y(almost_fib)
fmt.Println("fac(10) = ", fac(10))
fmt.Println("fib(10) = ", fib(10))
}
func Y(f FuncFunc) Func {
g := func(r RecursiveFunc) Func {
return f(func(x int) int {
return r(r)(x)
})
}
return g(g)
}
func almost_fac(f Func) Func {
return func(x int) int {
if x <= 1 {
return 1
}
return x * f(x-1)
}
}
func almost_fib(f Func) Func {
return func(x int) int {
if x <= 2 {
return 1
}
return f(x-1)+f(x-2)
}
}
|
Write the same algorithm in Go as shown in this C implementation. | #include<stdio.h>
typedef struct{
int integer;
float decimal;
char letter;
char string[100];
double bigDecimal;
}Composite;
Composite example()
{
Composite C = {1, 2.3, 'a', "Hello World", 45.678};
return C;
}
int main()
{
Composite C = example();
printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);
return 0;
}
| func addsub(x, y int) (int, int) {
return x + y, x - y
}
|
Produce a language-to-language conversion: from C to Go, same semantics. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| package main
import "fmt"
func main() {
const max = 1000
a := make([]int, max)
for n := 0; n < max-1; n++ {
for m := n - 1; m >= 0; m-- {
if a[m] == a[n] {
a[n+1] = n - m
break
}
}
}
fmt.Println("The first ten terms of the Van Eck sequence are:")
fmt.Println(a[:10])
fmt.Println("\nTerms 991 to 1000 of the sequence are:")
fmt.Println(a[990:])
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C version. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| package main
import "fmt"
func main() {
const max = 1000
a := make([]int, max)
for n := 0; n < max-1; n++ {
for m := n - 1; m >= 0; m-- {
if a[m] == a[n] {
a[n+1] = n - m
break
}
}
}
fmt.Println("The first ten terms of the Van Eck sequence are:")
fmt.Println(a[:10])
fmt.Println("\nTerms 991 to 1000 of the sequence are:")
fmt.Println(a[990:])
}
|
Please provide an equivalent version of this C code in Go. | #include <ftplib.h>
int main(void)
{
netbuf *nbuf;
FtpInit();
FtpConnect("kernel.org", &nbuf);
FtpLogin("anonymous", "", nbuf);
FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);
FtpChdir("pub/linux/kernel", nbuf);
FtpDir((void*)0, ".", nbuf);
FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf);
FtpQuit(nbuf);
return 0;
}
| package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Quit()
fmt.Println(conn)
if err = conn.Login(username, password); err != nil {
log.Fatal(err)
}
if err = conn.ChangeDir(dir); err != nil {
log.Fatal(err)
}
fmt.Println(conn.CurrentDir())
files, err := conn.List(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
}
r, err := conn.Retr(file)
if err != nil {
log.Fatal(err)
}
defer r.Close()
f, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
n, err := io.Copy(f, r)
if err != nil {
log.Fatal(err)
}
fmt.Println("Wrote", n, "bytes to", file)
}
|
Rewrite the snippet below in Go so it works the same as the original C code. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t digits[N_DIGITS];
void gen_digits()
{
int i;
for (i = 0; i < N_DIGITS; i++)
digits[i].val = 1 + rand() % 9;
}
#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;
#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;
void reset()
{
int i;
msg = 0;
pool_ptr = pos = 0;
for (i = 0; i < POOL_SIZE; i++) {
pool[i].op = OP_NONE;
pool[i].left = pool[i].right = 0;
}
for (i = 0; i < N_DIGITS; i++)
digits[i].used = 0;
}
void bail(const char *s)
{
msg = s;
longjmp(ctx, 1);
}
expr new_expr()
{
if (pool_ptr < POOL_SIZE)
return pool + pool_ptr++;
return 0;
}
int next_tok()
{
while (isspace(str[pos])) pos++;
return str[pos];
}
int take()
{
if (str[pos] != '\0') return ++pos;
return 0;
}
expr get_fact();
expr get_term();
expr get_expr();
expr get_expr()
{
int c;
expr l, r, ret;
if (!(ret = get_term())) bail("Expected term");
while ((c = next_tok()) == '+' || c == '-') {
if (!take()) bail("Unexpected end of input");
if (!(r = get_term())) bail("Expected term");
l = ret;
ret = new_expr();
ret->op = (c == '+') ? OP_ADD : OP_SUB;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_term()
{
int c;
expr l, r, ret;
ret = get_fact();
while((c = next_tok()) == '*' || c == '/') {
if (!take()) bail("Unexpected end of input");
r = get_fact();
l = ret;
ret = new_expr();
ret->op = (c == '*') ? OP_MUL : OP_DIV;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_digit()
{
int i, c = next_tok();
expr ret;
if (c >= '0' && c <= '9') {
take();
ret = new_expr();
ret->op = OP_NUM;
ret->val = c - '0';
for (i = 0; i < N_DIGITS; i++)
if (digits[i].val == ret->val && !digits[i].used) {
digits[i].used = 1;
return ret;
}
bail("Invalid digit");
}
return 0;
}
expr get_fact()
{
int c;
expr l = get_digit();
if (l) return l;
if ((c = next_tok()) == '(') {
take();
l = get_expr();
if (next_tok() != ')') bail("Unbalanced parens");
take();
return l;
}
return 0;
}
expr parse()
{
int i;
expr ret = get_expr();
if (next_tok() != '\0')
bail("Trailing garbage");
for (i = 0; i < N_DIGITS; i++)
if (!digits[i].used)
bail("Not all digits are used");
return ret;
}
typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };
int gcd(int m, int n)
{
int t;
while (m) {
t = m; m = n % m; n = t;
}
return n;
}
void eval_tree(expr e, frac res)
{
frac_t l, r;
int t;
if (e->op == OP_NUM) {
res->num = e->val;
res->denom = 1;
return;
}
eval_tree(e->left, &l);
eval_tree(e->right, &r);
switch(e->op) {
case OP_ADD:
res->num = l.num * r.denom + l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_SUB:
res->num = l.num * r.denom - l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_MUL:
res->num = l.num * r.num;
res->denom = l.denom * r.denom;
break;
case OP_DIV:
res->num = l.num * r.denom;
res->denom = l.denom * r.num;
break;
}
if ((t = gcd(res->denom, res->num))) {
res->denom /= t;
res->num /= t;
}
}
void get_input()
{
int i;
reinput:
reset();
printf("\nAvailable digits are:");
for (i = 0; i < N_DIGITS; i++)
printf(" %d", digits[i].val);
printf(". Type an expression and I'll check it for you, or make new numbers.\n"
"Your choice? [Expr/n/q] ");
while (1) {
for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
fgets(str, MAX_INPUT, stdin);
if (*str == '\0') goto reinput;
if (str[MAX_INPUT - 1] != '\n')
bail("string too long");
for (i = 0; i < MAX_INPUT; i++)
if (str[i] == '\n') str[i] = '\0';
if (str[0] == 'q') {
printf("Bye\n");
exit(0);
}
if (str[0] == 'n') {
gen_digits();
goto reinput;
}
return;
}
}
int main()
{
frac_t f;
srand(time(0));
gen_digits();
while(1) {
get_input();
setjmp(ctx);
if (msg) {
printf("%s at '%.*s'\n", msg, pos, str);
continue;
}
eval_tree(parse(), &f);
if (f.denom == 0) bail("Divide by zero");
if (f.denom == 1 && f.num == 24)
printf("You got 24. Very good.\n");
else {
if (f.denom == 1)
printf("Eval to: %d, ", f.num);
else
printf("Eval to: %d/%d, ", f.num, f.denom);
printf("no good. Try again.\n");
}
}
return 0;
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Generate a Go translation of this C snippet without changing its computational steps. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t digits[N_DIGITS];
void gen_digits()
{
int i;
for (i = 0; i < N_DIGITS; i++)
digits[i].val = 1 + rand() % 9;
}
#define MAX_INPUT 64
char str[MAX_INPUT];
int pos;
#define POOL_SIZE 8
expr_t pool[POOL_SIZE];
int pool_ptr;
void reset()
{
int i;
msg = 0;
pool_ptr = pos = 0;
for (i = 0; i < POOL_SIZE; i++) {
pool[i].op = OP_NONE;
pool[i].left = pool[i].right = 0;
}
for (i = 0; i < N_DIGITS; i++)
digits[i].used = 0;
}
void bail(const char *s)
{
msg = s;
longjmp(ctx, 1);
}
expr new_expr()
{
if (pool_ptr < POOL_SIZE)
return pool + pool_ptr++;
return 0;
}
int next_tok()
{
while (isspace(str[pos])) pos++;
return str[pos];
}
int take()
{
if (str[pos] != '\0') return ++pos;
return 0;
}
expr get_fact();
expr get_term();
expr get_expr();
expr get_expr()
{
int c;
expr l, r, ret;
if (!(ret = get_term())) bail("Expected term");
while ((c = next_tok()) == '+' || c == '-') {
if (!take()) bail("Unexpected end of input");
if (!(r = get_term())) bail("Expected term");
l = ret;
ret = new_expr();
ret->op = (c == '+') ? OP_ADD : OP_SUB;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_term()
{
int c;
expr l, r, ret;
ret = get_fact();
while((c = next_tok()) == '*' || c == '/') {
if (!take()) bail("Unexpected end of input");
r = get_fact();
l = ret;
ret = new_expr();
ret->op = (c == '*') ? OP_MUL : OP_DIV;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_digit()
{
int i, c = next_tok();
expr ret;
if (c >= '0' && c <= '9') {
take();
ret = new_expr();
ret->op = OP_NUM;
ret->val = c - '0';
for (i = 0; i < N_DIGITS; i++)
if (digits[i].val == ret->val && !digits[i].used) {
digits[i].used = 1;
return ret;
}
bail("Invalid digit");
}
return 0;
}
expr get_fact()
{
int c;
expr l = get_digit();
if (l) return l;
if ((c = next_tok()) == '(') {
take();
l = get_expr();
if (next_tok() != ')') bail("Unbalanced parens");
take();
return l;
}
return 0;
}
expr parse()
{
int i;
expr ret = get_expr();
if (next_tok() != '\0')
bail("Trailing garbage");
for (i = 0; i < N_DIGITS; i++)
if (!digits[i].used)
bail("Not all digits are used");
return ret;
}
typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };
int gcd(int m, int n)
{
int t;
while (m) {
t = m; m = n % m; n = t;
}
return n;
}
void eval_tree(expr e, frac res)
{
frac_t l, r;
int t;
if (e->op == OP_NUM) {
res->num = e->val;
res->denom = 1;
return;
}
eval_tree(e->left, &l);
eval_tree(e->right, &r);
switch(e->op) {
case OP_ADD:
res->num = l.num * r.denom + l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_SUB:
res->num = l.num * r.denom - l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_MUL:
res->num = l.num * r.num;
res->denom = l.denom * r.denom;
break;
case OP_DIV:
res->num = l.num * r.denom;
res->denom = l.denom * r.num;
break;
}
if ((t = gcd(res->denom, res->num))) {
res->denom /= t;
res->num /= t;
}
}
void get_input()
{
int i;
reinput:
reset();
printf("\nAvailable digits are:");
for (i = 0; i < N_DIGITS; i++)
printf(" %d", digits[i].val);
printf(". Type an expression and I'll check it for you, or make new numbers.\n"
"Your choice? [Expr/n/q] ");
while (1) {
for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
fgets(str, MAX_INPUT, stdin);
if (*str == '\0') goto reinput;
if (str[MAX_INPUT - 1] != '\n')
bail("string too long");
for (i = 0; i < MAX_INPUT; i++)
if (str[i] == '\n') str[i] = '\0';
if (str[0] == 'q') {
printf("Bye\n");
exit(0);
}
if (str[0] == 'n') {
gen_digits();
goto reinput;
}
return;
}
}
int main()
{
frac_t f;
srand(time(0));
gen_digits();
while(1) {
get_input();
setjmp(ctx);
if (msg) {
printf("%s at '%.*s'\n", msg, pos, str);
continue;
}
eval_tree(parse(), &f);
if (f.denom == 0) bail("Divide by zero");
if (f.denom == 1 && f.num == 24)
printf("You got 24. Very good.\n");
else {
if (f.denom == 1)
printf("Eval to: %d, ", f.num);
else
printf("Eval to: %d/%d, ", f.num, f.denom);
printf("no good. Try again.\n");
}
}
return 0;
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Ensure the translated Go code behaves exactly like the original C snippet. | for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
| package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Port the following code from C to Go with equivalent syntax and logic. | #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Ensure the translated Go code behaves exactly like the original C snippet. | #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Translate this program into Go but keep the logic exactly as in C. | #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
gotoxy(1+colour*MAXCOL/COLOURS,1);
textbackground(colour);
for(j=0;j<MAXROW;j++){
for(i=0;i<MAXCOL/COLOURS;i++){
cprintf(" ");
}
gotoxy(1+colour*MAXCOL/COLOURS,1+j);
}
}
getch();
textbackground(BLACK);
return 0;
}
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Generate an equivalent Go version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }
typedef double **mat;
#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) { for_ij x[i][j] = 0; }
#define _new(a) a = mat_new(n)
mat mat_new(_dim)
{
mat x = malloc(sizeof(double*) * n);
x[0] = malloc(sizeof(double) * n * n);
for_i x[i] = x[0] + n * i;
_zero(x);
return x;
}
#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim)
{
mat x = mat_new(n);
for_ij x[i][j] = ((double (*)[n])s)[i][j];
return x;
}
#define _del(x) mat_del(x)
void mat_del(mat x) { free(x[0]); free(x); }
#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim)
{
if (!fmt) fmt = "%8.4g";
for_i {
printf(i ? " " : " [ ");
for_j {
printf(fmt, x[i][j]);
printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n");
}
}
}
#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim)
{
mat c = _new(c);
for_ijk c[i][j] += a[i][k] * b[k][j];
return c;
}
#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim)
{
for_ij { p[i][j] = (i == j); }
for_i {
int max_j = i;
foreach(j, i, n)
if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j;
if (max_j != i)
for_k { _swap(p[i][k], p[max_j][k]); }
}
}
#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim)
{
_zero(L); _zero(U);
_pivot(A, P);
mat Aprime = _mul(P, A);
for_i { L[i][i] = 1; }
for_ij {
double s;
if (j <= i) {
_sum_k(0, j, L[j][k] * U[k][i], s)
U[j][i] = Aprime[j][i] - s;
}
if (j >= i) {
_sum_k(0, i, L[j][k] * U[k][i], s);
L[j][i] = (Aprime[j][i] - s) / U[i][i];
}
}
_del(Aprime);
}
double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }};
double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}};
int main()
{
int n = 3;
mat A, L, P, U;
_new(L); _new(P); _new(U);
A = _copy(A3);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
printf("\n");
n = 4;
_new(L); _new(P); _new(U);
A = _copy(A4);
_LU(A, L, U, P);
_show(A); _show(L); _show(U); _show(P);
_del(A); _del(L); _del(U); _del(P);
return 0;
}
| package main
import "fmt"
type matrix [][]float64
func zero(n int) matrix {
r := make([][]float64, n)
a := make([]float64, n*n)
for i := range r {
r[i] = a[n*i : n*(i+1)]
}
return r
}
func eye(n int) matrix {
r := zero(n)
for i := range r {
r[i][i] = 1
}
return r
}
func (m matrix) print(label string) {
if label > "" {
fmt.Printf("%s:\n", label)
}
for _, r := range m {
for _, e := range r {
fmt.Printf(" %9.5f", e)
}
fmt.Println()
}
}
func (a matrix) pivotize() matrix {
p := eye(len(a))
for j, r := range a {
max := r[j]
row := j
for i := j; i < len(a); i++ {
if a[i][j] > max {
max = a[i][j]
row = i
}
}
if j != row {
p[j], p[row] = p[row], p[j]
}
}
return p
}
func (m1 matrix) mul(m2 matrix) matrix {
r := zero(len(m1))
for i, r1 := range m1 {
for j := range m2 {
for k := range m1 {
r[i][j] += r1[k] * m2[k][j]
}
}
}
return r
}
func (a matrix) lu() (l, u, p matrix) {
l = zero(len(a))
u = zero(len(a))
p = a.pivotize()
a = p.mul(a)
for j := range a {
l[j][j] = 1
for i := 0; i <= j; i++ {
sum := 0.
for k := 0; k < i; k++ {
sum += u[k][j] * l[i][k]
}
u[i][j] = a[i][j] - sum
}
for i := j; i < len(a); i++ {
sum := 0.
for k := 0; k < j; k++ {
sum += u[k][j] * l[i][k]
}
l[i][j] = (a[i][j] - sum) / u[j][j]
}
}
return
}
func main() {
showLU(matrix{
{1, 3, 5},
{2, 4, 7},
{1, 1, 0}})
showLU(matrix{
{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}})
}
func showLU(a matrix) {
a.print("\na")
l, u, p := a.lu()
l.print("l")
u.print("u")
p.print("p")
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #include <iostream>
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n';
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
std::cout << "a shl b: " << (a << b) << '\n';
std::cout << "a shr b: " << (a >> b) << '\n';
unsigned int ua = a;
std::cout << "a lsr b: " << (ua >> b) << '\n';
std::cout << "a rol b: " << std::rotl(ua, b) << '\n';
std::cout << "a ror b: " << std::rotr(ua, b) << '\n';
}
| void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
printf("a or b: %d\n", a | b);
printf("a xor b: %d\n", a ^ b);
printf("not a: %d\n", ~a);
printf("a << n: %d\n", a << b);
printf("a >> n: %d\n", a >> b);
unsigned int c = a;
printf("c >> b: %d\n", c >> b);
return 0;
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #include <windows.h>
#include <iostream>
using namespace std;
const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c )
{
clr = c; createPen();
}
void setPenWidth( int w )
{
wid = w; createPen();
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class dragonC
{
public:
dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }
void draw( int iterations ) { generate( iterations ); draw(); }
private:
void generate( int it )
{
generator.push_back( 1 );
string temp;
for( int y = 0; y < it - 1; y++ )
{
temp = generator; temp.push_back( 1 );
for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )
temp.push_back( !( *x ) );
generator = temp;
}
}
void draw()
{
HDC dc = bmp.getDC();
unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };
int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;
for( int t = 0; t < 4; t++ )
{
int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];
MoveToEx( dc, a, b, NULL );
bmp.setPenColor( clr[t] );
for( string::iterator x = generator.begin(); x < generator.end(); x++ )
{
switch( dir )
{
case NORTH:
if( *x ) { a += LEN; dir = EAST; }
else { a -= LEN; dir = WEST; }
break;
case EAST:
if( *x ) { b += LEN; dir = SOUTH; }
else { b -= LEN; dir = NORTH; }
break;
case SOUTH:
if( *x ) { a -= LEN; dir = WEST; }
else { a += LEN; dir = EAST; }
break;
case WEST:
if( *x ) { b -= LEN; dir = NORTH; }
else { b += LEN; dir = SOUTH; }
}
LineTo( dc, a, b );
}
}
bmp.saveBitmap( "f:/rc/dragonCpp.bmp" );
}
int dir;
myBitmap bmp;
string generator;
};
int main( int argc, char* argv[] )
{
dragonC d; d.draw( 17 );
return system( "pause" );
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
long long tmp = dx - dy; dy = dx + dy; dx = tmp;
scale *= 2; x *= 2; y *= 2;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
double h = 6.0 * clen / scale;
double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;
double c = SAT * VAL;
double X = c * (1 - fabs(fmod(h, 2) - 1));
switch((int)h) {
case 0: p->r += c; p->g += X; return;
case 1: p->r += X; p->g += c; return;
case 2: p->g += c; p->b += X; return;
case 3: p->g += X; p->b += c; return;
case 4: p->r += X; p->b += c; return;
default:
p->r += c; p->b += X;
}
}
void iter_string(const char * str, int d)
{
long tmp;
# define LEFT tmp = -dy; dy = dx; dx = tmp
# define RIGHT tmp = dy; dy = -dx; dx = tmp
while (*str != '\0') {
switch(*(str++)) {
case 'X': if (d) iter_string("X+YF+", d - 1); continue;
case 'Y': if (d) iter_string("-FX-Y", d - 1); continue;
case '+': RIGHT; continue;
case '-': LEFT; continue;
case 'F':
clen ++;
h_rgb(x/scale, y/scale);
x += dx; y += dy;
continue;
}
}
}
void dragon(long leng, int depth)
{
long i, d = leng / 3 + 1;
long h = leng + 3, w = leng + d * 3 / 2 + 2;
rgb *buf = malloc(sizeof(rgb) * w * h);
pix = malloc(sizeof(rgb *) * h);
for (i = 0; i < h; i++)
pix[i] = buf + w * i;
memset(buf, 0, sizeof(rgb) * w * h);
x = y = d; dx = leng; dy = 0; scale = 1; clen = 0;
for (i = 0; i < depth; i++) sc_up();
iter_string("FX", depth);
unsigned char *fpix = malloc(w * h * 3);
double maxv = 0, *dbuf = (double*)buf;
for (i = 3 * w * h - 1; i >= 0; i--)
if (dbuf[i] > maxv) maxv = dbuf[i];
for (i = 3 * h * w - 1; i >= 0; i--)
fpix[i] = 255 * dbuf[i] / maxv;
printf("P6\n%ld %ld\n255\n", w, h);
fflush(stdout);
fwrite(fpix, h * w * 3, 1, stdout);
}
int main(int c, char ** v)
{
int size, depth;
depth = (c > 1) ? atoi(v[1]) : 10;
size = 1 << depth;
fprintf(stderr, "size: %d depth: %d\n", size, depth);
dragon(size, depth * 2);
return 0;
}
|
Generate an equivalent C version of this C++ code. | #include <fstream>
#include <string>
#include <iostream>
int main( int argc , char** argv ) {
int linecount = 0 ;
std::string line ;
std::ifstream infile( argv[ 1 ] ) ;
if ( infile ) {
while ( getline( infile , line ) ) {
std::cout << linecount << ": "
<< line << '\n' ;
linecount++ ;
}
}
infile.close( ) ;
return 0 ;
}
|
#include <conio.h>
#include <stdio.h>
int main()
{
int n1, n2, n3;
printf( "\n Introduzca el primer n%cmero (entero): ", 163 );
scanf( "%d", &n1 );
printf( "\n Introduzca el segundo n%cmero (entero): ", 163 );
scanf( "%d", &n2 );
printf( "\n Introduzca el tercer n%cmero (entero): ", 163 );
scanf( "%d", &n3 );
if ( n1 >= n2 && n1 >= n3 )
printf( "\n %d es el mayor.", n1 );
else
if ( n2 > n3 )
printf( "\n %d es el mayor.", n2 );
else
printf( "\n %d es el mayor.", n3 );
getch();
return 0;
}
|
Translate the given C++ code snippet into C without altering its behavior. | template <typename T>
void insert_after(Node<T>* N, T&& data)
{
auto node = new Node<T>{N, N->next, std::forward(data)};
if(N->next != nullptr)
N->next->prev = node;
N->next = node;
}
| void insert(link* anchor, link* newlink) {
newlink->next = anchor->next;
newlink->prev = anchor;
(newlink->next)->prev = newlink;
anchor->next = newlink;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #include <iostream>
#include <cstdint>
using integer = uint32_t;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 + next_prime_digit_number(n/10) * 10;
}
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };
integer p = 7;
for (;;) {
for (integer w : wheel) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += w;
}
}
}
int main() {
std::cout.imbue(std::locale(""));
const integer limit = 1000000000;
integer n = 0, max = 0;
std::cout << "First 25 SPDS primes:\n";
for (int i = 0; n < limit; ) {
n = next_prime_digit_number(n);
if (!is_prime(n))
continue;
if (i < 25) {
if (i > 0)
std::cout << ' ';
std::cout << n;
}
else if (i == 25)
std::cout << '\n';
++i;
if (i == 100)
std::cout << "Hundredth SPDS prime: " << n << '\n';
else if (i == 1000)
std::cout << "Thousandth SPDS prime: " << n << '\n';
else if (i == 10000)
std::cout << "Ten thousandth SPDS prime: " << n << '\n';
max = n;
}
std::cout << "Largest SPDS prime less than " << limit << ": " << max << '\n';
return 0;
}
| #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
typedef uint32_t integer;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 + next_prime_digit_number(n/10) * 10;
}
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
static const integer wheel[] = { 4,2,4,2,4,6,2,6 };
integer p = 7;
for (;;) {
for (int i = 0; i < 8; ++i) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += wheel[i];
}
}
}
int main() {
setlocale(LC_ALL, "");
const integer limit = 1000000000;
integer n = 0, max = 0;
printf("First 25 SPDS primes:\n");
for (int i = 0; n < limit; ) {
n = next_prime_digit_number(n);
if (!is_prime(n))
continue;
if (i < 25) {
if (i > 0)
printf(" ");
printf("%'u", n);
}
else if (i == 25)
printf("\n");
++i;
if (i == 100)
printf("Hundredth SPDS prime: %'u\n", n);
else if (i == 1000)
printf("Thousandth SPDS prime: %'u\n", n);
else if (i == 10000)
printf("Ten thousandth SPDS prime: %'u\n", n);
max = n;
}
printf("Largest SPDS prime less than %'u: %'u\n", limit, max);
return 0;
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #include <algorithm>
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));
std::cout << a[i];
if (i < 9) std::cout << ", ";
}
std::cout << std::endl;
return 0;
}
| #include <stdio.h>
#include <string.h>
int qselect(int *v, int len, int k)
{
# define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }
int i, st, tmp;
for (st = i = 0; i < len - 1; i++) {
if (v[i] > v[len-1]) continue;
SWAP(i, st);
st++;
}
SWAP(len-1, st);
return k == st ?v[st]
:st > k ? qselect(v, st, k)
: qselect(v + st, len - st, k - st);
}
int main(void)
{
# define N (sizeof(x)/sizeof(x[0]))
int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
int y[N];
int i;
for (i = 0; i < 10; i++) {
memcpy(y, x, sizeof(x));
printf("%d: %d\n", i, qselect(y, 10, i));
}
return 0;
}
|
Produce a language-to-language conversion: from C++ to C, same semantics. | #include <string>
#include <cstdlib>
#include <algorithm>
#include <cassert>
std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
std::string to_base(unsigned long num, int base)
{
if (num == 0)
return "0";
std::string result;
while (num > 0) {
std::ldiv_t temp = std::div(num, (long)base);
result += digits[temp.rem];
num = temp.quot;
}
std::reverse(result.begin(), result.end());
return result;
}
unsigned long from_base(std::string const& num_str, int base)
{
unsigned long result = 0;
for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)
result = result * base + digits.find(num_str[pos]);
return result;
}
| #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
char *to_base(int64_t num, int base)
{
char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[66] = {'\0'};
char *out;
uint64_t n;
int i, len = 0, neg = 0;
if (base > 36) {
fprintf(stderr, "base %d too large\n", base);
return 0;
}
n = ((neg = num < 0)) ? (~num) + 1 : num;
do { buf[len++] = tbl[n % base]; } while(n /= base);
out = malloc(len + neg + 1);
for (i = neg; len > 0; i++) out[i] = buf[--len];
if (neg) out[0] = '-';
return out;
}
long from_base(const char *num_str, int base)
{
char *endptr;
int result = strtol(num_str, &endptr, base);
return result;
}
int main()
{
int64_t x;
x = ~(1LL << 63) + 1;
printf("%lld in base 2: %s\n", x, to_base(x, 2));
x = 383;
printf("%lld in base 16: %s\n", x, to_base(x, 16));
return 0;
}
|
Produce a functionally identical C code for the snippet given in C++. | #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Change the following C++ code into C without altering its purpose. | UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)
{
UINT_64 N;
N = N1;
N = (N<<32)|N2;
return UINT_64(N);
}
UINT_32 TGost::ReplaceBlock(UINT_32 x)
{
register i;
UINT_32 res = 0UL;
for(i=7;i>=0;i--)
{
ui4_0 = x>>(i*4);
ui4_0 = BS[ui4_0][i];
res = (res<<4)|ui4_0;
}
return res;
}
UINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)
{
UINT_32 N1,N2,S=0UL;
N1=UINT_32(N);
N2=N>>32;
S = N1 + X % 0x4000000000000;
S = ReplaceBlock(S);
S = (S<<11)|(S>>21);
S ^= N2;
N2 = N1;
N1 = S;
return SWAP32(N2,N1);
}
| static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 };
static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 };
static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 };
static unsigned char const k5[16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 };
static unsigned char const k4[16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 };
static unsigned char const k3[16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 };
static unsigned char const k2[16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 };
static unsigned char const k1[16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 };
static unsigned char k87[256];
static unsigned char k65[256];
static unsigned char k43[256];
static unsigned char k21[256];
void
kboxinit(void)
{
int i;
for (i = 0; i < 256; i++) {
k87[i] = k8[i >> 4] << 4 | k7[i & 15];
k65[i] = k6[i >> 4] << 4 | k5[i & 15];
k43[i] = k4[i >> 4] << 4 | k3[i & 15];
k21[i] = k2[i >> 4] << 4 | k1[i & 15];
}
}
static word32
f(word32 x)
{
x = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |
k43[x>> 8 & 255] << 8 | k21[x & 255];
return x<<11 | x>>(32-11);
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <algorithm>
#include <iostream>
#include <string>
#include <array>
#include <vector>
template<typename T>
T unique(T&& src)
{
T retval(std::move(src));
std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());
retval.erase(std::unique(retval.begin(), retval.end()), retval.end());
return retval;
}
#define USE_FAKES 1
auto states = unique(std::vector<std::string>({
#if USE_FAKES
"Slender Dragon", "Abalamara",
#endif
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
}));
struct counted_pair
{
std::string name;
std::array<int, 26> count{};
void count_characters(const std::string& s)
{
for (auto&& c : s) {
if (c >= 'a' && c <= 'z') count[c - 'a']++;
if (c >= 'A' && c <= 'Z') count[c - 'A']++;
}
}
counted_pair(const std::string& s1, const std::string& s2)
: name(s1 + " + " + s2)
{
count_characters(s1);
count_characters(s2);
}
};
bool operator<(const counted_pair& lhs, const counted_pair& rhs)
{
auto lhs_size = lhs.name.size();
auto rhs_size = rhs.name.size();
return lhs_size == rhs_size
? std::lexicographical_compare(lhs.count.begin(),
lhs.count.end(),
rhs.count.begin(),
rhs.count.end())
: lhs_size < rhs_size;
}
bool operator==(const counted_pair& lhs, const counted_pair& rhs)
{
return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;
}
int main()
{
const int n_states = states.size();
std::vector<counted_pair> pairs;
for (int i = 0; i < n_states; i++) {
for (int j = 0; j < i; j++) {
pairs.emplace_back(counted_pair(states[i], states[j]));
}
}
std::sort(pairs.begin(), pairs.end());
auto start = pairs.begin();
while (true) {
auto match = std::adjacent_find(start, pairs.end());
if (match == pairs.end()) {
break;
}
auto next = match + 1;
std::cout << match->name << " => " << next->name << "\n";
start = next;
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define USE_FAKES 1
const char *states[] = {
#if USE_FAKES
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory",
#endif
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
};
int n_states = sizeof(states)/sizeof(*states);
typedef struct { unsigned char c[26]; const char *name[2]; } letters;
void count_letters(letters *l, const char *s)
{
int c;
if (!l->name[0]) l->name[0] = s;
else l->name[1] = s;
while ((c = *s++)) {
if (c >= 'a' && c <= 'z') l->c[c - 'a']++;
if (c >= 'A' && c <= 'Z') l->c[c - 'A']++;
}
}
int lcmp(const void *aa, const void *bb)
{
int i;
const letters *a = aa, *b = bb;
for (i = 0; i < 26; i++)
if (a->c[i] > b->c[i]) return 1;
else if (a->c[i] < b->c[i]) return -1;
return 0;
}
int scmp(const void *a, const void *b)
{
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
void no_dup()
{
int i, j;
qsort(states, n_states, sizeof(const char*), scmp);
for (i = j = 0; i < n_states;) {
while (++i < n_states && !strcmp(states[i], states[j]));
if (i < n_states) states[++j] = states[i];
}
n_states = j + 1;
}
void find_mix()
{
int i, j, n;
letters *l, *p;
no_dup();
n = n_states * (n_states - 1) / 2;
p = l = calloc(n, sizeof(letters));
for (i = 0; i < n_states; i++)
for (j = i + 1; j < n_states; j++, p++) {
count_letters(p, states[i]);
count_letters(p, states[j]);
}
qsort(l, n, sizeof(letters), lcmp);
for (j = 0; j < n; j++) {
for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) {
if (l[j].name[0] == l[i].name[0]
|| l[j].name[1] == l[i].name[0]
|| l[j].name[1] == l[i].name[1])
continue;
printf("%s + %s => %s + %s\n",
l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]);
}
}
free(l);
}
int main(void)
{
find_mix();
return 0;
}
|
Write the same algorithm in C as shown in this C++ implementation. | #include <algorithm>
#include <array>
#include <cstdint>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <string>
std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept
{
auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};
struct byte_checksum
{
std::uint_fast32_t operator()() noexcept
{
auto checksum = static_cast<std::uint_fast32_t>(n++);
for (auto i = 0; i < 8; ++i)
checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);
return checksum;
}
unsigned n = 0;
};
auto table = std::array<std::uint_fast32_t, 256>{};
std::generate(table.begin(), table.end(), byte_checksum{});
return table;
}
template <typename InputIterator>
std::uint_fast32_t crc(InputIterator first, InputIterator last)
{
static auto const table = generate_crc_lookup_table();
return std::uint_fast32_t{0xFFFFFFFFuL} &
~std::accumulate(first, last,
~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},
[](std::uint_fast32_t checksum, std::uint_fast8_t value)
{ return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });
}
int main()
{
auto const s = std::string{"The quick brown fox jumps over the lazy dog"};
std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n';
}
| #include <stdio.h>
#include <string.h>
#include <zlib.h>
int main()
{
const char *s = "The quick brown fox jumps over the lazy dog";
printf("%lX\n", crc32(0, (const void*)s, strlen(s)));
return 0;
}
|
Translate this program into C but keep the logic exactly as in C++. | #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!\n" ;
std::cout << csvToHTML( text ) ;
return 0 ;
}
std::string csvToHTML( const std::string & csvtext ) {
std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
const char* replacements [ 5 ] = { "<" , ">" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ;
boost::regex e1( regexes[ 0 ] ) ;
std::string tabletext = boost::regex_replace( csvtext , e1 ,
replacements[ 0 ] , boost::match_default | boost::format_all ) ;
for ( int i = 1 ; i < 5 ; i++ ) {
e1.assign( regexes[ i ] ) ;
tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
}
tabletext = std::string( "<TABLE>\n" ) + tabletext ;
tabletext.append( "</TABLE>\n" ) ;
return tabletext ;
}
| #include <stdio.h>
const char *input =
"Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; "
"he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!";
int main()
{
const char *s;
printf("<table>\n<tr><td>");
for (s = input; *s; s++) {
switch(*s) {
case '\n': printf("</td></tr>\n<tr><td>"); break;
case ',': printf("</td><td>"); break;
case '<': printf("<"); break;
case '>': printf(">"); break;
case '&': printf("&"); break;
default: putchar(*s);
}
}
puts("</td></tr>\n</table>");
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!\n" ;
std::cout << csvToHTML( text ) ;
return 0 ;
}
std::string csvToHTML( const std::string & csvtext ) {
std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
const char* replacements [ 5 ] = { "<" , ">" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ;
boost::regex e1( regexes[ 0 ] ) ;
std::string tabletext = boost::regex_replace( csvtext , e1 ,
replacements[ 0 ] , boost::match_default | boost::format_all ) ;
for ( int i = 1 ; i < 5 ; i++ ) {
e1.assign( regexes[ i ] ) ;
tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
}
tabletext = std::string( "<TABLE>\n" ) + tabletext ;
tabletext.append( "</TABLE>\n" ) ;
return tabletext ;
}
| #include <stdio.h>
const char *input =
"Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; "
"he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!";
int main()
{
const char *s;
printf("<table>\n<tr><td>");
for (s = input; *s; s++) {
switch(*s) {
case '\n': printf("</td></tr>\n<tr><td>"); break;
case ',': printf("</td><td>"); break;
case '<': printf("<"); break;
case '>': printf(">"); break;
case '&': printf("&"); break;
default: putchar(*s);
}
}
puts("</td></tr>\n</table>");
return 0;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
OPTION PARSE FALSE
'---The class does the declaring for you
CLASS Books
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1 = Books()
'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567
PRINT "Book title : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
| #include <stdlib.h>
typedef struct sMyClass
{
int variable;
} *MyClass;
MyClass MyClass_new()
{
MyClass pthis = malloc(sizeof *pthis);
pthis->variable = 0;
return pthis;
}
void MyClass_delete(MyClass* pthis)
{
if (pthis)
{
free(*pthis);
*pthis = NULL;
}
}
void MyClass_someMethod(MyClass pthis)
{
pthis->variable = 1;
}
MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <utility>
long string2long( const std::string & s ) {
long result ;
std::istringstream( s ) >> result ;
return result ;
}
bool isKaprekar( long number ) {
long long squarenumber = ((long long)number) * number ;
std::ostringstream numberbuf ;
numberbuf << squarenumber ;
std::string numberstring = numberbuf.str( ) ;
for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {
std::string firstpart = numberstring.substr( 0 , i ) ,
secondpart = numberstring.substr( i ) ;
if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) {
return false ;
}
if ( string2long( firstpart ) + string2long( secondpart ) == number ) {
return true ;
}
}
return false ;
}
int main( ) {
std::vector<long> kaprekarnumbers ;
kaprekarnumbers.push_back( 1 ) ;
for ( int i = 2 ; i < 1000001 ; i++ ) {
if ( isKaprekar( i ) )
kaprekarnumbers.push_back( i ) ;
}
std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;
std::cout << "Kaprekar numbers up to 10000: \n" ;
while ( *svi < 10000 ) {
std::cout << *svi << " " ;
svi++ ;
}
std::cout << '\n' ;
std::cout << "All the Kaprekar numbers up to 1000000 :\n" ;
std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,
std::ostream_iterator<long>( std::cout , "\n" ) ) ;
std::cout << "There are " << kaprekarnumbers.size( )
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}
| #include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
int kaprekar(ulong n, int base)
{
ulong nn = n * n, r, tens = 1;
if ((nn - n) % (base - 1)) return 0;
while (tens < n) tens *= base;
if (n == tens) return 1 == n;
while ((r = nn % tens) < n) {
if (nn / tens + r == n) return tens;
tens *= base;
}
return 0;
}
void print_num(ulong n, int base)
{
ulong q, div = base;
while (div < n) div *= base;
while (n && (div /= base)) {
q = n / div;
if (q < 10) putchar(q + '0');
else putchar(q + 'a' - 10);
n -= q * div;
}
}
int main()
{
ulong i, tens;
int cnt = 0;
int base = 10;
printf("base 10:\n");
for (i = 1; i < 1000000; i++)
if (kaprekar(i, base))
printf("%3d: %llu\n", ++cnt, i);
base = 17;
printf("\nbase %d:\n 1: 1\n", base);
for (i = 2, cnt = 1; i < 1000000; i++)
if ((tens = kaprekar(i, base))) {
printf("%3d: %llu", ++cnt, i);
printf(" \t"); print_num(i, base);
printf("\t"); print_num(i * i, base);
printf("\t"); print_num(i * i / tens, base);
printf(" + "); print_num(i * i % tens, base);
printf("\n");
}
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <utility>
long string2long( const std::string & s ) {
long result ;
std::istringstream( s ) >> result ;
return result ;
}
bool isKaprekar( long number ) {
long long squarenumber = ((long long)number) * number ;
std::ostringstream numberbuf ;
numberbuf << squarenumber ;
std::string numberstring = numberbuf.str( ) ;
for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {
std::string firstpart = numberstring.substr( 0 , i ) ,
secondpart = numberstring.substr( i ) ;
if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) {
return false ;
}
if ( string2long( firstpart ) + string2long( secondpart ) == number ) {
return true ;
}
}
return false ;
}
int main( ) {
std::vector<long> kaprekarnumbers ;
kaprekarnumbers.push_back( 1 ) ;
for ( int i = 2 ; i < 1000001 ; i++ ) {
if ( isKaprekar( i ) )
kaprekarnumbers.push_back( i ) ;
}
std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;
std::cout << "Kaprekar numbers up to 10000: \n" ;
while ( *svi < 10000 ) {
std::cout << *svi << " " ;
svi++ ;
}
std::cout << '\n' ;
std::cout << "All the Kaprekar numbers up to 1000000 :\n" ;
std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,
std::ostream_iterator<long>( std::cout , "\n" ) ) ;
std::cout << "There are " << kaprekarnumbers.size( )
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}
| #include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
int kaprekar(ulong n, int base)
{
ulong nn = n * n, r, tens = 1;
if ((nn - n) % (base - 1)) return 0;
while (tens < n) tens *= base;
if (n == tens) return 1 == n;
while ((r = nn % tens) < n) {
if (nn / tens + r == n) return tens;
tens *= base;
}
return 0;
}
void print_num(ulong n, int base)
{
ulong q, div = base;
while (div < n) div *= base;
while (n && (div /= base)) {
q = n / div;
if (q < 10) putchar(q + '0');
else putchar(q + 'a' - 10);
n -= q * div;
}
}
int main()
{
ulong i, tens;
int cnt = 0;
int base = 10;
printf("base 10:\n");
for (i = 1; i < 1000000; i++)
if (kaprekar(i, base))
printf("%3d: %llu\n", ++cnt, i);
base = 17;
printf("\nbase %d:\n 1: 1\n", base);
for (i = 2, cnt = 1; i < 1000000; i++)
if ((tens = kaprekar(i, base))) {
printf("%3d: %llu", ++cnt, i);
printf(" \t"); print_num(i, base);
printf("\t"); print_num(i * i, base);
printf("\t"); print_num(i * i / tens, base);
printf(" + "); print_num(i * i % tens, base);
printf("\n");
}
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #include <string>
#include <map>
template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result) {
int dictSize = 256;
std::map<std::string,int> dictionary;
for (int i = 0; i < 256; i++)
dictionary[std::string(1, i)] = i;
std::string w;
for (std::string::const_iterator it = uncompressed.begin();
it != uncompressed.end(); ++it) {
char c = *it;
std::string wc = w + c;
if (dictionary.count(wc))
w = wc;
else {
*result++ = dictionary[w];
dictionary[wc] = dictSize++;
w = std::string(1, c);
}
}
if (!w.empty())
*result++ = dictionary[w];
return result;
}
template <typename Iterator>
std::string decompress(Iterator begin, Iterator end) {
int dictSize = 256;
std::map<int,std::string> dictionary;
for (int i = 0; i < 256; i++)
dictionary[i] = std::string(1, i);
std::string w(1, *begin++);
std::string result = w;
std::string entry;
for ( ; begin != end; begin++) {
int k = *begin;
if (dictionary.count(k))
entry = dictionary[k];
else if (k == dictSize)
entry = w + w[0];
else
throw "Bad compressed k";
result += entry;
dictionary[dictSize++] = w + entry[0];
w = entry;
}
return result;
}
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> compressed;
compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed));
copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
std::string decompressed = decompress(compressed.begin(), compressed.end());
std::cout << decompressed << std::endl;
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
void* mem_alloc(size_t item_size, size_t n_item)
{
size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);
x[0] = item_size;
x[1] = n_item;
return x + 2;
}
void* mem_extend(void *m, size_t new_n)
{
size_t *x = (size_t*)m - 2;
x = realloc(x, sizeof(size_t) * 2 + *x * new_n);
if (new_n > x[1])
memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));
x[1] = new_n;
return x + 2;
}
inline void _clear(void *m)
{
size_t *x = (size_t*)m - 2;
memset(m, 0, x[0] * x[1]);
}
#define _new(type, n) mem_alloc(sizeof(type), n)
#define _del(m) { free((size_t*)(m) - 2); m = 0; }
#define _len(m) *((size_t*)m - 1)
#define _setsize(m, n) m = mem_extend(m, n)
#define _extend(m) m = mem_extend(m, _len(m) * 2)
typedef uint8_t byte;
typedef uint16_t ushort;
#define M_CLR 256
#define M_EOD 257
#define M_NEW 258
typedef struct {
ushort next[256];
} lzw_enc_t;
typedef struct {
ushort prev, back;
byte c;
} lzw_dec_t;
byte* lzw_encode(byte *in, int max_bits)
{
int len = _len(in), bits = 9, next_shift = 512;
ushort code, c, nc, next_code = M_NEW;
lzw_enc_t *d = _new(lzw_enc_t, 512);
if (max_bits > 15) max_bits = 15;
if (max_bits < 9 ) max_bits = 12;
byte *out = _new(ushort, 4);
int out_len = 0, o_bits = 0;
uint32_t tmp = 0;
inline void write_bits(ushort x) {
tmp = (tmp << bits) | x;
o_bits += bits;
if (_len(out) <= out_len) _extend(out);
while (o_bits >= 8) {
o_bits -= 8;
out[out_len++] = tmp >> o_bits;
tmp &= (1 << o_bits) - 1;
}
}
for (code = *(in++); --len; ) {
c = *(in++);
if ((nc = d[code].next[c]))
code = nc;
else {
write_bits(code);
nc = d[code].next[c] = next_code++;
code = c;
}
if (next_code == next_shift) {
if (++bits > max_bits) {
write_bits(M_CLR);
bits = 9;
next_shift = 512;
next_code = M_NEW;
_clear(d);
} else
_setsize(d, next_shift *= 2);
}
}
write_bits(code);
write_bits(M_EOD);
if (tmp) write_bits(tmp);
_del(d);
_setsize(out, out_len);
return out;
}
byte* lzw_decode(byte *in)
{
byte *out = _new(byte, 4);
int out_len = 0;
inline void write_out(byte c)
{
while (out_len >= _len(out)) _extend(out);
out[out_len++] = c;
}
lzw_dec_t *d = _new(lzw_dec_t, 512);
int len, j, next_shift = 512, bits = 9, n_bits = 0;
ushort code, c, t, next_code = M_NEW;
uint32_t tmp = 0;
inline void get_code() {
while(n_bits < bits) {
if (len > 0) {
len --;
tmp = (tmp << 8) | *(in++);
n_bits += 8;
} else {
tmp = tmp << (bits - n_bits);
n_bits = bits;
}
}
n_bits -= bits;
code = tmp >> n_bits;
tmp &= (1 << n_bits) - 1;
}
inline void clear_table() {
_clear(d);
for (j = 0; j < 256; j++) d[j].c = j;
next_code = M_NEW;
next_shift = 512;
bits = 9;
};
clear_table();
for (len = _len(in); len;) {
get_code();
if (code == M_EOD) break;
if (code == M_CLR) {
clear_table();
continue;
}
if (code >= next_code) {
fprintf(stderr, "Bad sequence\n");
_del(out);
goto bail;
}
d[next_code].prev = c = code;
while (c > 255) {
t = d[c].prev; d[t].back = c; c = t;
}
d[next_code - 1].c = c;
while (d[c].back) {
write_out(d[c].c);
t = d[c].back; d[c].back = 0; c = t;
}
write_out(d[c].c);
if (++next_code >= next_shift) {
if (++bits > 16) {
fprintf(stderr, "Too many bits\n");
_del(out);
goto bail;
}
_setsize(d, next_shift *= 2);
}
}
if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr);
_setsize(out, out_len);
bail: _del(d);
return out;
}
int main()
{
int i, fd = open("unixdict.txt", O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Can't read file\n");
return 1;
};
struct stat st;
fstat(fd, &st);
byte *in = _new(char, st.st_size);
read(fd, in, st.st_size);
_setsize(in, st.st_size);
close(fd);
printf("input size: %d\n", _len(in));
byte *enc = lzw_encode(in, 9);
printf("encoded size: %d\n", _len(enc));
byte *dec = lzw_decode(enc);
printf("decoded size: %d\n", _len(dec));
for (i = 0; i < _len(dec); i++)
if (dec[i] != in[i]) {
printf("bad decode at %d\n", i);
break;
}
if (i == _len(dec)) printf("Decoded ok\n");
_del(in);
_del(enc);
_del(dec);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <iomanip>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
while (list->size() > target_size) list->pop_back();
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
int m = max(*r.rbegin(), *s.rbegin());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef struct {
size_t len, alloc;
xint *buf;
} xarray;
xarray rs, ss;
void setsize(xarray *a, size_t size)
{
size_t n = a->alloc;
if (!n) n = 1;
while (n < size) n <<= 1;
if (a->alloc < n) {
a->buf = realloc(a->buf, sizeof(xint) * n);
if (!a->buf) abort();
a->alloc = n;
}
}
void push(xarray *a, xint v)
{
while (a->alloc <= a->len)
setsize(a, a->alloc * 2);
a->buf[a->len++] = v;
}
void RS_append(void);
xint R(int n)
{
while (n > rs.len) RS_append();
return rs.buf[n - 1];
}
xint S(int n)
{
while (n > ss.len) RS_append();
return ss.buf[n - 1];
}
void RS_append()
{
int n = rs.len;
xint r = R(n) + S(n);
xint s = S(ss.len);
push(&rs, r);
while (++s < r) push(&ss, s);
push(&ss, r + 1);
}
int main(void)
{
push(&rs, 1);
push(&ss, 2);
int i;
printf("R(1 .. 10):");
for (i = 1; i <= 10; i++)
printf(" %llu", R(i));
char seen[1001] = { 0 };
for (i = 1; i <= 40; i++) seen[ R(i) ] = 1;
for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
for (i = 1; i <= 1000 && seen[i]; i++);
if (i <= 1000) {
fprintf(stderr, "%d not seen\n", i);
abort();
}
puts("\nfirst 1000 ok");
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #include <iomanip>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
while (list->size() > target_size) list->pop_back();
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
int m = max(*r.rbegin(), *s.rbegin());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef struct {
size_t len, alloc;
xint *buf;
} xarray;
xarray rs, ss;
void setsize(xarray *a, size_t size)
{
size_t n = a->alloc;
if (!n) n = 1;
while (n < size) n <<= 1;
if (a->alloc < n) {
a->buf = realloc(a->buf, sizeof(xint) * n);
if (!a->buf) abort();
a->alloc = n;
}
}
void push(xarray *a, xint v)
{
while (a->alloc <= a->len)
setsize(a, a->alloc * 2);
a->buf[a->len++] = v;
}
void RS_append(void);
xint R(int n)
{
while (n > rs.len) RS_append();
return rs.buf[n - 1];
}
xint S(int n)
{
while (n > ss.len) RS_append();
return ss.buf[n - 1];
}
void RS_append()
{
int n = rs.len;
xint r = R(n) + S(n);
xint s = S(ss.len);
push(&rs, r);
while (++s < r) push(&ss, s);
push(&ss, r + 1);
}
int main(void)
{
push(&rs, 1);
push(&ss, 2);
int i;
printf("R(1 .. 10):");
for (i = 1; i <= 10; i++)
printf(" %llu", R(i));
char seen[1001] = { 0 };
for (i = 1; i <= 40; i++) seen[ R(i) ] = 1;
for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
for (i = 1; i <= 1000 && seen[i]; i++);
if (i <= 1000) {
fprintf(stderr, "%d not seen\n", i);
abort();
}
puts("\nfirst 1000 ok");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
class MagicSquare
{
public:
MagicSquare(int d) : sqr(d*d,0), sz(d)
{
assert(d&1);
fillSqr();
}
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr;
cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ )
{
int yy = y * sz;
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr()
{
int sx = sz / 2, sy = 0, c = 0;
while( c < sz * sz )
{
if( !sqr[sx + sy * sz] )
{
sqr[sx + sy * sz]= c + 1;
inc( sx ); dec( sy );
c++;
}
else
{
dec( sx ); inc( sy ); inc( sy );
}
}
}
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a )
{ if( ++a == sz ) a = 0; }
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
vector<int> sqr;
int sz;
};
int main()
{
MagicSquare s(7);
s.display();
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
int f(int n, int x, int y)
{
return (x + y*2 + 1)%n;
}
int main(int argc, char **argv)
{
int i, j, n;
if(argc!=2) return 1;
n = atoi(argv[1]);
if (n < 3 || (n%2) == 0) return 2;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1);
putchar('\n');
}
printf("\n Magic Constant: %d.\n", (n*n+1)/2*n);
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
class MagicSquare
{
public:
MagicSquare(int d) : sqr(d*d,0), sz(d)
{
assert(d&1);
fillSqr();
}
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr;
cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ )
{
int yy = y * sz;
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr()
{
int sx = sz / 2, sy = 0, c = 0;
while( c < sz * sz )
{
if( !sqr[sx + sy * sz] )
{
sqr[sx + sy * sz]= c + 1;
inc( sx ); dec( sy );
c++;
}
else
{
dec( sx ); inc( sy ); inc( sy );
}
}
}
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a )
{ if( ++a == sz ) a = 0; }
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
vector<int> sqr;
int sz;
};
int main()
{
MagicSquare s(7);
s.display();
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
int f(int n, int x, int y)
{
return (x + y*2 + 1)%n;
}
int main(int argc, char **argv)
{
int i, j, n;
if(argc!=2) return 1;
n = atoi(argv[1]);
if (n < 3 || (n%2) == 0) return 2;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1);
putchar('\n');
}
printf("\n Magic Constant: %d.\n", (n*n+1)/2*n);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(n1_, n_) == 1
&& std::gcd(n2_, n_) > 1); ++n_) {}
}
sequence_.insert(n_);
for (;;) {
auto it = sequence_.find(min_);
if (it == sequence_.end())
break;
sequence_.erase(it);
++min_;
}
return n_;
}
private:
std::set<integer> sequence_;
integer min_ = 1;
integer n_ = 0;
integer n1_ = 0;
integer n2_ = 0;
};
int main() {
std::cout << "First 30 Yellowstone numbers:\n";
yellowstone_generator<unsigned int> ygen;
std::cout << ygen.next();
for (int i = 1; i < 30; ++i)
std::cout << ' ' << ygen.next();
std::cout << '\n';
return 0;
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode_t {
struct lnode_t *prev;
struct lnode_t *next;
int v;
} Lnode;
Lnode *make_list_node(int v) {
Lnode *node = malloc(sizeof(Lnode));
if (node == NULL) {
return NULL;
}
node->v = v;
node->prev = NULL;
node->next = NULL;
return node;
}
void free_lnode(Lnode *node) {
if (node == NULL) {
return;
}
node->v = 0;
node->prev = NULL;
free_lnode(node->next);
node->next = NULL;
}
typedef struct list_t {
Lnode *front;
Lnode *back;
size_t len;
} List;
List *make_list() {
List *list = malloc(sizeof(List));
if (list == NULL) {
return NULL;
}
list->front = NULL;
list->back = NULL;
list->len = 0;
return list;
}
void free_list(List *list) {
if (list == NULL) {
return;
}
list->len = 0;
list->back = NULL;
free_lnode(list->front);
list->front = NULL;
}
void list_insert(List *list, int v) {
Lnode *node;
if (list == NULL) {
return;
}
node = make_list_node(v);
if (list->front == NULL) {
list->front = node;
list->back = node;
list->len = 1;
} else {
node->prev = list->back;
list->back->next = node;
list->back = node;
list->len++;
}
}
void list_print(List *list) {
Lnode *it;
if (list == NULL) {
return;
}
for (it = list->front; it != NULL; it = it->next) {
printf("%d ", it->v);
}
}
int list_get(List *list, int idx) {
Lnode *it = NULL;
if (list != NULL && list->front != NULL) {
int i;
if (idx < 0) {
it = list->back;
i = -1;
while (it != NULL && i > idx) {
it = it->prev;
i--;
}
} else {
it = list->front;
i = 0;
while (it != NULL && i < idx) {
it = it->next;
i++;
}
}
}
if (it == NULL) {
return INT_MIN;
}
return it->v;
}
typedef struct mnode_t {
int k;
bool v;
struct mnode_t *next;
} Mnode;
Mnode *make_map_node(int k, bool v) {
Mnode *node = malloc(sizeof(Mnode));
if (node == NULL) {
return node;
}
node->k = k;
node->v = v;
node->next = NULL;
return node;
}
void free_mnode(Mnode *node) {
if (node == NULL) {
return;
}
node->k = 0;
node->v = false;
free_mnode(node->next);
node->next = NULL;
}
typedef struct map_t {
Mnode *front;
} Map;
Map *make_map() {
Map *map = malloc(sizeof(Map));
if (map == NULL) {
return NULL;
}
map->front = NULL;
return map;
}
void free_map(Map *map) {
if (map == NULL) {
return;
}
free_mnode(map->front);
map->front = NULL;
}
void map_insert(Map *map, int k, bool v) {
if (map == NULL) {
return;
}
if (map->front == NULL) {
map->front = make_map_node(k, v);
} else {
Mnode *it = map->front;
while (it->next != NULL) {
it = it->next;
}
it->next = make_map_node(k, v);
}
}
bool map_get(Map *map, int k) {
if (map != NULL) {
Mnode *it = map->front;
while (it != NULL && it->k != k) {
it = it->next;
}
if (it != NULL) {
return it->v;
}
}
return false;
}
int gcd(int u, int v) {
if (u < 0) u = -u;
if (v < 0) v = -v;
if (v) {
while ((u %= v) && (v %= u));
}
return u + v;
}
List *yellow(size_t n) {
List *a;
Map *b;
int i;
a = make_list();
list_insert(a, 1);
list_insert(a, 2);
list_insert(a, 3);
b = make_map();
map_insert(b, 1, true);
map_insert(b, 2, true);
map_insert(b, 3, true);
i = 4;
while (n > a->len) {
if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {
list_insert(a, i);
map_insert(b, i, true);
i = 4;
}
i++;
}
free_map(b);
return a;
}
int main() {
List *a = yellow(30);
list_print(a);
free_list(a);
putc('\n', stdout);
return 0;
}
|
Translate this program into C but keep the logic exactly as in C++. | #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(n1_, n_) == 1
&& std::gcd(n2_, n_) > 1); ++n_) {}
}
sequence_.insert(n_);
for (;;) {
auto it = sequence_.find(min_);
if (it == sequence_.end())
break;
sequence_.erase(it);
++min_;
}
return n_;
}
private:
std::set<integer> sequence_;
integer min_ = 1;
integer n_ = 0;
integer n1_ = 0;
integer n2_ = 0;
};
int main() {
std::cout << "First 30 Yellowstone numbers:\n";
yellowstone_generator<unsigned int> ygen;
std::cout << ygen.next();
for (int i = 1; i < 30; ++i)
std::cout << ' ' << ygen.next();
std::cout << '\n';
return 0;
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode_t {
struct lnode_t *prev;
struct lnode_t *next;
int v;
} Lnode;
Lnode *make_list_node(int v) {
Lnode *node = malloc(sizeof(Lnode));
if (node == NULL) {
return NULL;
}
node->v = v;
node->prev = NULL;
node->next = NULL;
return node;
}
void free_lnode(Lnode *node) {
if (node == NULL) {
return;
}
node->v = 0;
node->prev = NULL;
free_lnode(node->next);
node->next = NULL;
}
typedef struct list_t {
Lnode *front;
Lnode *back;
size_t len;
} List;
List *make_list() {
List *list = malloc(sizeof(List));
if (list == NULL) {
return NULL;
}
list->front = NULL;
list->back = NULL;
list->len = 0;
return list;
}
void free_list(List *list) {
if (list == NULL) {
return;
}
list->len = 0;
list->back = NULL;
free_lnode(list->front);
list->front = NULL;
}
void list_insert(List *list, int v) {
Lnode *node;
if (list == NULL) {
return;
}
node = make_list_node(v);
if (list->front == NULL) {
list->front = node;
list->back = node;
list->len = 1;
} else {
node->prev = list->back;
list->back->next = node;
list->back = node;
list->len++;
}
}
void list_print(List *list) {
Lnode *it;
if (list == NULL) {
return;
}
for (it = list->front; it != NULL; it = it->next) {
printf("%d ", it->v);
}
}
int list_get(List *list, int idx) {
Lnode *it = NULL;
if (list != NULL && list->front != NULL) {
int i;
if (idx < 0) {
it = list->back;
i = -1;
while (it != NULL && i > idx) {
it = it->prev;
i--;
}
} else {
it = list->front;
i = 0;
while (it != NULL && i < idx) {
it = it->next;
i++;
}
}
}
if (it == NULL) {
return INT_MIN;
}
return it->v;
}
typedef struct mnode_t {
int k;
bool v;
struct mnode_t *next;
} Mnode;
Mnode *make_map_node(int k, bool v) {
Mnode *node = malloc(sizeof(Mnode));
if (node == NULL) {
return node;
}
node->k = k;
node->v = v;
node->next = NULL;
return node;
}
void free_mnode(Mnode *node) {
if (node == NULL) {
return;
}
node->k = 0;
node->v = false;
free_mnode(node->next);
node->next = NULL;
}
typedef struct map_t {
Mnode *front;
} Map;
Map *make_map() {
Map *map = malloc(sizeof(Map));
if (map == NULL) {
return NULL;
}
map->front = NULL;
return map;
}
void free_map(Map *map) {
if (map == NULL) {
return;
}
free_mnode(map->front);
map->front = NULL;
}
void map_insert(Map *map, int k, bool v) {
if (map == NULL) {
return;
}
if (map->front == NULL) {
map->front = make_map_node(k, v);
} else {
Mnode *it = map->front;
while (it->next != NULL) {
it = it->next;
}
it->next = make_map_node(k, v);
}
}
bool map_get(Map *map, int k) {
if (map != NULL) {
Mnode *it = map->front;
while (it != NULL && it->k != k) {
it = it->next;
}
if (it != NULL) {
return it->v;
}
}
return false;
}
int gcd(int u, int v) {
if (u < 0) u = -u;
if (v < 0) v = -v;
if (v) {
while ((u %= v) && (v %= u));
}
return u + v;
}
List *yellow(size_t n) {
List *a;
Map *b;
int i;
a = make_list();
list_insert(a, 1);
list_insert(a, 2);
list_insert(a, 3);
b = make_map();
map_insert(b, 1, true);
map_insert(b, 2, true);
map_insert(b, 3, true);
i = 4;
while (n > a->len) {
if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) {
list_insert(a, i);
map_insert(b, i, true);
i = 4;
}
i++;
}
free_map(b);
return a;
}
int main() {
List *a = yellow(30);
list_print(a);
free_list(a);
putc('\n', stdout);
return 0;
}
|
Please provide an equivalent version of this C++ code in C. | #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char byte;
byte *grid = 0;
int w, h, len;
unsigned long long cnt;
static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
int i, t;
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
t = y * (w + 1) + x;
grid[t]++, grid[len - t]++;
for (i = 0; i < 4; i++)
if (!grid[t + next[i]])
walk(y + dir[i][0], x + dir[i][1]);
grid[t]--, grid[len - t]--;
}
unsigned long long solve(int hh, int ww, int recur)
{
int t, cx, cy, x;
h = hh, w = ww;
if (h & 1) t = w, w = h, h = t;
if (h & 1) return 0;
if (w == 1) return 1;
if (w == 2) return h;
if (h == 2) return w;
cy = h / 2, cx = w / 2;
len = (h + 1) * (w + 1);
grid = realloc(grid, len);
memset(grid, 0, len--);
next[0] = -1;
next[1] = -w - 1;
next[2] = 1;
next[3] = w + 1;
if (recur) cnt = 0;
for (x = cx + 1; x < w; x++) {
t = cy * (w + 1) + x;
grid[t] = 1;
grid[len - t] = 1;
walk(cy - 1, x);
}
cnt++;
if (h == w)
cnt *= 2;
else if (!(w & 1) && recur)
solve(w, h, 0);
return cnt;
}
int main()
{
int y, x;
for (y = 1; y <= 10; y++)
for (x = 1; x <= y; x++)
if (!(x & 1) || !(y & 1))
printf("%d x %d: %llu\n", y, x, solve(y, x, 1));
return 0;
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char byte;
byte *grid = 0;
int w, h, len;
unsigned long long cnt;
static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
void walk(int y, int x)
{
int i, t;
if (!y || y == h || !x || x == w) {
cnt += 2;
return;
}
t = y * (w + 1) + x;
grid[t]++, grid[len - t]++;
for (i = 0; i < 4; i++)
if (!grid[t + next[i]])
walk(y + dir[i][0], x + dir[i][1]);
grid[t]--, grid[len - t]--;
}
unsigned long long solve(int hh, int ww, int recur)
{
int t, cx, cy, x;
h = hh, w = ww;
if (h & 1) t = w, w = h, h = t;
if (h & 1) return 0;
if (w == 1) return 1;
if (w == 2) return h;
if (h == 2) return w;
cy = h / 2, cx = w / 2;
len = (h + 1) * (w + 1);
grid = realloc(grid, len);
memset(grid, 0, len--);
next[0] = -1;
next[1] = -w - 1;
next[2] = 1;
next[3] = w + 1;
if (recur) cnt = 0;
for (x = cx + 1; x < w; x++) {
t = cy * (w + 1) + x;
grid[t] = 1;
grid[len - t] = 1;
walk(cy - 1, x);
}
cnt++;
if (h == w)
cnt *= 2;
else if (!(w & 1) && recur)
solve(w, h, 0);
return cnt;
}
int main()
{
int y, x;
for (y = 1; y <= 10; y++)
for (x = 1; x <= y; x++)
if (!(x & 1) || !(y & 1))
printf("%d x %d: %llu\n", y, x, solve(y, x, 1));
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(mertens_numbers(max));
std::cout << "First 199 Mertens numbers:\n";
for (int i = 0, column = 0; i < 200; ++i) {
if (column > 0)
std::cout << ' ';
if (i == 0)
std::cout << " ";
else
std::cout << std::setw(2) << m[i];
++column;
if (column == 20) {
std::cout << '\n';
column = 0;
}
}
int zero = 0, cross = 0, previous = 0;
for (int i = 1; i <= max; ++i) {
if (m[i] == 0) {
++zero;
if (previous != 0)
++cross;
}
previous = m[i];
}
std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n";
std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
int* mertens_numbers(int max) {
int* m = malloc((max + 1) * sizeof(int));
if (m == NULL)
return m;
m[1] = 1;
for (int n = 2; n <= max; ++n) {
m[n] = 1;
for (int k = 2; k <= n; ++k)
m[n] -= m[n/k];
}
return m;
}
int main() {
const int max = 1000;
int* mertens = mertens_numbers(max);
if (mertens == NULL) {
fprintf(stderr, "Out of memory\n");
return 1;
}
printf("First 199 Mertens numbers:\n");
const int count = 200;
for (int i = 0, column = 0; i < count; ++i) {
if (column > 0)
printf(" ");
if (i == 0)
printf(" ");
else
printf("%2d", mertens[i]);
++column;
if (column == 20) {
printf("\n");
column = 0;
}
}
int zero = 0, cross = 0, previous = 0;
for (int i = 1; i <= max; ++i) {
int m = mertens[i];
if (m == 0) {
++zero;
if (previous != 0)
++cross;
}
previous = m;
}
free(mertens);
printf("M(n) is zero %d times for 1 <= n <= %d.\n", zero, max);
printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max);
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false;
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
return !response.empty() && response.front() == 'y';
}
void PrintOrder(const vector<string>& items)
{
cout << "{ ";
for(auto& item : items) cout << item << " ";
cout << "}\n";
}
int main()
{
const vector<string> items
{
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
};
vector<string> sortedItems;
for(auto& item : items)
{
cout << "Inserting '" << item << "' into ";
PrintOrder(sortedItems);
auto spotToInsert = lower_bound(sortedItems.begin(),
sortedItems.end(), item, InteractiveCompare);
sortedItems.insert(spotToInsert, item);
}
PrintOrder(sortedItems);
return 0;
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int interactiveCompare(const void *x1, const void *x2)
{
const char *s1 = *(const char * const *)x1;
const char *s2 = *(const char * const *)x2;
static int count = 0;
printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2);
int response;
scanf("%d", &response);
return response;
}
void printOrder(const char *items[], int len)
{
printf("{ ");
for (int i = 0; i < len; ++i) printf("%s ", items[i]);
printf("}\n");
}
int main(void)
{
const char *items[] =
{
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
};
qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);
printOrder(items, sizeof(items)/sizeof(*items));
return 0;
}
|
Write a version of this C++ function in C with identical behavior. |
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
float *benford_distribution(void)
{
static float prob[9];
for (int i = 1; i < 10; i++)
prob[i - 1] = log10f(1 + 1.0 / i);
return prob;
}
float *get_actual_distribution(char *fn)
{
FILE *input = fopen(fn, "r");
if (!input)
{
perror("Can't open file");
exit(EXIT_FAILURE);
}
int tally[9] = { 0 };
char c;
int total = 0;
while ((c = getc(input)) != EOF)
{
while (c < '1' || c > '9')
c = getc(input);
tally[c - '1']++;
total++;
while ((c = getc(input)) != '\n' && c != EOF)
;
}
fclose(input);
static float freq[9];
for (int i = 0; i < 9; i++)
freq[i] = tally[i] / (float) total;
return freq;
}
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Usage: benford <file>\n");
return EXIT_FAILURE;
}
float *actual = get_actual_distribution(argv[1]);
float *expected = benford_distribution();
puts("digit\tactual\texpected");
for (int i = 0; i < 9; i++)
printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]);
return EXIT_SUCCESS;
}
|
Produce a functionally identical C code for the snippet given in C++. |
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
float *benford_distribution(void)
{
static float prob[9];
for (int i = 1; i < 10; i++)
prob[i - 1] = log10f(1 + 1.0 / i);
return prob;
}
float *get_actual_distribution(char *fn)
{
FILE *input = fopen(fn, "r");
if (!input)
{
perror("Can't open file");
exit(EXIT_FAILURE);
}
int tally[9] = { 0 };
char c;
int total = 0;
while ((c = getc(input)) != EOF)
{
while (c < '1' || c > '9')
c = getc(input);
tally[c - '1']++;
total++;
while ((c = getc(input)) != '\n' && c != EOF)
;
}
fclose(input);
static float freq[9];
for (int i = 0; i < 9; i++)
freq[i] = tally[i] / (float) total;
return freq;
}
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Usage: benford <file>\n");
return EXIT_FAILURE;
}
float *actual = get_actual_distribution(argv[1]);
float *expected = benford_distribution();
puts("digit\tactual\texpected");
for (int i = 0; i < 9; i++)
printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]);
return EXIT_SUCCESS;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
class bells
{
public:
void start()
{
watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First";
count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
}
private:
static DWORD WINAPI bell( LPVOID p )
{
DWORD wait = _inst->waitTime();
while( true )
{
Sleep( wait );
_inst->playBell();
wait = _inst->waitTime();
}
return 0;
}
DWORD waitTime()
{
GetLocalTime( &st );
int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
}
void playBell()
{
GetLocalTime( &st );
int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
int w = ( 60 * st.wHour + st.wMinute );
if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );
cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;
for( int x = 0, c = 1; x < b; x++, c++ )
{
cout << "\7"; Sleep( 500 );
if( !( c % 2 ) ) Sleep( 300 );
}
}
SYSTEMTIME st;
string watch[7], count[8];
static bells* _inst;
};
bells* bells::_inst = 0;
int main( int argc, char* argv[] )
{
bells b; b.start();
while( 1 );
return 0;
}
| #include<unistd.h>
#include<stdio.h>
#include<time.h>
#define SHORTLAG 1000
#define LONGLAG 2000
int main(){
int i,times,hour,min,sec,min1,min2;
time_t t;
struct tm* currentTime;
while(1){
time(&t);
currentTime = localtime(&t);
hour = currentTime->tm_hour;
min = currentTime->tm_min;
sec = currentTime->tm_sec;
hour = 12;
min = 0;
sec = 0;
if((min==0 || min==30) && sec==0)
times = ((hour*60 + min)%240)%8;
if(times==0){
times = 8;
}
if(min==0){
min1 = 0;
min2 = 0;
}
else{
min1 = 3;
min2 = 0;
}
if((min==0 || min==30) && sec==0){
printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times);
for(i=1;i<=times;i++){
printf("\a");
(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);
}
}
}
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
class bells
{
public:
void start()
{
watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First";
count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
}
private:
static DWORD WINAPI bell( LPVOID p )
{
DWORD wait = _inst->waitTime();
while( true )
{
Sleep( wait );
_inst->playBell();
wait = _inst->waitTime();
}
return 0;
}
DWORD waitTime()
{
GetLocalTime( &st );
int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
}
void playBell()
{
GetLocalTime( &st );
int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
int w = ( 60 * st.wHour + st.wMinute );
if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );
cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;
for( int x = 0, c = 1; x < b; x++, c++ )
{
cout << "\7"; Sleep( 500 );
if( !( c % 2 ) ) Sleep( 300 );
}
}
SYSTEMTIME st;
string watch[7], count[8];
static bells* _inst;
};
bells* bells::_inst = 0;
int main( int argc, char* argv[] )
{
bells b; b.start();
while( 1 );
return 0;
}
| #include<unistd.h>
#include<stdio.h>
#include<time.h>
#define SHORTLAG 1000
#define LONGLAG 2000
int main(){
int i,times,hour,min,sec,min1,min2;
time_t t;
struct tm* currentTime;
while(1){
time(&t);
currentTime = localtime(&t);
hour = currentTime->tm_hour;
min = currentTime->tm_min;
sec = currentTime->tm_sec;
hour = 12;
min = 0;
sec = 0;
if((min==0 || min==30) && sec==0)
times = ((hour*60 + min)%240)%8;
if(times==0){
times = 8;
}
if(min==0){
min1 = 0;
min2 = 0;
}
else{
min1 = 3;
min2 = 0;
}
if((min==0 || min==30) && sec==0){
printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times);
for(i=1;i<=times;i++){
printf("\a");
(i%2==0)?sleep(LONGLAG):sleep(SHORTLAG);
}
}
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | double fib(double n)
{
if(n < 0)
{
throw "Invalid argument passed to fib";
}
else
{
struct actual_fib
{
static double calc(double n)
{
if(n < 2)
{
return n;
}
else
{
return calc(n-1) + calc(n-2);
}
}
};
return actual_fib::calc(n);
}
}
| #include <stdio.h>
long fib(long x)
{
long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };
if (x < 0) {
printf("Bad argument: fib(%ld)\n", x);
return -1;
}
return fib_i(x);
}
long fib_i(long n)
{
printf("This is not the fib you are looking for\n");
return -1;
}
int main()
{
long x;
for (x = -1; x < 4; x ++)
printf("fib %ld = %ld\n", x, fib(x));
printf("calling fib_i from outside fib:\n");
fib_i(3);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <windows.h>
#include <ctime>
#include <iostream>
#include <string>
const int WID = 60, HEI = 30, MAX_LEN = 600;
enum DIR { NORTH, EAST, SOUTH, WEST };
class snake {
public:
snake() {
console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( "Snake" );
COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );
SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );
CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );
}
void play() {
std::string a;
while( 1 ) {
createField(); alive = true;
while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }
COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );
SetConsoleTextAttribute( console, 0x000b );
std::cout << "Play again [Y/N]? "; std::cin >> a;
if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;
}
}
private:
void createField() {
COORD coord = { 0, 0 }; DWORD c;
FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );
FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );
SetConsoleCursorPosition( console, coord );
int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;
for( x = 0; x < WID; x++ ) {
brd[x] = brd[x + WID * ( HEI - 1 )] = '+';
}
for( ; y < HEI; y++ ) {
brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';
}
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@';
tailIdx = 0; headIdx = 4; x = 3; y = 2;
for( int c = tailIdx; c < headIdx; c++ ) {
brd[x + WID * y] = '#';
snk[c].X = 3 + c; snk[c].Y = 2;
}
head = snk[3]; dir = EAST; points = 0;
}
void readKey() {
if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;
if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;
if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;
if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;
}
void drawField() {
COORD coord; char t;
for( int y = 0; y < HEI; y++ ) {
coord.Y = y;
for( int x = 0; x < WID; x++ ) {
t = brd[x + WID * y]; if( !t ) continue;
coord.X = x; SetConsoleCursorPosition( console, coord );
if( coord.X == head.X && coord.Y == head.Y ) {
SetConsoleTextAttribute( console, 0x002e );
std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );
continue;
}
switch( t ) {
case '#': SetConsoleTextAttribute( console, 0x002a ); break;
case '+': SetConsoleTextAttribute( console, 0x0019 ); break;
case '@': SetConsoleTextAttribute( console, 0x004c ); break;
}
std::cout << t; SetConsoleTextAttribute( console, 0x0000 );
}
}
std::cout << t; SetConsoleTextAttribute( console, 0x0007 );
COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );
std::cout << "Points: " << points;
}
void moveSnake() {
switch( dir ) {
case NORTH: head.Y--; break;
case EAST: head.X++; break;
case SOUTH: head.Y++; break;
case WEST: head.X--; break;
}
char t = brd[head.X + WID * head.Y];
if( t && t != '@' ) { alive = false; return; }
brd[head.X + WID * head.Y] = '#';
snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;
if( ++headIdx >= MAX_LEN ) headIdx = 0;
if( t == '@' ) {
points++; int x, y;
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@'; return;
}
SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';
brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;
if( ++tailIdx >= MAX_LEN ) tailIdx = 0;
}
bool alive; char brd[WID * HEI];
HANDLE console; DIR dir; COORD snk[MAX_LEN];
COORD head; int tailIdx, headIdx, points;
};
int main( int argc, char* argv[] ) {
srand( static_cast<unsigned>( time( NULL ) ) );
snake s; s.play(); return 0;
}
|
char nonblocking_getch();
void positional_putch(int x, int y, char ch);
void millisecond_sleep(int n);
void init_screen();
void update_screen();
void close_screen();
#ifdef __linux__
#define _POSIX_C_SOURCE 200809L
#include <time.h>
#include <ncurses.h>
char nonblocking_getch() { return getch(); }
void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }
void millisecond_sleep(int n) {
struct timespec t = { 0, n * 1000000 };
nanosleep(&t, 0);
}
void update_screen() { refresh(); }
void init_screen() {
initscr();
noecho();
cbreak();
nodelay(stdscr, TRUE);
}
void close_screen() { endwin(); }
#endif
#ifdef _WIN32
#error "not implemented"
#endif
#include <time.h>
#include <stdlib.h>
#define w 80
#define h 40
int board[w * h];
int head;
enum Dir { N, E, S, W } dir;
int quit;
enum State { SPACE=0, FOOD=1, BORDER=2 };
void age() {
int i;
for(i = 0; i < w * h; ++i)
if(board[i] < 0)
++board[i];
}
void plant() {
int r;
do
r = rand() % (w * h);
while(board[r] != SPACE);
board[r] = FOOD;
}
void start(void) {
int i;
for(i = 0; i < w; ++i)
board[i] = board[i + (h - 1) * w] = BORDER;
for(i = 0; i < h; ++i)
board[i * w] = board[i * w + w - 1] = BORDER;
head = w * (h - 1 - h % 2) / 2;
board[head] = -5;
dir = N;
quit = 0;
srand(time(0));
plant();
}
void step() {
int len = board[head];
switch(dir) {
case N: head -= w; break;
case S: head += w; break;
case W: --head; break;
case E: ++head; break;
}
switch(board[head]) {
case SPACE:
board[head] = len - 1;
age();
break;
case FOOD:
board[head] = len - 1;
plant();
break;
default:
quit = 1;
}
}
void show() {
const char * symbol = " @.";
int i;
for(i = 0; i < w * h; ++i)
positional_putch(i / w, i % w,
board[i] < 0 ? '#' : symbol[board[i]]);
update_screen();
}
int main (int argc, char * argv[]) {
init_screen();
start();
do {
show();
switch(nonblocking_getch()) {
case 'i': dir = N; break;
case 'j': dir = W; break;
case 'k': dir = S; break;
case 'l': dir = E; break;
case 'q': quit = 1; break;
}
step();
millisecond_sleep(100);
}
while(!quit);
millisecond_sleep(999);
close_screen();
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
| #include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char ** argv ){
const char * str_a = "knight";
const char * str_b = "socks";
const char * str_c = "brooms";
char * new_a = malloc( strlen( str_a ) - 1 );
char * new_b = malloc( strlen( str_b ) - 1 );
char * new_c = malloc( strlen( str_c ) - 2 );
strcpy( new_a, str_a + 1 );
strncpy( new_b, str_b, strlen( str_b ) - 1 );
strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );
printf( "%s\n%s\n%s\n", new_a, new_b, new_c );
free( new_a );
free( new_b );
free( new_c );
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
| #include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char ** argv ){
const char * str_a = "knight";
const char * str_b = "socks";
const char * str_c = "brooms";
char * new_a = malloc( strlen( str_a ) - 1 );
char * new_b = malloc( strlen( str_b ) - 1 );
char * new_c = malloc( strlen( str_c ) - 2 );
strcpy( new_a, str_a + 1 );
strncpy( new_b, str_b, strlen( str_b ) - 1 );
strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );
printf( "%s\n%s\n%s\n", new_a, new_b, new_c );
free( new_a );
free( new_b );
free( new_c );
return 0;
}
|
Translate this program into C but keep the logic exactly as in C++. | #include <cmath>
#include <iostream>
#include <vector>
std::vector<int> generate_primes(int limit) {
std::vector<bool> sieve(limit >> 1, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
class legendre_prime_counter {
public:
explicit legendre_prime_counter(int limit);
int prime_count(int n);
private:
int phi(int x, int a);
std::vector<int> primes;
};
legendre_prime_counter::legendre_prime_counter(int limit) :
primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}
int legendre_prime_counter::prime_count(int n) {
if (n < 2)
return 0;
int a = prime_count(static_cast<int>(std::sqrt(n)));
return phi(n, a) + a - 1;
}
int legendre_prime_counter::phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes[a - 1];
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
int main() {
legendre_prime_counter counter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
std::cout << "10^" << i << "\t" << counter.prime_count(n) << '\n';
}
| #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
const uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};
#define half(n) ((int64_t)((n) - 1) >> 1)
#define divide(nm, d) ((uint64_t)((double)nm / (double)d))
int64_t countPrimes(uint64_t n) {
if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2;
uint64_t rtlmt = (uint64_t)sqrt((double)n);
int64_t mxndx = (int64_t)((rtlmt - 1) / 2);
int arrlen = (int)(mxndx + 1);
uint32_t *smalls = malloc(arrlen * 4);
uint32_t *roughs = malloc(arrlen * 4);
int64_t *larges = malloc(arrlen * 8);
for (int i = 0; i < arrlen; ++i) {
smalls[i] = (uint32_t)i;
roughs[i] = (uint32_t)(i + i + 1);
larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2);
}
int cullbuflen = (int)((mxndx + 8) / 8);
uint8_t *cullbuf = calloc(cullbuflen, 1);
int64_t nbps = 0;
int rilmt = arrlen;
for (int64_t i = 1; ; ++i) {
int64_t sqri = (i + i) * (i + 1);
if (sqri > mxndx) break;
if (cullbuf[i >> 3] & masks[i & 7]) continue;
cullbuf[i >> 3] |= masks[i & 7];
uint64_t bp = (uint64_t)(i + i + 1);
for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) {
cullbuf[c >> 3] |= masks[c & 7];
}
int nri = 0;
for (int ori = 0; ori < rilmt; ++ori) {
uint32_t r = roughs[ori];
int64_t rci = (int64_t)(r >> 1);
if (cullbuf[rci >> 3] & masks[rci & 7]) continue;
uint64_t d = (uint64_t)r * bp;
int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] :
(int64_t)smalls[half(divide(n, d))];
larges[nri] = larges[ori] - t + nbps;
roughs[nri] = r;
nri++;
}
int64_t si = mxndx;
for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) {
uint32_t c = smalls[pm >> 1];
uint64_t e = (pm * bp) >> 1;
for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps;
}
rilmt = nri;
nbps++;
}
int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2);
int ri, sri;
for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri];
for (ri = 1; ; ++ri) {
uint64_t p = (uint64_t)roughs[ri];
uint64_t m = n / p;
int ei = (int)smalls[half((uint64_t)m/p)] - nbps;
if (ei <= ri) break;
ans -= (int64_t)((ei - ri) * (nbps + ri - 1));
for (sri = ri + 1; sri < ei + 1; ++sri) {
ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))];
}
}
free(smalls);
free(roughs);
free(larges);
free(cullbuf);
return ans + 1;
}
int main() {
uint64_t n;
int i;
clock_t start = clock();
for (i = 0, n = 1; i < 10; ++i, n *= 10) {
printf("10^%d %ld\n", i, countPrimes(n));
}
clock_t end = clock();
printf("\nTook %f seconds\n", (double) (end - start) / CLOCKS_PER_SEC);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #include <string>
using std::string;
extern "C" int
Query (char *Data, size_t *Length)
{
const string Message = "Here am I";
if (*Length < Message.length())
return false;
*Length = Message.length();
Message.copy(Data, *Length);
return true;
}
| #include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}
|
Generate an equivalent C version of this C++ code. | #include <iostream>
#include <string.h>
int main()
{
std::string longLine, longestLines, newLine;
while (std::cin >> newLine)
{
auto isNewLineShorter = longLine.c_str();
auto isLongLineShorter = newLine.c_str();
while (*isNewLineShorter && *isLongLineShorter)
{
isNewLineShorter = &isNewLineShorter[1];
isLongLineShorter = &isLongLineShorter[1];
}
if(*isNewLineShorter) continue;
if(*isLongLineShorter)
{
longLine = newLine;
longestLines = newLine;
}
else
{
longestLines+=newLine;
}
longestLines+="\n";
}
std::cout << "\nLongest string:\n" << longestLines;
}
| #include <stdio.h>
#include <string.h>
int cmp(const char *p, const char *q)
{
while (*p && *q) p = &p[1], q = &q[1];
return *p;
}
int main()
{
char line[65536];
char buf[1000000] = {0};
char *last = buf;
char *next = buf;
while (gets(line)) {
strcat(line, "\n");
if (cmp(last, line)) continue;
if (cmp(line, last)) next = buf;
last = next;
strcpy(next, line);
while (*next) next = &next[1];
}
printf("%s", buf);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
| #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
enum {
LEFT,
RIGHT,
STAY
};
typedef struct {
int state1;
int symbol1;
int symbol2;
int dir;
int state2;
} transition_t;
typedef struct tape_t tape_t;
struct tape_t {
int symbol;
tape_t *left;
tape_t *right;
};
typedef struct {
int states_len;
char **states;
int final_states_len;
int *final_states;
int symbols_len;
char *symbols;
int blank;
int state;
int tape_len;
tape_t *tape;
int transitions_len;
transition_t ***transitions;
} turing_t;
int state_index (turing_t *t, char *state) {
int i;
for (i = 0; i < t->states_len; i++) {
if (!strcmp(t->states[i], state)) {
return i;
}
}
return 0;
}
int symbol_index (turing_t *t, char symbol) {
int i;
for (i = 0; i < t->symbols_len; i++) {
if (t->symbols[i] == symbol) {
return i;
}
}
return 0;
}
void move (turing_t *t, int dir) {
tape_t *orig = t->tape;
if (dir == RIGHT) {
if (orig && orig->right) {
t->tape = orig->right;
}
else {
t->tape = calloc(1, sizeof (tape_t));
t->tape->symbol = t->blank;
if (orig) {
t->tape->left = orig;
orig->right = t->tape;
}
}
}
else if (dir == LEFT) {
if (orig && orig->left) {
t->tape = orig->left;
}
else {
t->tape = calloc(1, sizeof (tape_t));
t->tape->symbol = t->blank;
if (orig) {
t->tape->right = orig;
orig->left = t->tape;
}
}
}
}
turing_t *create (int states_len, ...) {
va_list args;
va_start(args, states_len);
turing_t *t = malloc(sizeof (turing_t));
t->states_len = states_len;
t->states = malloc(states_len * sizeof (char *));
int i;
for (i = 0; i < states_len; i++) {
t->states[i] = va_arg(args, char *);
}
t->final_states_len = va_arg(args, int);
t->final_states = malloc(t->final_states_len * sizeof (int));
for (i = 0; i < t->final_states_len; i++) {
t->final_states[i] = state_index(t, va_arg(args, char *));
}
t->symbols_len = va_arg(args, int);
t->symbols = malloc(t->symbols_len);
for (i = 0; i < t->symbols_len; i++) {
t->symbols[i] = va_arg(args, int);
}
t->blank = symbol_index(t, va_arg(args, int));
t->state = state_index(t, va_arg(args, char *));
t->tape_len = va_arg(args, int);
t->tape = NULL;
for (i = 0; i < t->tape_len; i++) {
move(t, RIGHT);
t->tape->symbol = symbol_index(t, va_arg(args, int));
}
if (!t->tape_len) {
move(t, RIGHT);
}
while (t->tape->left) {
t->tape = t->tape->left;
}
t->transitions_len = va_arg(args, int);
t->transitions = malloc(t->states_len * sizeof (transition_t **));
for (i = 0; i < t->states_len; i++) {
t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));
}
for (i = 0; i < t->transitions_len; i++) {
transition_t *tran = malloc(sizeof (transition_t));
tran->state1 = state_index(t, va_arg(args, char *));
tran->symbol1 = symbol_index(t, va_arg(args, int));
tran->symbol2 = symbol_index(t, va_arg(args, int));
tran->dir = va_arg(args, int);
tran->state2 = state_index(t, va_arg(args, char *));
t->transitions[tran->state1][tran->symbol1] = tran;
}
va_end(args);
return t;
}
void print_state (turing_t *t) {
printf("%-10s ", t->states[t->state]);
tape_t *tape = t->tape;
while (tape->left) {
tape = tape->left;
}
while (tape) {
if (tape == t->tape) {
printf("[%c]", t->symbols[tape->symbol]);
}
else {
printf(" %c ", t->symbols[tape->symbol]);
}
tape = tape->right;
}
printf("\n");
}
void run (turing_t *t) {
int i;
while (1) {
print_state(t);
for (i = 0; i < t->final_states_len; i++) {
if (t->final_states[i] == t->state) {
return;
}
}
transition_t *tran = t->transitions[t->state][t->tape->symbol];
t->tape->symbol = tran->symbol2;
move(t, tran->dir);
t->state = tran->state2;
}
}
int main () {
printf("Simple incrementer\n");
turing_t *t = create(
2, "q0", "qf",
1, "qf",
2, 'B', '1',
'B',
"q0",
3, '1', '1', '1',
2,
"q0", '1', '1', RIGHT, "q0",
"q0", 'B', '1', STAY, "qf"
);
run(t);
printf("\nThree-state busy beaver\n");
t = create(
4, "a", "b", "c", "halt",
1, "halt",
2, '0', '1',
'0',
"a",
0,
6,
"a", '0', '1', RIGHT, "b",
"a", '1', '1', LEFT, "c",
"b", '0', '1', LEFT, "a",
"b", '1', '1', RIGHT, "b",
"c", '0', '1', LEFT, "b",
"c", '1', '1', STAY, "halt"
);
run(t);
return 0;
printf("\nFive-state two-symbol probable busy beaver\n");
t = create(
6, "A", "B", "C", "D", "E", "H",
1, "H",
2, '0', '1',
'0',
"A",
0,
10,
"A", '0', '1', RIGHT, "B",
"A", '1', '1', LEFT, "C",
"B", '0', '1', RIGHT, "C",
"B", '1', '1', RIGHT, "B",
"C", '0', '1', RIGHT, "D",
"C", '1', '0', LEFT, "E",
"D", '0', '1', LEFT, "A",
"D", '1', '1', LEFT, "D",
"E", '0', '1', STAY, "H",
"E", '1', '0', LEFT, "A"
);
run(t);
}
|
Change the following C++ code into C without altering its purpose. | #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
| #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
enum {
LEFT,
RIGHT,
STAY
};
typedef struct {
int state1;
int symbol1;
int symbol2;
int dir;
int state2;
} transition_t;
typedef struct tape_t tape_t;
struct tape_t {
int symbol;
tape_t *left;
tape_t *right;
};
typedef struct {
int states_len;
char **states;
int final_states_len;
int *final_states;
int symbols_len;
char *symbols;
int blank;
int state;
int tape_len;
tape_t *tape;
int transitions_len;
transition_t ***transitions;
} turing_t;
int state_index (turing_t *t, char *state) {
int i;
for (i = 0; i < t->states_len; i++) {
if (!strcmp(t->states[i], state)) {
return i;
}
}
return 0;
}
int symbol_index (turing_t *t, char symbol) {
int i;
for (i = 0; i < t->symbols_len; i++) {
if (t->symbols[i] == symbol) {
return i;
}
}
return 0;
}
void move (turing_t *t, int dir) {
tape_t *orig = t->tape;
if (dir == RIGHT) {
if (orig && orig->right) {
t->tape = orig->right;
}
else {
t->tape = calloc(1, sizeof (tape_t));
t->tape->symbol = t->blank;
if (orig) {
t->tape->left = orig;
orig->right = t->tape;
}
}
}
else if (dir == LEFT) {
if (orig && orig->left) {
t->tape = orig->left;
}
else {
t->tape = calloc(1, sizeof (tape_t));
t->tape->symbol = t->blank;
if (orig) {
t->tape->right = orig;
orig->left = t->tape;
}
}
}
}
turing_t *create (int states_len, ...) {
va_list args;
va_start(args, states_len);
turing_t *t = malloc(sizeof (turing_t));
t->states_len = states_len;
t->states = malloc(states_len * sizeof (char *));
int i;
for (i = 0; i < states_len; i++) {
t->states[i] = va_arg(args, char *);
}
t->final_states_len = va_arg(args, int);
t->final_states = malloc(t->final_states_len * sizeof (int));
for (i = 0; i < t->final_states_len; i++) {
t->final_states[i] = state_index(t, va_arg(args, char *));
}
t->symbols_len = va_arg(args, int);
t->symbols = malloc(t->symbols_len);
for (i = 0; i < t->symbols_len; i++) {
t->symbols[i] = va_arg(args, int);
}
t->blank = symbol_index(t, va_arg(args, int));
t->state = state_index(t, va_arg(args, char *));
t->tape_len = va_arg(args, int);
t->tape = NULL;
for (i = 0; i < t->tape_len; i++) {
move(t, RIGHT);
t->tape->symbol = symbol_index(t, va_arg(args, int));
}
if (!t->tape_len) {
move(t, RIGHT);
}
while (t->tape->left) {
t->tape = t->tape->left;
}
t->transitions_len = va_arg(args, int);
t->transitions = malloc(t->states_len * sizeof (transition_t **));
for (i = 0; i < t->states_len; i++) {
t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *));
}
for (i = 0; i < t->transitions_len; i++) {
transition_t *tran = malloc(sizeof (transition_t));
tran->state1 = state_index(t, va_arg(args, char *));
tran->symbol1 = symbol_index(t, va_arg(args, int));
tran->symbol2 = symbol_index(t, va_arg(args, int));
tran->dir = va_arg(args, int);
tran->state2 = state_index(t, va_arg(args, char *));
t->transitions[tran->state1][tran->symbol1] = tran;
}
va_end(args);
return t;
}
void print_state (turing_t *t) {
printf("%-10s ", t->states[t->state]);
tape_t *tape = t->tape;
while (tape->left) {
tape = tape->left;
}
while (tape) {
if (tape == t->tape) {
printf("[%c]", t->symbols[tape->symbol]);
}
else {
printf(" %c ", t->symbols[tape->symbol]);
}
tape = tape->right;
}
printf("\n");
}
void run (turing_t *t) {
int i;
while (1) {
print_state(t);
for (i = 0; i < t->final_states_len; i++) {
if (t->final_states[i] == t->state) {
return;
}
}
transition_t *tran = t->transitions[t->state][t->tape->symbol];
t->tape->symbol = tran->symbol2;
move(t, tran->dir);
t->state = tran->state2;
}
}
int main () {
printf("Simple incrementer\n");
turing_t *t = create(
2, "q0", "qf",
1, "qf",
2, 'B', '1',
'B',
"q0",
3, '1', '1', '1',
2,
"q0", '1', '1', RIGHT, "q0",
"q0", 'B', '1', STAY, "qf"
);
run(t);
printf("\nThree-state busy beaver\n");
t = create(
4, "a", "b", "c", "halt",
1, "halt",
2, '0', '1',
'0',
"a",
0,
6,
"a", '0', '1', RIGHT, "b",
"a", '1', '1', LEFT, "c",
"b", '0', '1', LEFT, "a",
"b", '1', '1', RIGHT, "b",
"c", '0', '1', LEFT, "b",
"c", '1', '1', STAY, "halt"
);
run(t);
return 0;
printf("\nFive-state two-symbol probable busy beaver\n");
t = create(
6, "A", "B", "C", "D", "E", "H",
1, "H",
2, '0', '1',
'0',
"A",
0,
10,
"A", '0', '1', RIGHT, "B",
"A", '1', '1', LEFT, "C",
"B", '0', '1', RIGHT, "C",
"B", '1', '1', RIGHT, "B",
"C", '0', '1', RIGHT, "D",
"C", '1', '0', LEFT, "E",
"D", '0', '1', LEFT, "A",
"D", '1', '1', LEFT, "D",
"E", '0', '1', STAY, "H",
"E", '1', '0', LEFT, "A"
);
run(t);
}
|
Keep all operations the same but rewrite the snippet in C. | #include <direct.h>
#include <fstream>
int main() {
std::fstream f("output.txt", std::ios::out);
f.close();
f.open("/output.txt", std::ios::out);
f.close();
_mkdir("docs");
_mkdir("/docs");
return 0;
}
| #include <stdio.h>
int main() {
FILE *fh = fopen("output.txt", "w");
fclose(fh);
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
typedef uint32_t integer;
int count_digits(integer n) {
int digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
integer change_digit(integer n, int index, int new_digit) {
integer p = 1;
integer changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
bool unprimeable(const prime_sieve& sieve, integer n) {
if (sieve.is_prime(n))
return false;
int d = count_digits(n);
for (int i = 0; i < d; ++i) {
for (int j = 0; j <= 9; ++j) {
integer m = change_digit(n, i, j);
if (m != n && sieve.is_prime(m))
return false;
}
}
return true;
}
int main() {
const integer limit = 10000000;
prime_sieve sieve(limit);
std::cout.imbue(std::locale(""));
std::cout << "First 35 unprimeable numbers:\n";
integer n = 100;
integer lowest[10] = { 0 };
for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(sieve, n)) {
if (count < 35) {
if (count != 0)
std::cout << ", ";
std::cout << n;
}
++count;
if (count == 600)
std::cout << "\n600th unprimeable number: " << n << '\n';
int last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
for (int i = 0; i < 10; ++i)
std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
return 0;
}
| #include <assert.h>
#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct bit_array_tag {
uint32_t size;
uint32_t* array;
} bit_array;
bool bit_array_create(bit_array* b, uint32_t size) {
uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));
if (array == NULL)
return false;
b->size = size;
b->array = array;
return true;
}
void bit_array_destroy(bit_array* b) {
free(b->array);
b->array = NULL;
}
void bit_array_set(bit_array* b, uint32_t index, bool value) {
assert(index < b->size);
uint32_t* p = &b->array[index >> 5];
uint32_t bit = 1 << (index & 31);
if (value)
*p |= bit;
else
*p &= ~bit;
}
bool bit_array_get(const bit_array* b, uint32_t index) {
assert(index < b->size);
uint32_t* p = &b->array[index >> 5];
uint32_t bit = 1 << (index & 31);
return (*p & bit) != 0;
}
typedef struct sieve_tag {
uint32_t limit;
bit_array not_prime;
} sieve;
bool sieve_create(sieve* s, uint32_t limit) {
if (!bit_array_create(&s->not_prime, limit/2))
return false;
for (uint32_t p = 3; p * p <= limit; p += 2) {
if (bit_array_get(&s->not_prime, p/2 - 1) == false) {
uint32_t inc = 2 * p;
for (uint32_t q = p * p; q <= limit; q += inc)
bit_array_set(&s->not_prime, q/2 - 1, true);
}
}
s->limit = limit;
return true;
}
void sieve_destroy(sieve* s) {
bit_array_destroy(&s->not_prime);
}
bool is_prime(const sieve* s, uint32_t n) {
assert(n <= s->limit);
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
return bit_array_get(&s->not_prime, n/2 - 1) == false;
}
uint32_t count_digits(uint32_t n) {
uint32_t digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {
uint32_t p = 1;
uint32_t changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
bool unprimeable(const sieve* s, uint32_t n) {
if (is_prime(s, n))
return false;
uint32_t d = count_digits(n);
for (uint32_t i = 0; i < d; ++i) {
for (uint32_t j = 0; j <= 9; ++j) {
uint32_t m = change_digit(n, i, j);
if (m != n && is_prime(s, m))
return false;
}
}
return true;
}
int main() {
const uint32_t limit = 10000000;
setlocale(LC_ALL, "");
sieve s = { 0 };
if (!sieve_create(&s, limit)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
printf("First 35 unprimeable numbers:\n");
uint32_t n = 100;
uint32_t lowest[10] = { 0 };
for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(&s, n)) {
if (count < 35) {
if (count != 0)
printf(", ");
printf("%'u", n);
}
++count;
if (count == 600)
printf("\n600th unprimeable number: %'u\n", n);
uint32_t last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
sieve_destroy(&s);
for (uint32_t i = 0; i < 10; ++i)
printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]);
return 0;
}
|
Translate the given C++ code snippet into C without altering its behavior. | #include <iostream>
#include <iomanip>
inline int sign(int i) {
return i < 0 ? -1 : i > 0;
}
inline int& E(int *x, int row, int col) {
return x[row * (row + 1) / 2 + col];
}
int iter(int *v, int *diff) {
E(v, 0, 0) = 151;
E(v, 2, 0) = 40;
E(v, 4, 1) = 11;
E(v, 4, 3) = 4;
for (auto i = 1u; i < 5u; i++)
for (auto j = 0u; j <= i; j++) {
E(diff, i, j) = 0;
if (j < i)
E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
if (j)
E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
}
for (auto i = 0u; i < 4u; i++)
for (auto j = 0u; j < i; j++)
E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);
E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);
uint sum;
int e = 0;
for (auto i = sum = 0u; i < 15u; i++) {
sum += !!sign(e = diff[i]);
if (e >= 4 || e <= -4)
v[i] += e / 5;
else if (rand() < RAND_MAX / 4)
v[i] += sign(e);
}
return sum;
}
void show(int *x) {
for (auto i = 0u; i < 5u; i++)
for (auto j = 0u; j <= i; j++)
std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}
int main() {
int v[15] = { 0 }, diff[15] = { 0 };
for (auto i = 1u, s = 1u; s; i++) {
s = iter(v, diff);
std::cout << "pass " << i << ": " << s << std::endl;
}
show(v);
return 0;
}
|
#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;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <iostream>
#include <iomanip>
inline int sign(int i) {
return i < 0 ? -1 : i > 0;
}
inline int& E(int *x, int row, int col) {
return x[row * (row + 1) / 2 + col];
}
int iter(int *v, int *diff) {
E(v, 0, 0) = 151;
E(v, 2, 0) = 40;
E(v, 4, 1) = 11;
E(v, 4, 3) = 4;
for (auto i = 1u; i < 5u; i++)
for (auto j = 0u; j <= i; j++) {
E(diff, i, j) = 0;
if (j < i)
E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
if (j)
E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
}
for (auto i = 0u; i < 4u; i++)
for (auto j = 0u; j < i; j++)
E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);
E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);
uint sum;
int e = 0;
for (auto i = sum = 0u; i < 15u; i++) {
sum += !!sign(e = diff[i]);
if (e >= 4 || e <= -4)
v[i] += e / 5;
else if (rand() < RAND_MAX / 4)
v[i] += sign(e);
}
return sum;
}
void show(int *x) {
for (auto i = 0u; i < 5u; i++)
for (auto j = 0u; j <= i; j++)
std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}
int main() {
int v[15] = { 0 }, diff[15] = { 0 };
for (auto i = 1u, s = 1u; s; i++) {
s = iter(v, diff);
std::cout << "pass " << i << ": " << s << std::endl;
}
show(v);
return 0;
}
|
#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 a version of this C++ function in C with identical behavior. | #include <gmp.h>
#include <iostream>
using namespace std;
typedef unsigned long long int u64;
bool 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;
}
bool probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
bool is_chernick(int n, u64 m, mpz_t z) {
if (!primality_pretest(6 * m + 1)) {
return false;
}
if (!primality_pretest(12 * m + 1)) {
return false;
}
u64 t = 9 * m;
for (int i = 1; i <= n - 2; i++) {
if (!primality_pretest((t << i) + 1)) {
return false;
}
}
if (!probprime(6 * m + 1, z)) {
return false;
}
if (!probprime(12 * m + 1, z)) {
return false;
}
for (int i = 1; i <= n - 2; i++) {
if (!probprime((t << i) + 1, z)) {
return false;
}
}
return true;
}
int main() {
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)) {
cout << "a(" << n << ") has m = " << m << endl;
break;
}
}
}
return 0;
}
| #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;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
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 = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::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) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\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);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "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);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
| #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;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
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 = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::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) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\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);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "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);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
| #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;
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #include <iomanip>
#include <iostream>
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;
std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
}
| #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 this C++ snippet to C and keep its semantics consistent. | #include <iomanip>
#include <iostream>
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;
std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
}
| #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 C++ to C, ensuring the logic remains intact. | #include <string>
#include <iostream>
int main()
{
char* data = new char[sizeof(std::string)];
std::string* stringPtr = new (data) std::string("ABCD");
std::cout << *stringPtr << " 0x" << stringPtr << std::endl;
stringPtr->~basic_string();
stringPtr = new (data) std::string("123456");
std::cout << *stringPtr << " 0x" << stringPtr << std::endl;
stringPtr->~basic_string();
delete[] data;
}
| #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;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #include <cstdint>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_probably_prime(const integer& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
int main() {
const unsigned int max = 20;
integer primorial = 1;
for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {
if (!is_prime(p))
continue;
primorial *= p;
++index;
if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {
if (count > 0)
std::cout << ' ';
std::cout << index;
++count;
}
}
std::cout << '\n';
return 0;
}
| #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);
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <map>
#include <string>
#include <iostream>
#include <iomanip>
const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";
class DnaBase {
public:
DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {
for (auto elm : dna) {
if (count.find(elm) == count.end())
count[elm] = 0;
++count[elm];
}
}
void viewGenome() {
std::cout << "Sequence:" << std::endl;
std::cout << std::endl;
int limit = genome.size() / displayWidth;
if (genome.size() % displayWidth != 0)
++limit;
for (int i = 0; i < limit; ++i) {
int beginPos = i * displayWidth;
std::cout << std::setw(4) << beginPos << " :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;
}
std::cout << std::endl;
std::cout << "Base Count" << std::endl;
std::cout << "----------" << std::endl;
std::cout << std::endl;
int total = 0;
for (auto elm : count) {
std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl;
total += elm.second;
}
std::cout << std::endl;
std::cout << "Total: " << total << std::endl;
}
private:
std::string genome;
std::map<char, int> count;
int displayWidth;
};
int main(void) {
auto d = new DnaBase();
d->viewGenome();
delete d;
return 0;
}
| #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;
}
|
Write the same code in C as shown below in C++. | #include <map>
#include <string>
#include <iostream>
#include <iomanip>
const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";
class DnaBase {
public:
DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {
for (auto elm : dna) {
if (count.find(elm) == count.end())
count[elm] = 0;
++count[elm];
}
}
void viewGenome() {
std::cout << "Sequence:" << std::endl;
std::cout << std::endl;
int limit = genome.size() / displayWidth;
if (genome.size() % displayWidth != 0)
++limit;
for (int i = 0; i < limit; ++i) {
int beginPos = i * displayWidth;
std::cout << std::setw(4) << beginPos << " :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;
}
std::cout << std::endl;
std::cout << "Base Count" << std::endl;
std::cout << "----------" << std::endl;
std::cout << std::endl;
int total = 0;
for (auto elm : count) {
std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl;
total += elm.second;
}
std::cout << std::endl;
std::cout << "Total: " << total << std::endl;
}
private:
std::string genome;
std::map<char, int> count;
int displayWidth;
};
int main(void) {
auto d = new DnaBase();
d->viewGenome();
delete d;
return 0;
}
| #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;
}
|
Translate this program into C but keep the logic exactly as in C++. | #include <algorithm>
#include <array>
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <string>
#include <string_view>
#include <thread>
const int timeScale = 42;
void Message(std::string_view message)
{
static std::mutex cout_mutex;
std::scoped_lock cout_lock(cout_mutex);
std::cout << message << std::endl;
}
struct Fork {
std::mutex mutex;
};
struct Dinner {
std::array<Fork, 5> forks;
~Dinner() { Message("Dinner is over"); }
};
class Philosopher
{
std::mt19937 rng{std::random_device {}()};
const std::string name;
Fork& left;
Fork& right;
std::thread worker;
void live();
void dine();
void ponder();
public:
Philosopher(std::string name_, Fork& l, Fork& r)
: name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)
{}
~Philosopher()
{
worker.join();
Message(name + " went to sleep.");
}
};
void Philosopher::live()
{
for(;;)
{
{
std::scoped_lock dine_lock(left.mutex, right.mutex);
dine();
}
ponder();
}
}
void Philosopher::dine()
{
Message(name + " started eating.");
thread_local std::array<const char*, 3> foods {"chicken", "rice", "soda"};
thread_local std::array<const char*, 3> reactions {
"I like this %s!", "This %s is good.", "Mmm, %s..."
};
thread_local std::uniform_int_distribution<> dist(1, 6);
std::shuffle( foods.begin(), foods.end(), rng);
std::shuffle(reactions.begin(), reactions.end(), rng);
constexpr size_t buf_size = 64;
char buffer[buf_size];
for(int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));
snprintf(buffer, buf_size, reactions[i], foods[i]);
Message(name + ": " + buffer);
}
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);
Message(name + " finished and left.");
}
void Philosopher::ponder()
{
static constexpr std::array<const char*, 5> topics {{
"politics", "art", "meaning of life", "source of morality", "how many straws makes a bale"
}};
thread_local std::uniform_int_distribution<> wait(1, 6);
thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);
while(dist(rng) > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is pondering about " + topics[dist(rng)] + ".");
}
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is hungry again!");
}
int main()
{
Dinner dinner;
Message("Dinner started!");
std::array<Philosopher, 5> philosophers {{
{"Aristotle", dinner.forks[0], dinner.forks[1]},
{"Democritus", dinner.forks[1], dinner.forks[2]},
{"Plato", dinner.forks[2], dinner.forks[3]},
{"Pythagoras", dinner.forks[3], dinner.forks[4]},
{"Socrates", dinner.forks[4], dinner.forks[0]},
}};
Message("It is dark outside...");
}
| #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);
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return sum == i;
}
private:
ulong f[12];
};
int main() {
factorion_t factorion;
for (uint b = 9u; b <= 12u; ++b) {
std::cout << "factorions for base " << b << ':';
for (uint i = 1u; i < 1500000u; ++i)
if (factorion(i, b))
std::cout << ' ' << i;
std::cout << std::endl;
}
return 0;
}
| #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;
}
|
Translate the given C++ code snippet into C without altering its behavior. | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return sum == i;
}
private:
ulong f[12];
};
int main() {
factorion_t factorion;
for (uint b = 9u; b <= 12u; ++b) {
std::cout << "factorions for base " << b << ':';
for (uint i = 1u; i < 1500000u; ++i)
if (factorion(i, b))
std::cout << ' ' << i;
std::cout << std::endl;
}
return 0;
}
| #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;
}
|
Produce a functionally identical C code for the snippet given in C++. | #include <cmath>
#include <functional>
#include <iostream>
constexpr double K = 7.8e9;
constexpr int n0 = 27;
constexpr 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
};
double f(double r) {
double sq = 0;
constexpr size_t len = std::size(actual);
for (size_t i = 0; i < len; ++i) {
double eri = std::exp(r * i);
double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K);
double diff = guess - actual[i];
sq += diff * diff;
}
return sq;
}
double solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) {
for (double 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;
}
int main() {
double r = solve(f);
double R0 = std::exp(12 * r);
std::cout << "r = " << r << ", R0 = " << R0 << '\n';
return 0;
}
| #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;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <list>
template <typename T>
std::list<T> strandSort(std::list<T> lst) {
if (lst.size() <= 1)
return lst;
std::list<T> result;
std::list<T> sorted;
while (!lst.empty()) {
sorted.push_back(lst.front());
lst.pop_front();
for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) {
if (sorted.back() <= *it) {
sorted.push_back(*it);
it = lst.erase(it);
} else
it++;
}
result.merge(sorted);
}
return result;
}
| #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;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <iomanip>
#include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int digit_sum(unsigned int n) {
unsigned int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
int main() {
const unsigned int limit = 500;
std::cout << "Additive primes less than " << limit << ":\n";
unsigned int count = 0;
for (unsigned int n = 1; n < limit; ++n) {
if (is_prime(digit_sum(n)) && is_prime(n)) {
std::cout << std::setw(3) << n;
if (++count % 10 == 0)
std::cout << '\n';
else
std::cout << ' ';
}
}
std::cout << '\n' << count << " additive primes found.\n";
}
| #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;
}
|
Keep all operations the same but rewrite the snippet in C. | class invertedAssign {
int data;
public:
invertedAssign(int data):data(data){}
int getData(){return data;}
void operator=(invertedAssign& other) const {
other.data = this->data;
}
};
#include <iostream>
int main(){
invertedAssign a = 0;
invertedAssign b = 42;
std::cout << a.getData() << ' ' << b.getData() << '\n';
b = a;
std::cout << a.getData() << ' ' << b.getData() << '\n';
}
| #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);
}
|
Translate this program into C but keep the logic exactly as in C++. | class invertedAssign {
int data;
public:
invertedAssign(int data):data(data){}
int getData(){return data;}
void operator=(invertedAssign& other) const {
other.data = this->data;
}
};
#include <iostream>
int main(){
invertedAssign a = 0;
invertedAssign b = 42;
std::cout << a.getData() << ' ' << b.getData() << '\n';
b = a;
std::cout << a.getData() << ' ' << b.getData() << '\n';
}
| #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);
}
|
Generate an equivalent C version of this C++ code. | class invertedAssign {
int data;
public:
invertedAssign(int data):data(data){}
int getData(){return data;}
void operator=(invertedAssign& other) const {
other.data = this->data;
}
};
#include <iostream>
int main(){
invertedAssign a = 0;
invertedAssign b = 42;
std::cout << a.getData() << ' ' << b.getData() << '\n';
b = a;
std::cout << a.getData() << ' ' << b.getData() << '\n';
}
| #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);
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
bool perfect_totient_number(const totient_calculator& tc, int n) {
int sum = 0;
for (int m = n; m > 1; ) {
int t = tc.totient(m);
sum += t;
m = t;
}
return sum == n;
}
int main() {
totient_calculator tc(10000);
int count = 0, n = 1;
std::cout << "First 20 perfect totient numbers:\n";
for (; count < 20; ++n) {
if (perfect_totient_number(tc, n)) {
if (count > 0)
std::cout << ' ';
++count;
std::cout << n;
}
}
std::cout << '\n';
return 0;
}
| #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;
}
|
Produce a functionally identical C code for the snippet given in C++. | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
bool perfect_totient_number(const totient_calculator& tc, int n) {
int sum = 0;
for (int m = n; m > 1; ) {
int t = tc.totient(m);
sum += t;
m = t;
}
return sum == n;
}
int main() {
totient_calculator tc(10000);
int count = 0, n = 1;
std::cout << "First 20 perfect totient numbers:\n";
for (; count < 20; ++n) {
if (perfect_totient_number(tc, n)) {
if (count > 0)
std::cout << ' ';
++count;
std::cout << n;
}
}
std::cout << '\n';
return 0;
}
| #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;
}
|
Produce a functionally identical C code for the snippet given in C++. | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
bool perfect_totient_number(const totient_calculator& tc, int n) {
int sum = 0;
for (int m = n; m > 1; ) {
int t = tc.totient(m);
sum += t;
m = t;
}
return sum == n;
}
int main() {
totient_calculator tc(10000);
int count = 0, n = 1;
std::cout << "First 20 perfect totient numbers:\n";
for (; count < 20; ++n) {
if (perfect_totient_number(tc, n)) {
if (count > 0)
std::cout << ' ';
++count;
std::cout << n;
}
}
std::cout << '\n';
return 0;
}
| #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;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace std::tr1;
using std::tr1::function;
class IDelegate
{
public:
virtual ~IDelegate() {}
};
class IThing
{
public:
virtual ~IThing() {}
virtual std::string Thing() = 0;
};
class DelegateA : virtual public IDelegate
{
};
class DelegateB : public IThing, public IDelegate
{
std::string Thing()
{
return "delegate implementation";
}
};
class Delegator
{
public:
std::string Operation()
{
if(Delegate)
if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))
return pThing->Thing();
return "default implementation";
}
shared_ptr<IDelegate> Delegate;
};
int main()
{
shared_ptr<DelegateA> delegateA(new DelegateA());
shared_ptr<DelegateB> delegateB(new DelegateB());
Delegator delegator;
std::cout << delegator.Operation() << std::endl;
delegator.Delegate = delegateA;
std::cout << delegator.Operation() << std::endl;
delegator.Delegate = delegateB;
std::cout << delegator.Operation() << std::endl;
}
| #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;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int 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;
std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(4) << divisor_sum(n);
if (n % 10 == 0)
std::cout << '\n';
}
}
| #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;
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int 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;
std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(4) << divisor_sum(n);
if (n % 10 == 0)
std::cout << '\n';
}
}
| #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;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
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";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
| #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;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
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";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
| #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;
}
|
Generate an equivalent C version of this C++ code. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
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";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
| #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 the given C++ code snippet into C without altering its behavior. | #include <iostream>
class MyOtherClass
{
public:
const int m_x;
MyOtherClass(const int initX = 0) : m_x(initX) { }
};
int main()
{
MyOtherClass mocA, mocB(7);
std::cout << mocA.m_x << std::endl;
std::cout << mocB.m_x << std::endl;
return 0;
}
| #define PI 3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100
|
Port the following code from C++ to C with equivalent syntax and logic. | #include <iostream>
#include <span>
#include <vector>
struct vec2 {
float x = 0.0f, y = 0.0f;
constexpr vec2 operator+(vec2 other) const {
return vec2{x + other.x, y + other.y};
}
constexpr vec2 operator-(vec2 other) const {
return vec2{x - other.x, y - other.y};
}
};
constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }
constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }
constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }
constexpr bool is_inside(vec2 point, vec2 a, vec2 b) {
return (cross(a - b, point) + cross(b, a)) < 0.0f;
}
constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {
return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *
(1.0f / cross(a1 - a2, b1 - b2));
}
std::vector<vec2> suther_land_hodgman(
std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {
if (clip_polygon.empty() || subject_polygon.empty()) {
return {};
}
std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};
vec2 p1 = clip_polygon[clip_polygon.size() - 1];
std::vector<vec2> input;
for (vec2 p2 : clip_polygon) {
input.clear();
input.insert(input.end(), ring.begin(), ring.end());
vec2 s = input[input.size() - 1];
ring.clear();
for (vec2 e : input) {
if (is_inside(e, p1, p2)) {
if (!is_inside(s, p1, p2)) {
ring.push_back(intersection(p1, p2, s, e));
}
ring.push_back(e);
} else if (is_inside(s, p1, p2)) {
ring.push_back(intersection(p1, p2, s, e));
}
s = e;
}
p1 = p2;
}
return ring;
}
int main(int argc, char **argv) {
vec2 subject_polygon[] = {{50, 150}, {200, 50}, {350, 150},
{350, 300}, {250, 300}, {200, 250},
{150, 350}, {100, 250}, {100, 200}};
vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};
std::vector<vec2> clipped_polygon =
suther_land_hodgman(subject_polygon, clip_polygon);
std::cout << "Clipped polygon points:" << std::endl;
for (vec2 p : clipped_polygon) {
std::cout << "(" << p.x << ", " << p.y << ")" << std::endl;
}
return EXIT_SUCCESS;
}
| #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;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
| #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;
}
|
Produce a functionally identical C code for the snippet given in C++. | #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
| #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;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.