Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate an equivalent C version of this C# code. | using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
| #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
|
Write a version of this C# function in C with identical behavior. | using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
| #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
|
Please provide an equivalent version of this C# code in C. | using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
| #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result += ", " + ip.AddressList[i].ToString();
return result;
}
catch (System.Net.Sockets.SocketException se)
{
return se.Message;
}
}
| #include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main()
{
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo("www.kame.net", NULL, &hints, &res0);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
exit(1);
}
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
} else {
printf("%s\n", host);
}
}
freeaddrinfo(res0);
return 0;
}
|
Write the same code in C as shown below in C#. | using System;
public class SevenSidedDice
{
Random random = new Random();
static void Main(string[] args)
{
SevenSidedDice sevenDice = new SevenSidedDice();
Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
Console.Read();
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1 + random.Next(5);
}
}
| int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
int main()
{
printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n");
printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n");
return 0;
}
|
Translate this program into C but keep the logic exactly as in C#. | using System; using static System.Console;
class Program {
static bool[] np;
static void ms(long lmt) {
np = new bool[lmt]; np[0] = np[1] = true;
for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])
for (long k = n * n; k < lmt; k += n) np[k] = true; }
static bool is_Mag(long n) { long res, rem;
for (long p = 10; n >= p; p *= 10) {
res = Math.DivRem (n, p, out rem);
if (np[res + rem]) return false; } return true; }
static void Main(string[] args) { ms(100_009); string mn;
WriteLine("First 45{0}", mn = " magnanimous numbers:");
for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {
if (c++ < 45 || (c > 240 && c <= 250) || c > 390)
Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l);
if (c < 45 && c % 15 == 0) WriteLine();
if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn);
if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } }
}
| #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;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
| #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;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
| #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;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
| #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;
}
|
Generate an equivalent C version of this C# code. | using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
| #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
| #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;
}
|
Translate the given C# code snippet into C without altering its behavior. | using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
| #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;
}
|
Generate an equivalent C version of this C# code. | using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
got -= 2;
while (s[got] == '0' || s[got] == '9') got--;
printf("%.*s", (int)(got - done), s + done);
free(s);
done = got;
accu *= 2;
}
return 0;
}
|
Write a version of this C# function in C with identical behavior. | using System;
static class YCombinator<T, TResult>
{
private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);
public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}
static class Program
{
static void Main()
{
var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));
Console.WriteLine(fac(10));
Console.WriteLine(fib(10));
}
}
| #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;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
|
Produce a language-to-language conversion: from C# to C, same semantics. | using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
|
Write a version of this C# function in C with identical behavior. | using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
|
Change the programming language of this snippet from C# to C without modifying what it does. | using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
|
Port the provided C# code into C while preserving the original functionality. | using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
| for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
|
Convert the following code from C# to C, ensuring the logic remains intact. | using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
| for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
| #include <stdio.h>
#include <stdlib.h>
struct replace_info {
int n;
char *text;
};
int compare(const void *a, const void *b)
{
struct replace_info *x = (struct replace_info *) a;
struct replace_info *y = (struct replace_info *) b;
return x->n - y->n;
}
void generic_fizz_buzz(int max, struct replace_info *info, int info_length)
{
int i, it;
int found_word;
for (i = 1; i < max; ++i) {
found_word = 0;
for (it = 0; it < info_length; ++it) {
if (0 == i % info[it].n) {
printf("%s", info[it].text);
found_word = 1;
}
}
if (0 == found_word)
printf("%d", i);
printf("\n");
}
}
int main(void)
{
struct replace_info info[3] = {
{5, "Buzz"},
{7, "Baxx"},
{3, "Fizz"}
};
qsort(info, 3, sizeof(struct replace_info), compare);
generic_fizz_buzz(20, info, 3);
return 0;
}
|
Translate the given C# code snippet into C without altering its behavior. | using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Generate an equivalent C version of this C# code. | namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
| #include <stdio.h>
#include <stdint.h>
void to_seq(uint64_t x, uint8_t *out)
{
int i, j;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) break;
}
for (j = 0; j <= i; j++)
out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
out[i] ^= 128;
}
uint64_t from_seq(uint8_t *in)
{
uint64_t r = 0;
do {
r = (r << 7) | (uint64_t)(*in & 127);
} while (*in++ & 128);
return r;
}
int main()
{
uint8_t s[10];
uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};
int i, j;
for (j = 0; j < sizeof(x)/8; j++) {
to_seq(x[j], s);
printf("seq from %llx: [ ", x[j]);
i = 0;
do { printf("%02x ", s[i]); } while ((s[i++] & 128));
printf("] back: %llx\n", from_seq(s));
}
return 0;
}
|
Port the following code from C# to C with equivalent syntax and logic. | namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
| #include <stdio.h>
#include <stdint.h>
void to_seq(uint64_t x, uint8_t *out)
{
int i, j;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) break;
}
for (j = 0; j <= i; j++)
out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
out[i] ^= 128;
}
uint64_t from_seq(uint8_t *in)
{
uint64_t r = 0;
do {
r = (r << 7) | (uint64_t)(*in & 127);
} while (*in++ & 128);
return r;
}
int main()
{
uint8_t s[10];
uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};
int i, j;
for (j = 0; j < sizeof(x)/8; j++) {
to_seq(x[j], s);
printf("seq from %llx: [ ", x[j]);
i = 0;
do { printf("%02x ", s[i]); } while ((s[i++] & 128));
printf("] back: %llx\n", from_seq(s));
}
return 0;
}
|
Please provide an equivalent version of this C# code in C. | using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
|
#include <ctype.h>
#include <stdio.h>
void str_toupper(char *s)
{
while(*s)
{
*s=toupper(*s);
s++;
}
}
void str_tolower(char *s)
{
while(*s)
{
*s=tolower(*s);
s++;
}
}
int main(int argc, char *argv[])
{
char t[255]="alphaBETA";
str_toupper(t);
printf("uppercase: %s\n", t);
str_tolower(t);
printf("lowercase: %s\n", t);
return 0;
}
|
Translate this program into C but keep the logic exactly as in C#. | using System.Text;
using System.Security.Cryptography;
byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
const char *string = "The quick brown fox jumped over the lazy dog's back";
int main()
{
int i;
unsigned char result[MD5_DIGEST_LENGTH];
MD5(string, strlen(string), result);
for(i = 0; i < MD5_DIGEST_LENGTH; i++)
printf("%02x", result[i]);
printf("\n");
return EXIT_SUCCESS;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct tm ts;
time_t t;
const char *d = "March 7 2009 7:30pm EST";
strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
t = mktime(&ts);
t += 12*60*60;
printf("%s", ctime(&t));
return EXIT_SUCCESS;
}
|
Produce a functionally identical C code for the snippet given in C#. | class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct tm ts;
time_t t;
const char *d = "March 7 2009 7:30pm EST";
strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
t = mktime(&ts);
t += 12*60*60;
printf("%s", ctime(&t));
return EXIT_SUCCESS;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
}
| >>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
+++++[-<------>]>>+>,----
------<<+[->>>>>+<<<<<]>>
]>>>[<<<<[<<<[->>+<<[->+>
[-]<<]]>[-<+>]>[-<<<.>>>>
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
|
Generate a C translation of this C# snippet without changing its computational steps. | using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
}
| #include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(" %d", a[i][j]);
if (a[i][j] == 20)
goto Done;
}
printf("\n");
}
Done:
printf("\n");
return 0;
}
|
Port the provided C# code into C while preserving the original functionality. | int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
| #include <stdio.h>
#include <stdlib.h>
struct list_node {int x; struct list_node *next;};
typedef struct list_node node;
node * uniq(int *a, unsigned alen)
{if (alen == 0) return NULL;
node *start = malloc(sizeof(node));
if (start == NULL) exit(EXIT_FAILURE);
start->x = a[0];
start->next = NULL;
for (int i = 1 ; i < alen ; ++i)
{node *n = start;
for (;; n = n->next)
{if (a[i] == n->x) break;
if (n->next == NULL)
{n->next = malloc(sizeof(node));
n = n->next;
if (n == NULL) exit(EXIT_FAILURE);
n->x = a[i];
n->next = NULL;
break;}}}
return start;}
int main(void)
{int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};
for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)
printf("%d ", n->x);
puts("");
return 0;}
|
Maintain the same structure and functionality when rewriting this code in C. | using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
|
Translate this program into C but keep the logic exactly as in C#. | using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
|
Translate this program into C but keep the logic exactly as in C#. |
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek();
top = stack.Pop();
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek();
top = stack.Pop();
| #include <stdio.h>
#include <stdlib.h>
#define DECL_STACK_TYPE(type, name) \
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \
stk_##name stk_##name##_create(size_t init_size) { \
stk_##name s; if (!init_size) init_size = 4; \
s = malloc(sizeof(struct stk_##name##_t)); \
if (!s) return 0; \
s->buf = malloc(sizeof(type) * init_size); \
if (!s->buf) { free(s); return 0; } \
s->len = 0, s->alloc = init_size; \
return s; } \
int stk_##name##_push(stk_##name s, type item) { \
type *tmp; \
if (s->len >= s->alloc) { \
tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \
if (!tmp) return -1; s->buf = tmp; \
s->alloc *= 2; } \
s->buf[s->len++] = item; \
return s->len; } \
type stk_##name##_pop(stk_##name s) { \
type tmp; \
if (!s->len) abort(); \
tmp = s->buf[--s->len]; \
if (s->len * 2 <= s->alloc && s->alloc >= 8) { \
s->alloc /= 2; \
s->buf = realloc(s->buf, s->alloc * sizeof(type));} \
return tmp; } \
void stk_##name##_delete(stk_##name s) { \
free(s->buf); free(s); }
#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)
DECL_STACK_TYPE(int, int)
int main(void)
{
int i;
stk_int stk = stk_int_create(0);
printf("pushing: ");
for (i = 'a'; i <= 'z'; i++) {
printf(" %c", i);
stk_int_push(stk, i);
}
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
printf("\npoppoing:");
while (stk_size(stk))
printf(" %c", stk_int_pop(stk));
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
stk_int_delete(stk);
return 0;
}
|
Change the programming language of this snippet from C# to C without modifying what it does. | using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
|
#include<stdio.h>
int totient(int n){
int 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;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);
printf("\n---------------\n");
for(n=1;n<=25;n++){
tot = totient(n);
if(n-1 == tot)
count++;
printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False");
}
printf("\nNumber of primes up to %6d =%4d\n", 25,count);
for(n = 26; n <= 100000; n++){
tot = totient(n);
if(tot == n-1)
count++;
if(n == 100 || n == 1000 || n%10000 == 0){
printf("\nNumber of primes up to %6d = %4d\n", n, count);
}
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
|
#include<stdio.h>
int totient(int n){
int 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;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);
printf("\n---------------\n");
for(n=1;n<=25;n++){
tot = totient(n);
if(n-1 == tot)
count++;
printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False");
}
printf("\nNumber of primes up to %6d =%4d\n", 25,count);
for(n = 26; n <= 100000; n++){
tot = totient(n);
if(tot == n-1)
count++;
if(n == 100 || n == 1000 || n%10000 == 0){
printf("\nNumber of primes up to %6d = %4d\n", n, count);
}
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | if (condition)
{
}
if (condition)
{
}
else if (condition2)
{
}
else
{
}
| int a = 3;
if (a == 2) {
puts ("a is 2");
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
unless (a == 2) {
puts ("a is 2");
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
switch (a) {
case 2:
puts ("a is 2");
break;
case 3:
puts ("a is 3");
break;
case 4:
puts ("a is 4");
break;
default:
puts("is neither");
}
|
Generate a C translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
| #include <stdlib.h>
#include <string.h>
#include <strings.h>
int mycmp(const void *s1, const void *s2)
{
const char *l = *(const char **)s1, *r = *(const char **)s2;
size_t ll = strlen(l), lr = strlen(r);
if (ll > lr) return -1;
if (ll < lr) return 1;
return strcasecmp(l, r);
}
int main()
{
const char *strings[] = {
"Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
}
|
Generate an equivalent C version of this C# code. | using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
| #include <stdlib.h>
#include <string.h>
#include <strings.h>
int mycmp(const void *s1, const void *s2)
{
const char *l = *(const char **)s1, *r = *(const char **)s2;
size_t ll = strlen(l), lr = strlen(r);
if (ll > lr) return -1;
if (ll < lr) return 1;
return strcasecmp(l, r);
}
int main()
{
const char *strings[] = {
"Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
}
|
Convert the following code from C# to C, ensuring the logic remains intact. | using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
}
| #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
|
Can you help me rewrite this code in C instead of C#, keeping it the same logically? | using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
}
| #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
|
Translate the given C# code snippet into C without altering its behavior. | using System;
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move)
old[i-j] = old[i];
else
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
| #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
unsigned *ll = from, *rr = to - 1;
for (;;) {
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*rr & bit)) rr--;
if (ll >= rr) break;
swap(ll, rr);
}
if (!(bit & *ll) && ll < to) ll++;
bit >>= 1;
rad_sort_u(from, ll, bit);
rad_sort_u(ll, to, bit);
}
static void radix_sort(int *a, const size_t len)
{
size_t i;
unsigned *x = (unsigned*) a;
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
rad_sort_u(x, x + len, INT_MIN);
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
}
int main(void)
{
srand(time(NULL));
int x[16];
for (size_t i = 0; i < ARR_LEN(x); i++)
x[i] = RAND_RNG(-128,127)
radix_sort(x, ARR_LEN(x));
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}
|
Please provide an equivalent version of this C# code in C. | using System;
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move)
old[i-j] = old[i];
else
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
| #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
unsigned *ll = from, *rr = to - 1;
for (;;) {
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*rr & bit)) rr--;
if (ll >= rr) break;
swap(ll, rr);
}
if (!(bit & *ll) && ll < to) ll++;
bit >>= 1;
rad_sort_u(from, ll, bit);
rad_sort_u(ll, to, bit);
}
static void radix_sort(int *a, const size_t len)
{
size_t i;
unsigned *x = (unsigned*) a;
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
rad_sort_u(x, x + len, INT_MIN);
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
}
int main(void)
{
srand(time(NULL));
int x[16];
for (size_t i = 0; i < ARR_LEN(x); i++)
x[i] = RAND_RNG(-128,127)
radix_sort(x, ARR_LEN(x));
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}
|
Convert this C# block to C, preserving its control flow and logic. | using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Change the programming language of this snippet from C# to C without modifying what it does. | using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
| for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
|
Generate a C translation of this C# snippet without changing its computational steps. | class SelectionSort<T> where T : IComparable {
public T[] Sort(T[] list) {
int k;
T temp;
for (int i = 0; i < list.Length; i++) {
k = i;
for (int j=i + 1; j < list.Length; j++) {
if (list[j].CompareTo(list[k]) < 0) {
k = j;
}
}
temp = list[i];
list[i] = list[k];
list[k] = temp;
}
return list;
}
}
| #include <stdio.h>
void selection_sort (int *a, int n) {
int i, j, m, t;
for (i = 0; i < n; i++) {
for (j = i, m = i; j < n; j++) {
if (a[j] < a[m]) {
m = j;
}
}
t = a[i];
a[i] = a[m];
a[m] = t;
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
selection_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
Produce a functionally identical C code for the snippet given in C#. | int[] intArray = { 1, 2, 3, 4, 5 };
int[] squares1 = intArray.Select(x => x * x).ToArray();
int[] squares2 = (from x in intArray
select x * x).ToArray();
foreach (var i in intArray)
Console.WriteLine(i * i);
| #ifndef CALLBACK_H
#define CALLBACK_H
void map(int* array, int len, void(*callback)(int,int));
#endif
|
Keep all operations the same but rewrite the snippet in C. | public sealed class Singleton1
{
private static Singleton1 instance;
private static readonly object lockObj = new object();
public static Singleton1 Instance {
get {
lock(lockObj) {
if (instance == null) {
instance = new Singleton1();
}
}
return instance;
}
}
}
| #ifndef SILLY_H
#define SILLY_H
extern void JumpOverTheDog( int numberOfTimes);
extern int PlayFetchWithDog( float weightOfStick);
#endif
|
Port the provided C# code into C while preserving the original functionality. | using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl++;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static float NextDown(float d) {
if (d == 0.0) return -float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl--;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static Tuple<float, float> SafeAdd(float a, float b) {
return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
}
static void Main(string[] args) {
float a = 1.20f;
float b = 0.03f;
Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
}
}
}
| #include <fenv.h>
#include <stdio.h>
void
safe_add(volatile double interval[2], volatile double a, volatile double b)
{
#pragma STDC FENV_ACCESS ON
unsigned int orig;
orig = fegetround();
fesetround(FE_DOWNWARD);
interval[0] = a + b;
fesetround(FE_UPWARD);
interval[1] = a + b;
fesetround(orig);
}
int
main()
{
const double nums[][2] = {
{1, 2},
{0.1, 0.2},
{1e100, 1e-100},
{1e308, 1e308},
};
double ival[2];
int i;
for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
safe_add(ival, nums[i][0], nums[i][1]);
printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]);
printf(" [%.17g, %.17g]\n", ival[0], ival[1]);
printf(" size %.17g\n\n", ival[1] - ival[0]);
}
return 0;
}
|
Generate an equivalent C version of this C# code. | using System;
namespace SafeAddition {
class Program {
static float NextUp(float d) {
if (d == 0.0) return float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl++;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static float NextDown(float d) {
if (d == 0.0) return -float.Epsilon;
if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d;
byte[] bytes = BitConverter.GetBytes(d);
int dl = BitConverter.ToInt32(bytes, 0);
dl--;
bytes = BitConverter.GetBytes(dl);
return BitConverter.ToSingle(bytes, 0);
}
static Tuple<float, float> SafeAdd(float a, float b) {
return new Tuple<float, float>(NextDown(a + b), NextUp(a + b));
}
static void Main(string[] args) {
float a = 1.20f;
float b = 0.03f;
Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b));
}
}
}
| #include <fenv.h>
#include <stdio.h>
void
safe_add(volatile double interval[2], volatile double a, volatile double b)
{
#pragma STDC FENV_ACCESS ON
unsigned int orig;
orig = fegetround();
fesetround(FE_DOWNWARD);
interval[0] = a + b;
fesetround(FE_UPWARD);
interval[1] = a + b;
fesetround(orig);
}
int
main()
{
const double nums[][2] = {
{1, 2},
{0.1, 0.2},
{1e100, 1e-100},
{1e308, 1e308},
};
double ival[2];
int i;
for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) {
safe_add(ival, nums[i][0], nums[i][1]);
printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]);
printf(" [%.17g, %.17g]\n", ival[0], ival[1]);
printf(" size %.17g\n\n", ival[1] - ival[0]);
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C# to C. | for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}
| int i;
for(i = 10; i >= 0; --i)
printf("%d\n",i);
|
Write the same algorithm in C as shown in this C# implementation. | System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.",
freopen("sample.txt","wb",stdout));
}
|
Convert this C# snippet to C and keep its semantics consistent. | using System;
class Program {
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
| int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
putchar('*');
puts("");
}
|
Port the provided C# code into C while preserving the original functionality. | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COUNTOF(a) (sizeof(a)/sizeof(a[0]))
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;
}
int icompare(const void* p1, const void* p2) {
const int* ip1 = p1;
const int* ip2 = p2;
return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);
}
size_t unique(int* array, size_t len) {
size_t out_index = 0;
int prev;
for (size_t i = 0; i < len; ++i) {
if (i == 0 || prev != array[i])
array[out_index++] = array[i];
prev = array[i];
}
return out_index;
}
int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {
size_t len = 0;
for (size_t i = 0; i < count; ++i)
len += lengths[i];
int* array = xmalloc(len * sizeof(int));
for (size_t i = 0, offset = 0; i < count; ++i) {
memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));
offset += lengths[i];
}
qsort(array, len, sizeof(int), icompare);
*size = unique(array, len);
return array;
}
void print(const int* array, size_t len) {
printf("[");
for (size_t i = 0; i < len; ++i) {
if (i > 0)
printf(", ");
printf("%d", array[i]);
}
printf("]\n");
}
int main() {
const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};
const int b[] = {3, 5, 9, 8, 4};
const int c[] = {1, 3, 7, 9};
size_t len = 0;
const int* arrays[] = {a, b, c};
size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};
int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);
print(sorted, len);
free(sorted);
return 0;
}
|
Translate the given C# code snippet into C without altering its behavior. | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main() {
var sequence = new[] { "A", "B", "C", "D" };
foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) {
Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i])));
}
}
static IEnumerable<List<int>> Subsets(int length) {
int[] values = Enumerable.Range(0, length).ToArray();
var stack = new Stack<int>(length);
for (int i = 0; stack.Count > 0 || i < length; ) {
if (i < length) {
stack.Push(i++);
yield return (from index in stack.Reverse() select values[index]).ToList();
} else {
i = stack.Pop() + 1;
if (stack.Count > 0) i = stack.Pop() + 1;
}
}
}
static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count;
}
| #include <assert.h>
#include <stdio.h>
int main(int c, char **v)
{
unsigned int n = 1 << (c - 1), i = n, j, k;
assert(n);
while (i--) {
if (!(i & (i + (i & -(int)i))))
continue;
for (j = n, k = 1; j >>= 1; k++)
if (i & j) printf("%s ", v[k]);
putchar('\n');
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in C#. | using System;
class Program {
static uint[] res = new uint[10];
static uint ri = 1, p = 10, count = 0;
static void TabulateTwinPrimes(uint bound) {
if (bound < 5) return; count++;
uint cl = (bound - 1) >> 1, i = 1, j,
limit = (uint)(Math.Sqrt(bound) - 1) >> 1;
var comp = new bool[cl]; bool lp;
for (j = 3; j < cl; j += 3) comp[j] = true;
while (i < limit) {
if (lp = !comp[i]) {
uint pr = (i << 1) + 3;
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
if (!comp[++i]) {
uint pr = (i << 1) + 3;
if (lp) {
if (pr > p) {
res[ri++] = count;
p *= 10;
}
count++;
i++;
}
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
}
cl--;
while (i < cl) {
lp = !comp[i++];
if (!comp[i] && lp) {
if ((i++ << 1) + 3 > p) {
res[ri++] = count;
p *= 10;
}
count++;
}
}
res[ri] = count;
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
string fmt = "{0,9:n0} twin primes below {1,-13:n0}";
TabulateTwinPrimes(1_000_000_000);
sw.Stop();
p = 1;
for (var j = 1; j <= ri; j++)
Console.WriteLine(fmt, res[j], p *= 10);
Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
}
}
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool isPrime(int64_t n) {
int64_t i;
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;
if (n % 7 == 0) return n == 7;
if (n % 11 == 0) return n == 11;
if (n % 13 == 0) return n == 13;
if (n % 17 == 0) return n == 17;
if (n % 19 == 0) return n == 19;
for (i = 23; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
int countTwinPrimes(int limit) {
int count = 0;
int64_t p3 = true, p2 = true, p1 = false;
int64_t i;
for (i = 5; i <= limit; i++) {
p3 = p2;
p2 = p1;
p1 = isPrime(i);
if (p3 && p1) {
count++;
}
}
return count;
}
void test(int limit) {
int count = countTwinPrimes(limit);
printf("Number of twin prime pairs less than %d is %d\n", limit, count);
}
int main() {
test(10);
test(100);
test(1000);
test(10000);
test(100000);
test(1000000);
test(10000000);
test(100000000);
return 0;
}
|
Write a version of this C# function in C with identical behavior. | using System;
class Program {
static uint[] res = new uint[10];
static uint ri = 1, p = 10, count = 0;
static void TabulateTwinPrimes(uint bound) {
if (bound < 5) return; count++;
uint cl = (bound - 1) >> 1, i = 1, j,
limit = (uint)(Math.Sqrt(bound) - 1) >> 1;
var comp = new bool[cl]; bool lp;
for (j = 3; j < cl; j += 3) comp[j] = true;
while (i < limit) {
if (lp = !comp[i]) {
uint pr = (i << 1) + 3;
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
if (!comp[++i]) {
uint pr = (i << 1) + 3;
if (lp) {
if (pr > p) {
res[ri++] = count;
p *= 10;
}
count++;
i++;
}
for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
comp[j] = true;
}
}
cl--;
while (i < cl) {
lp = !comp[i++];
if (!comp[i] && lp) {
if ((i++ << 1) + 3 > p) {
res[ri++] = count;
p *= 10;
}
count++;
}
}
res[ri] = count;
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
string fmt = "{0,9:n0} twin primes below {1,-13:n0}";
TabulateTwinPrimes(1_000_000_000);
sw.Stop();
p = 1;
for (var j = 1; j <= ri; j++)
Console.WriteLine(fmt, res[j], p *= 10);
Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
}
}
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool isPrime(int64_t n) {
int64_t i;
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;
if (n % 7 == 0) return n == 7;
if (n % 11 == 0) return n == 11;
if (n % 13 == 0) return n == 13;
if (n % 17 == 0) return n == 17;
if (n % 19 == 0) return n == 19;
for (i = 23; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
int countTwinPrimes(int limit) {
int count = 0;
int64_t p3 = true, p2 = true, p1 = false;
int64_t i;
for (i = 5; i <= limit; i++) {
p3 = p2;
p2 = p1;
p1 = isPrime(i);
if (p3 && p1) {
count++;
}
}
return count;
}
void test(int limit) {
int count = countTwinPrimes(limit);
printf("Number of twin prime pairs less than %d is %d\n", limit, count);
}
int main() {
test(10);
test(100);
test(1000);
test(10000);
test(100000);
test(1000000);
test(10000000);
test(100000000);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
class Program
{
static IEnumerable<Complex> RootsOfUnity(int degree)
{
return Enumerable
.Range(0, degree)
.Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree));
}
static void Main()
{
var degree = 3;
foreach (var root in RootsOfUnity(degree))
{
Console.WriteLine(root);
}
}
}
| #include <stdio.h>
#include <math.h>
int main()
{
double a, c, s, PI2 = atan2(1, 1) * 8;
int n, i;
for (n = 1; n < 10; n++) for (i = 0; i < n; i++) {
c = s = 0;
if (!i ) c = 1;
else if(n == 4 * i) s = 1;
else if(n == 2 * i) c = -1;
else if(3 * n == 4 * i) s = -1;
else
a = i * PI2 / n, c = cos(a), s = sin(a);
if (c) printf("%.2g", c);
printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s);
printf(i == n - 1 ?"\n":", ");
}
return 0;
}
|
Convert the following code from C# to C, ensuring the logic remains intact. | using System;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static decimal mx = 1E28M, hm = 1E14M, a;
struct bi { public decimal hi, lo; }
static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; }
static string toStr(bi a, bool comma = false) {
string r = a.hi == 0 ? string.Format("{0:0}", a.lo) :
string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo);
if (!comma) return r; string rc = "";
for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc;
return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; }
static decimal Pow_dec(decimal bas, uint exp) {
if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp;
if ((exp & 1) == 0) return tmp; return tmp * bas; }
static void Main(string[] args) {
for (uint p = 64; p < 95; p += 30) {
bi x = set4sq(a = Pow_dec(2M, p)), y;
WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2);
y.lo = x.lo * x.lo; y.hi = x.hi * x.hi;
a = x.hi * x.lo * 2M;
y.hi += Math.Floor(a / hm);
y.lo += (a % hm) * hm;
while (y.lo > mx) { y.lo -= mx; y.hi++; }
WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true),
BS.ToString() == toStr(y) ? "does" : "fails to"); } }
}
| #include <stdio.h>
#include <string.h>
void longmulti(const char *a, const char *b, char *c)
{
int i = 0, j = 0, k = 0, n, carry;
int la, lb;
if (!strcmp(a, "0") || !strcmp(b, "0")) {
c[0] = '0', c[1] = '\0';
return;
}
if (a[0] == '-') { i = 1; k = !k; }
if (b[0] == '-') { j = 1; k = !k; }
if (i || j) {
if (k) c[0] = '-';
longmulti(a + i, b + j, c + k);
return;
}
la = strlen(a);
lb = strlen(b);
memset(c, '0', la + lb);
c[la + lb] = '\0';
# define I(a) (a - '0')
for (i = la - 1; i >= 0; i--) {
for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {
n = I(a[i]) * I(b[j]) + I(c[k]) + carry;
carry = n / 10;
c[k] = (n % 10) + '0';
}
c[k] += carry;
}
# undef I
if (c[0] == '0') memmove(c, c + 1, la + lb);
return;
}
int main()
{
char c[1024];
longmulti("-18446744073709551616", "-18446744073709551616", c);
printf("%s\n", c);
return 0;
}
|
Write the same code in C as shown below in C#. | using System;
using System.Numerics;
static class Program
{
static void Fun(ref BigInteger a, ref BigInteger b, int c)
{
BigInteger t = a; a = b; b = b * c + t;
}
static void SolvePell(int n, ref BigInteger a, ref BigInteger b)
{
int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1;
BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1;
while (true)
{
y = r * z - y; z = (n - y * y) / z; r = (x + y) / z;
Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x);
if (a * a - n * b * b == 1) return;
}
}
static void Main()
{
BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 })
{
SolvePell(n, ref x, ref y);
Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y);
}
}
}
| #include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
struct Pair {
uint64_t v1, v2;
};
struct Pair makePair(uint64_t a, uint64_t b) {
struct Pair r;
r.v1 = a;
r.v2 = b;
return r;
}
struct Pair solvePell(int n) {
int x = (int) sqrt(n);
if (x * x == n) {
return makePair(1, 0);
} else {
int y = x;
int z = 1;
int r = 2 * x;
struct Pair e = makePair(1, 0);
struct Pair f = makePair(0, 1);
uint64_t a = 0;
uint64_t b = 0;
while (true) {
y = r * z - y;
z = (n - y * y) / z;
r = (x + y) / z;
e = makePair(e.v2, r * e.v2 + e.v1);
f = makePair(f.v2, r * f.v2 + f.v1);
a = e.v2 + x * f.v2;
b = f.v2;
if (a * a - n * b * b == 1) {
break;
}
}
return makePair(a, b);
}
}
void test(int n) {
struct Pair r = solvePell(n);
printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2);
}
int main() {
test(61);
test(109);
test(181);
test(277);
return 0;
}
|
Please provide an equivalent version of this C# code in C. | using System;
namespace BullsnCows
{
class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
KnuthShuffle<int>(ref nums);
int[] chosenNum = new int[4];
Array.Copy(nums, chosenNum, 4);
Console.WriteLine("Your Guess ?");
while (!game(Console.ReadLine(), chosenNum))
{
Console.WriteLine("Your next Guess ?");
}
Console.ReadKey();
}
public static void KnuthShuffle<T>(ref T[] array)
{
System.Random random = new System.Random();
for (int i = 0; i < array.Length; i++)
{
int j = random.Next(array.Length);
T temp = array[i]; array[i] = array[j]; array[j] = temp;
}
}
public static bool game(string guess, int[] num)
{
char[] guessed = guess.ToCharArray();
int bullsCount = 0, cowsCount = 0;
if (guessed.Length != 4)
{
Console.WriteLine("Not a valid guess.");
return false;
}
for (int i = 0; i < 4; i++)
{
int curguess = (int) char.GetNumericValue(guessed[i]);
if (curguess < 1 || curguess > 9)
{
Console.WriteLine("Digit must be ge greater 0 and lower 10.");
return false;
}
if (curguess == num[i])
{
bullsCount++;
}
else
{
for (int j = 0; j < 4; j++)
{
if (curguess == num[j])
cowsCount++;
}
}
}
if (bullsCount == 4)
{
Console.WriteLine("Congratulations! You have won!");
return true;
}
else
{
Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount);
return false;
}
}
}
}
| #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
#include <string.h>
#define MAX_NUM_TRIES 72
#define LINE_BEGIN 7
#define LAST_LINE 18
int yp=LINE_BEGIN, xp=0;
char number[5];
char guess[5];
#define MAX_STR 256
void mvaddstrf(int y, int x, const char *fmt, ...)
{
va_list args;
char buf[MAX_STR];
va_start(args, fmt);
vsprintf(buf, fmt, args);
move(y, x);
clrtoeol();
addstr(buf);
va_end(args);
}
void ask_for_a_number()
{
int i=0;
char symbols[] = "123456789";
move(5,0); clrtoeol();
addstr("Enter four digits: ");
while(i<4) {
int c = getch();
if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
addch(c);
symbols[c-'1'] = 0;
guess[i++] = c;
}
}
}
void choose_the_number()
{
int i=0, j;
char symbols[] = "123456789";
while(i<4) {
j = rand() % 9;
if ( symbols[j] != 0 ) {
number[i++] = symbols[j];
symbols[j] = 0;
}
}
}
|
Change the programming language of this snippet from C# to C without modifying what it does. | using System;
using System.Collections.Generic;
namespace RosettaCode.BubbleSort
{
public static class BubbleSortMethods
{
public static void BubbleSort<T>(this List<T> list) where T : IComparable
{
bool madeChanges;
int itemCount = list.Count;
do
{
madeChanges = false;
itemCount--;
for (int i = 0; i < itemCount; i++)
{
if (list[i].CompareTo(list[i + 1]) > 0)
{
T temp = list[i + 1];
list[i + 1] = list[i];
list[i] = temp;
madeChanges = true;
}
}
} while (madeChanges);
}
}
class Program
{
static void Main()
{
List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
testList.BubbleSort();
foreach (var t in testList) Console.Write(t + " ");
}
}
}
| #include <stdio.h>
void bubble_sort (int *a, int n) {
int i, t, j = n, s = 1;
while (s) {
s = 0;
for (i = 1; i < j; i++) {
if (a[i] < a[i - 1]) {
t = a[i];
a[i] = a[i - 1];
a[i - 1] = t;
s = 1;
}
}
j--;
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
bubble_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
Write a version of this C# function in C with identical behavior. | #include <cmath>
#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;
}
unsigned int divisor_product(unsigned int n) {
return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));
}
int main() {
const unsigned int limit = 50;
std::cout << "Product of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(11) << divisor_product(n);
if (n % 5 == 0)
std::cout << '\n';
}
}
| #include <math.h>
#include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
unsigned int p;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
unsigned int divisor_product(unsigned int n) {
return pow(n, divisor_count(n) / 2.0);
}
int main() {
const unsigned int limit = 50;
unsigned int n;
printf("Product of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%11d", divisor_product(n));
if (n % 5 == 0) {
printf("\n");
}
}
return 0;
}
|
Please provide an equivalent version of this C# code in C. | #include <cmath>
#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;
}
unsigned int divisor_product(unsigned int n) {
return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));
}
int main() {
const unsigned int limit = 50;
std::cout << "Product of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(11) << divisor_product(n);
if (n % 5 == 0)
std::cout << '\n';
}
}
| #include <math.h>
#include <stdio.h>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
unsigned int p;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
unsigned int divisor_product(unsigned int n) {
return pow(n, divisor_count(n) / 2.0);
}
int main() {
const unsigned int limit = 50;
unsigned int n;
printf("Product of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%11d", divisor_product(n));
if (n % 5 == 0) {
printf("\n");
}
}
return 0;
}
|
Translate the given C# code snippet into C without altering its behavior. | using System;
using System.IO;
namespace FileIO
{
class Program
{
static void Main()
{
String s = scope .();
File.ReadAllText("input.txt", s);
File.WriteAllText("output.txt", s);
}
}
}
| #include <stdio.h>
int main(int argc, char **argv) {
FILE *in, *out;
int c;
in = fopen("input.txt", "r");
if (!in) {
fprintf(stderr, "Error opening input.txt for reading.\n");
return 1;
}
out = fopen("output.txt", "w");
if (!out) {
fprintf(stderr, "Error opening output.txt for writing.\n");
fclose(in);
return 1;
}
while ((c = fgetc(in)) != EOF) {
fputc(c, out);
}
fclose(out);
fclose(in);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C# to C. | using System;
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(args[0]);
int b = Convert.ToInt32(args[1]);
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
Console.WriteLine("{0} % {1} = {2}", a, b, a % b);
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}
| #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
if (argc < 3) exit(1);
b = atoi(argv[--argc]);
if (b == 0) exit(2);
a = atoi(argv[--argc]);
printf("a+b = %d\n", a+b);
printf("a-b = %d\n", a-b);
printf("a*b = %d\n", a*b);
printf("a/b = %d\n", a/b);
printf("a%%b = %d\n", a%b);
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | using System;
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(args[0]);
int b = Convert.ToInt32(args[1]);
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.WriteLine("{0} / {1} = {2}", a, b, a / b);
Console.WriteLine("{0} % {1} = {2}", a, b, a % b);
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}
| #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
if (argc < 3) exit(1);
b = atoi(argv[--argc]);
if (b == 0) exit(2);
a = atoi(argv[--argc]);
printf("a+b = %d\n", a+b);
printf("a-b = %d\n", a-b);
printf("a*b = %d\n", a*b);
printf("a/b = %d\n", a/b);
printf("a%%b = %d\n", a%b);
return 0;
}
|
Translate this program into C but keep the logic exactly as in C#. | using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
double[,] m = { {1,2,3},{4,5,6},{7,8,9} };
double[,] t = Transpose( m );
for( int i=0; i<t.GetLength(0); i++ )
{
for( int j=0; j<t.GetLength(1); j++ )
Console.Write( t[i,j] + " " );
Console.WriteLine("");
}
}
public static double[,] Transpose( double[,] m )
{
double[,] t = new double[m.GetLength(1),m.GetLength(0)];
for( int i=0; i<m.GetLength(0); i++ )
for( int j=0; j<m.GetLength(1); j++ )
t[j,i] = m[i,j];
return t;
}
}
}
| #include <stdio.h>
void transpose(void *dest, void *src, int src_h, int src_w)
{
int i, j;
double (*d)[src_h] = dest, (*s)[src_w] = src;
for (i = 0; i < src_h; i++)
for (j = 0; j < src_w; j++)
d[j][i] = s[i][j];
}
int main()
{
int i, j;
double a[3][5] = {{ 0, 1, 2, 3, 4 },
{ 5, 6, 7, 8, 9 },
{ 1, 0, 0, 0, 42}};
double b[5][3];
transpose(b, a, 3, 5);
for (i = 0; i < 5; i++)
for (j = 0; j < 3; j++)
printf("%g%c", b[i][j], j == 2 ? '\n' : ' ');
return 0;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
delegate T Func<T>();
class ManOrBoy
{
static void Main()
{
Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0)));
}
static Func<int> C(int i)
{
return delegate { return i; };
}
static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5)
{
Func<int> b = null;
b = delegate { k--; return A(k, b, x1, x2, x3, x4); };
return k <= 0 ? x4() + x5() : b();
}
}
|
#include <stdio.h>
#include <stdlib.h>
typedef struct arg
{
int (*fn)(struct arg*);
int *k;
struct arg *x1, *x2, *x3, *x4, *x5;
} ARG;
int f_1 (ARG* _) { return -1; }
int f0 (ARG* _) { return 0; }
int f1 (ARG* _) { return 1; }
int eval(ARG* a) { return a->fn(a); }
#define MAKE_ARG(...) (&(ARG){__VA_ARGS__})
#define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__)
int A(ARG*);
int B(ARG* a)
{
int k = *a->k -= 1;
return A(FUN(a, a->x1, a->x2, a->x3, a->x4));
}
int A(ARG* a)
{
return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a);
}
int main(int argc, char **argv)
{
int k = argc == 2 ? strtol(argv[1], 0, 0) : 10;
printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1),
MAKE_ARG(f1), MAKE_ARG(f0))));
return 0;
}
|
Change the following C# code into C without altering its purpose. | using System;
class Program
{
static bool a(bool value)
{
Console.WriteLine("a");
return value;
}
static bool b(bool value)
{
Console.WriteLine("b");
return value;
}
static void Main()
{
foreach (var i in new[] { false, true })
{
foreach (var j in new[] { false, true })
{
Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
Console.WriteLine();
Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
Console.WriteLine();
}
}
}
}
| #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&);
TEST(true, false, ||);
TEST(true, false, &&);
TEST(false, false, ||);
return 0;
}
|
Translate the given C# code snippet into C without altering its behavior. | using System;
class Program
{
static bool a(bool value)
{
Console.WriteLine("a");
return value;
}
static bool b(bool value)
{
Console.WriteLine("b");
return value;
}
static void Main()
{
foreach (var i in new[] { false, true })
{
foreach (var j in new[] { false, true })
{
Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j));
Console.WriteLine();
Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j));
Console.WriteLine();
}
}
}
}
| #include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&);
TEST(true, false, ||);
TEST(true, false, &&);
TEST(false, false, ||);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
| #include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1);
}
int main()
{
recurse(0);
return 0;
}
|
Write a version of this C# function in C with identical behavior. | using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
| #include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1);
}
int main()
{
recurse(0);
return 0;
}
|
Convert this C# snippet to C and keep its semantics consistent. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
static Size size = new Size(320, 240);
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
static PictureBox pb;
static BackgroundWorker worker;
static double time = 0;
static double frames = 0;
static Random rand = new Random();
static byte tmp;
static byte white = 255;
static byte black = 0;
static int halfmax = int.MaxValue / 2;
static IEnumerable<byte> YieldVodoo()
{
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white;
yield return tmp;
yield return tmp;
yield return tmp;
}
}
static Image Randimg()
{
var bitmap = new Bitmap(size.Width, size.Height);
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(
YieldVodoo().ToArray<byte>(),
0,
data.Scan0,
numbytes);
bitmap.UnlockBits(data);
return bitmap;
}
[STAThread]
static void Main()
{
var form = new Form();
form.AutoSize = true;
form.Size = new Size(0, 0);
form.Text = "Test";
form.FormClosed += delegate
{
Application.Exit();
};
worker = new BackgroundWorker();
worker.DoWork += delegate
{
System.Threading.Thread.Sleep(500);
while (true)
{
var a = DateTime.Now;
pb.Image = Randimg();
var b = DateTime.Now;
time += (b - a).TotalSeconds;
frames += 1;
if (frames == 30)
{
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
time = 0;
frames = 0;
}
}
};
worker.RunWorkerAsync();
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
pb = new PictureBox();
pb.Size = size;
flp.AutoSize = true;
flp.Controls.Add(pb);
form.Show();
Application.Run();
}
}
| #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL/SDL.h>
unsigned int frames = 0;
unsigned int t_acc = 0;
void print_fps ()
{
static Uint32 last_t = 0;
Uint32 t = SDL_GetTicks();
Uint32 dt = t - last_t;
t_acc += dt;
if (t_acc > 1000)
{
unsigned int el_time = t_acc / 1000;
printf("- fps: %g\n",
(float) frames / (float) el_time);
t_acc = 0;
frames = 0;
}
last_t = t;
}
void blit_noise(SDL_Surface *surf)
{
unsigned int i;
long dim = surf->w * surf->h;
while (1)
{
SDL_LockSurface(surf);
for (i=0; i < dim; ++i) {
((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);
}
SDL_UnlockSurface(surf);
SDL_Flip(surf);
++frames;
print_fps();
}
}
int main(void)
{
SDL_Surface *surf = NULL;
srand((unsigned int)time(NULL));
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);
blit_noise(surf);
}
|
Rewrite the snippet below in C so it works the same as the original C# code. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
static Size size = new Size(320, 240);
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
static PictureBox pb;
static BackgroundWorker worker;
static double time = 0;
static double frames = 0;
static Random rand = new Random();
static byte tmp;
static byte white = 255;
static byte black = 0;
static int halfmax = int.MaxValue / 2;
static IEnumerable<byte> YieldVodoo()
{
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white;
yield return tmp;
yield return tmp;
yield return tmp;
}
}
static Image Randimg()
{
var bitmap = new Bitmap(size.Width, size.Height);
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
Marshal.Copy(
YieldVodoo().ToArray<byte>(),
0,
data.Scan0,
numbytes);
bitmap.UnlockBits(data);
return bitmap;
}
[STAThread]
static void Main()
{
var form = new Form();
form.AutoSize = true;
form.Size = new Size(0, 0);
form.Text = "Test";
form.FormClosed += delegate
{
Application.Exit();
};
worker = new BackgroundWorker();
worker.DoWork += delegate
{
System.Threading.Thread.Sleep(500);
while (true)
{
var a = DateTime.Now;
pb.Image = Randimg();
var b = DateTime.Now;
time += (b - a).TotalSeconds;
frames += 1;
if (frames == 30)
{
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
time = 0;
frames = 0;
}
}
};
worker.RunWorkerAsync();
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
pb = new PictureBox();
pb.Size = size;
flp.AutoSize = true;
flp.Controls.Add(pb);
form.Show();
Application.Run();
}
}
| #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL/SDL.h>
unsigned int frames = 0;
unsigned int t_acc = 0;
void print_fps ()
{
static Uint32 last_t = 0;
Uint32 t = SDL_GetTicks();
Uint32 dt = t - last_t;
t_acc += dt;
if (t_acc > 1000)
{
unsigned int el_time = t_acc / 1000;
printf("- fps: %g\n",
(float) frames / (float) el_time);
t_acc = 0;
frames = 0;
}
last_t = t;
}
void blit_noise(SDL_Surface *surf)
{
unsigned int i;
long dim = surf->w * surf->h;
while (1)
{
SDL_LockSurface(surf);
for (i=0; i < dim; ++i) {
((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0);
}
SDL_UnlockSurface(surf);
SDL_Flip(surf);
++frames;
print_fps();
}
}
int main(void)
{
SDL_Surface *surf = NULL;
srand((unsigned int)time(NULL));
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);
blit_noise(surf);
}
|
Translate the given C# code snippet into C without altering its behavior. | static void Main(string[] args)
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
for (int x = 0; x < 33550337; x++)
{
if (IsPerfect(x))
Console.WriteLine(x + " is perfect.");
}
Console.ReadLine();
}
static bool IsPerfect(int num)
{
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
sum += i;
}
return sum == num ;
}
| #include "stdio.h"
#include "math.h"
int perfect(int n) {
int max = (int)sqrt((double)n) + 1;
int tot = 1;
int i;
for (i = 2; i < max; i++)
if ( (n % i) == 0 ) {
tot += i;
int q = n / i;
if (q > i)
tot += q;
}
return tot == n;
}
int main() {
int n;
for (n = 2; n < 33550337; n++)
if (perfect(n))
printf("%d\n", n);
return 0;
}
|
Write the same algorithm in C as shown in this C# implementation. | static void Main(string[] args)
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
for (int x = 0; x < 33550337; x++)
{
if (IsPerfect(x))
Console.WriteLine(x + " is perfect.");
}
Console.ReadLine();
}
static bool IsPerfect(int num)
{
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
sum += i;
}
return sum == num ;
}
| #include "stdio.h"
#include "math.h"
int perfect(int n) {
int max = (int)sqrt((double)n) + 1;
int tot = 1;
int i;
for (i = 2; i < max; i++)
if ( (n % i) == 0 ) {
tot += i;
int q = n / i;
if (q > i)
tot += q;
}
return tot == n;
}
int main() {
int n;
for (n = 2; n < 33550337; n++)
if (perfect(n))
printf("%d\n", n);
return 0;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
Debug.Assert(result.Length == 183231);
Debug.Assert(result.StartsWith("62060698786608744707"));
Debug.Assert(result.EndsWith("92256259918212890625"));
Console.WriteLine("n = 5^4^3^2");
Console.WriteLine("n = {0}...{1}",
result.Substring(0, 20),
result.Substring(result.Length - 20, 20)
);
Console.WriteLine("n digits = {0}", result.Length);
}
}
| #include <gmp.h>
#include <stdio.h>
#include <string.h>
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18);
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
char *s = mpz_get_str(0, 10, a);
printf("size really is %d\n", len = strlen(s));
printf("Digits: %.20s...%s\n", s, s + len - 20);
return 0;
}
|
Produce a functionally identical C code for the snippet given in C#. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class InvertedIndex
{
static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary)
{
return dictionary
.SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key)))
.GroupBy(keyValuePair => keyValuePair.Key)
.ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value));
}
static void Main()
{
Console.Write("files: ");
var files = Console.ReadLine();
Console.Write("find: ");
var find = Console.ReadLine();
var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable());
Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find]));
}
}
| #include <stdio.h>
#include <stdlib.h>
char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./";
int chr_idx[256] = {0};
char idx_chr[256] = {0};
#define FNAME 0
typedef struct trie_t *trie, trie_t;
struct trie_t {
trie next[sizeof(chr_legal)];
int eow;
};
trie trie_new() { return calloc(sizeof(trie_t), 1); }
#define find_word(r, w) trie_trav(r, w, 1)
trie trie_trav(trie root, const char * str, int no_create)
{
int c;
while (root) {
if ((c = str[0]) == '\0') {
if (!root->eow && no_create) return 0;
break;
}
if (! (c = chr_idx[c]) ) {
str++;
continue;
}
if (!root->next[c]) {
if (no_create) return 0;
root->next[c] = trie_new();
}
root = root->next[c];
str++;
}
return root;
}
int trie_all(trie root, char path[], int depth, int (*callback)(char *))
{
int i;
if (root->eow && !callback(path)) return 0;
for (i = 1; i < sizeof(chr_legal); i++) {
if (!root->next[i]) continue;
path[depth] = idx_chr[i];
path[depth + 1] = '\0';
if (!trie_all(root->next[i], path, depth + 1, callback))
return 0;
}
return 1;
}
void add_index(trie root, const char *word, const char *fname)
{
trie x = trie_trav(root, word, 0);
x->eow = 1;
if (!x->next[FNAME])
x->next[FNAME] = trie_new();
x = trie_trav(x->next[FNAME], fname, 0);
x->eow = 1;
}
int print_path(char *path)
{
printf(" %s", path);
return 1;
}
const char *files[] = { "f1.txt", "source/f2.txt", "other_file" };
const char *text[][5] ={{ "it", "is", "what", "it", "is" },
{ "what", "is", "it", 0 },
{ "it", "is", "a", "banana", 0 }};
trie init_tables()
{
int i, j;
trie root = trie_new();
for (i = 0; i < sizeof(chr_legal); i++) {
chr_idx[(int)chr_legal[i]] = i + 1;
idx_chr[i + 1] = chr_legal[i];
}
#define USE_ADVANCED_FILE_HANDLING 0
#if USE_ADVANCED_FILE_HANDLING
void read_file(const char * fname) {
char cmd[1024];
char word[1024];
sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname);
FILE *in = popen(cmd, "r");
while (!feof(in)) {
fscanf(in, "%1000s", word);
add_index(root, word, fname);
}
pclose(in);
};
read_file("f1.txt");
read_file("source/f2.txt");
read_file("other_file");
#else
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
if (!text[i][j]) break;
add_index(root, text[i][j], files[i]);
}
}
#endif
return root;
}
void search_index(trie root, const char *word)
{
char path[1024];
printf("Search for \"%s\": ", word);
trie found = find_word(root, word);
if (!found) printf("not found\n");
else {
trie_all(found->next[FNAME], path, 0, print_path);
printf("\n");
}
}
int main()
{
trie root = init_tables();
search_index(root, "what");
search_index(root, "is");
search_index(root, "banana");
search_index(root, "boo");
return 0;
}
|
Generate an equivalent C version of this C# code. | Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Port the following code from C# to C with equivalent syntax and logic. | Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Please provide an equivalent version of this C# code in C. | Using System;
class Program
{
static int gcd(int m, int n)
{
return n == 0 ? Math.Abs(m) : gcd(n, n % m);
}
static int lcm(int m, int n)
{
return Math.Abs(m * n) / gcd(m, n);
}
static void Main()
{
Console.WriteLine("lcm(12,18)=" + lcm(12,18));
}
}
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | class Program
{
static void Main(string[] args)
{
Random random = new Random();
while (true)
{
int a = random.Next(20);
Console.WriteLine(a);
if (a == 10)
break;
int b = random.Next(20)
Console.WriteLine(b);
}
Console.ReadLine();
}
}
| int main(){
time_t t;
int a, b;
srand((unsigned)time(&t));
for(;;){
a = rand() % 20;
printf("%d\n", a);
if(a == 10)
break;
b = rand() % 20;
printf("%d\n", b);
}
return 0;
}
|
Write a version of this C# function in C with identical behavior. | class Program
{
static void Main(string[] args)
{
int[][] wta = {
new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 },
new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }};
string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " ";
for (int i = 0; i < wta.Length; i++)
{
int bpf; blk = ""; do
{
string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++)
{
if (wta[i][j] > 0)
{ floor += tb; wta[i][j] -= 1; bpf += 1; }
else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt);
}
if (bpf > 0) blk = floor + lf + blk;
} while (bpf > 0);
while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt);
while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt);
if (args.Length > 0) System.Console.Write("\n{0}", blk);
System.Console.WriteLine("Block {0} retains {1,2} water units.",
i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2);
}
}
}
| #include<stdlib.h>
#include<stdio.h>
int getWater(int* arr,int start,int end,int cutoff){
int i, sum = 0;
for(i=start;i<=end;i++)
sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);
return sum;
}
int netWater(int* arr,int size){
int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;
if(size<3)
return 0;
for(i=0;i<size-1;i++){
start:if(i!=size-2 && arr[i]>arr[i+1]){
ref1 = i;
for(j=ref1+1;j<size;j++){
if(arr[j]>=arr[ref1]){
ref2 = j;
sum += getWater(arr,ref1+1,ref2-1,ref1);
i = ref2;
goto start;
}
else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){
marker = j+1;
markerSet = 1;
}
}
if(markerSet==1){
sum += getWater(arr,ref1+1,marker-1,marker);
i = marker;
markerSet = 0;
goto start;
}
}
}
return sum;
}
int main(int argC,char* argV[])
{
int *arr,i;
if(argC==1)
printf("Usage : %s <followed by space separated series of integers>");
else{
arr = (int*)malloc((argC-1)*sizeof(int));
for(i=1;i<argC;i++)
arr[i-1] = atoi(argV[i]);
printf("Water collected : %d",netWater(arr,argC-1));
}
return 0;
}
|
Produce a language-to-language conversion: from C# to C, same semantics. | using System;
class Program {
static bool ispr(uint n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (uint j = 3; j * j <= n; j += 2)
if (n % j == 0) return false; return true; }
static void Main(string[] args) {
uint c = 0; int nc;
var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var nxt = new uint[128];
while (true) {
nc = 0;
foreach (var a in ps) {
if (ispr(a))
Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " ");
for (uint b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) {
Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); }
else break;
}
Console.WriteLine("\n{0} descending primes found", c);
}
}
| #include <stdio.h>
int ispr(unsigned int n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (unsigned int j = 3; j * j <= n; j += 2)
if (n % j == 0) return 0; return 1; }
int main() {
unsigned int c = 0, nc, pc = 9, i, a, b, l,
ps[128], nxt[128];
for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;
while (1) {
nc = 0;
for (i = 0; i < pc; i++) {
if (ispr(a = ps[i]))
printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
for (b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
else break;
}
printf("\n%d descending primes found", c);
}
|
Generate an equivalent C version of this C# code. | using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const int maxSum = 100;
var pairs = (
from X in 2.To(maxSum / 2 - 1)
from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)
select new { X, Y, S = X + Y, P = X * Y }
).ToHashSet();
Console.WriteLine(pairs.Count);
var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
foreach (var pair in pairs) Console.WriteLine(pair);
}
}
public static class Extensions
{
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i <= end; i++) yield return i;
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t {
int x, y;
struct node_t *prev, *next;
} node;
node *new_node(int x, int y) {
node *n = malloc(sizeof(node));
n->x = x;
n->y = y;
n->next = NULL;
n->prev = NULL;
return n;
}
void free_node(node **n) {
if (n == NULL) {
return;
}
(*n)->prev = NULL;
(*n)->next = NULL;
free(*n);
*n = NULL;
}
typedef struct list_t {
node *head;
node *tail;
} list;
list make_list() {
list lst = { NULL, NULL };
return lst;
}
void append_node(list *const lst, int x, int y) {
if (lst == NULL) {
return;
}
node *n = new_node(x, y);
if (lst->head == NULL) {
lst->head = n;
lst->tail = n;
} else {
n->prev = lst->tail;
lst->tail->next = n;
lst->tail = n;
}
}
void remove_node(list *const lst, const node *const n) {
if (lst == NULL || n == NULL) {
return;
}
if (n->prev != NULL) {
n->prev->next = n->next;
if (n->next != NULL) {
n->next->prev = n->prev;
} else {
lst->tail = n->prev;
}
} else {
if (n->next != NULL) {
n->next->prev = NULL;
lst->head = n->next;
}
}
free_node(&n);
}
void free_list(list *const lst) {
node *ptr;
if (lst == NULL) {
return;
}
ptr = lst->head;
while (ptr != NULL) {
node *nxt = ptr->next;
free_node(&ptr);
ptr = nxt;
}
lst->head = NULL;
lst->tail = NULL;
}
void print_list(const list *lst) {
node *it;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
int prod = it->x * it->y;
printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod);
}
}
void print_count(const list *const lst) {
node *it;
int c = 0;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
c++;
}
if (c == 0) {
printf("no candidates\n");
} else if (c == 1) {
printf("one candidate\n");
} else {
printf("%d candidates\n", c);
}
}
void setup(list *const lst) {
int x, y;
if (lst == NULL) {
return;
}
for (x = 2; x <= 98; x++) {
for (y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
append_node(lst, x, y);
}
}
}
}
void remove_by_sum(list *const lst, const int sum) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int s = it->x + it->y;
if (s == sum) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void remove_by_prod(list *const lst, const int prod) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int p = it->x * it->y;
if (p == prod) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void statement1(list *const lst) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = lst->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = lst->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] == 1) {
remove_by_sum(lst, it->x + it->y);
it = lst->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement2(list *const candidates) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = candidates->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] > 1) {
remove_by_prod(candidates, prod);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement3(list *const candidates) {
short *unique = calloc(100, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
unique[sum]++;
}
it = candidates->head;
while (it != NULL) {
int sum = it->x + it->y;
nxt = it->next;
if (unique[sum] > 1) {
remove_by_sum(candidates, sum);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
int main() {
list candidates = make_list();
setup(&candidates);
print_count(&candidates);
statement1(&candidates);
print_count(&candidates);
statement2(&candidates);
print_count(&candidates);
statement3(&candidates);
print_count(&candidates);
print_list(&candidates);
free_list(&candidates);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C# to C. | using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
const int maxSum = 100;
var pairs = (
from X in 2.To(maxSum / 2 - 1)
from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum)
select new { X, Y, S = X + Y, P = X * Y }
).ToHashSet();
Console.WriteLine(pairs.Count);
var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g));
Console.WriteLine(pairs.Count);
foreach (var pair in pairs) Console.WriteLine(pair);
}
}
public static class Extensions
{
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i <= end; i++) yield return i;
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t {
int x, y;
struct node_t *prev, *next;
} node;
node *new_node(int x, int y) {
node *n = malloc(sizeof(node));
n->x = x;
n->y = y;
n->next = NULL;
n->prev = NULL;
return n;
}
void free_node(node **n) {
if (n == NULL) {
return;
}
(*n)->prev = NULL;
(*n)->next = NULL;
free(*n);
*n = NULL;
}
typedef struct list_t {
node *head;
node *tail;
} list;
list make_list() {
list lst = { NULL, NULL };
return lst;
}
void append_node(list *const lst, int x, int y) {
if (lst == NULL) {
return;
}
node *n = new_node(x, y);
if (lst->head == NULL) {
lst->head = n;
lst->tail = n;
} else {
n->prev = lst->tail;
lst->tail->next = n;
lst->tail = n;
}
}
void remove_node(list *const lst, const node *const n) {
if (lst == NULL || n == NULL) {
return;
}
if (n->prev != NULL) {
n->prev->next = n->next;
if (n->next != NULL) {
n->next->prev = n->prev;
} else {
lst->tail = n->prev;
}
} else {
if (n->next != NULL) {
n->next->prev = NULL;
lst->head = n->next;
}
}
free_node(&n);
}
void free_list(list *const lst) {
node *ptr;
if (lst == NULL) {
return;
}
ptr = lst->head;
while (ptr != NULL) {
node *nxt = ptr->next;
free_node(&ptr);
ptr = nxt;
}
lst->head = NULL;
lst->tail = NULL;
}
void print_list(const list *lst) {
node *it;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
int prod = it->x * it->y;
printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod);
}
}
void print_count(const list *const lst) {
node *it;
int c = 0;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
c++;
}
if (c == 0) {
printf("no candidates\n");
} else if (c == 1) {
printf("one candidate\n");
} else {
printf("%d candidates\n", c);
}
}
void setup(list *const lst) {
int x, y;
if (lst == NULL) {
return;
}
for (x = 2; x <= 98; x++) {
for (y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
append_node(lst, x, y);
}
}
}
}
void remove_by_sum(list *const lst, const int sum) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int s = it->x + it->y;
if (s == sum) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void remove_by_prod(list *const lst, const int prod) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int p = it->x * it->y;
if (p == prod) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void statement1(list *const lst) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = lst->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = lst->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] == 1) {
remove_by_sum(lst, it->x + it->y);
it = lst->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement2(list *const candidates) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = candidates->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] > 1) {
remove_by_prod(candidates, prod);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement3(list *const candidates) {
short *unique = calloc(100, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
unique[sum]++;
}
it = candidates->head;
while (it != NULL) {
int sum = it->x + it->y;
nxt = it->next;
if (unique[sum] > 1) {
remove_by_sum(candidates, sum);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
int main() {
list candidates = make_list();
setup(&candidates);
print_count(&candidates);
statement1(&candidates);
print_count(&candidates);
statement2(&candidates);
print_count(&candidates);
statement3(&candidates);
print_count(&candidates);
print_list(&candidates);
free_list(&candidates);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C# code. | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
Console.WriteLine(infix.ToPostfix());
}
}
public static class ShuntingYard
{
private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators
= new (string symbol, int precedence, bool rightAssociative) [] {
("^", 4, true),
("*", 3, false),
("/", 3, false),
("+", 2, false),
("-", 2, false)
}.ToDictionary(op => op.symbol);
public static string ToPostfix(this string infix) {
string[] tokens = infix.Split(' ');
var stack = new Stack<string>();
var output = new List<string>();
foreach (string token in tokens) {
if (int.TryParse(token, out _)) {
output.Add(token);
Print(token);
} else if (operators.TryGetValue(token, out var op1)) {
while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {
int c = op1.precedence.CompareTo(op2.precedence);
if (c < 0 || !op1.rightAssociative && c <= 0) {
output.Add(stack.Pop());
} else {
break;
}
}
stack.Push(token);
Print(token);
} else if (token == "(") {
stack.Push(token);
Print(token);
} else if (token == ")") {
string top = "";
while (stack.Count > 0 && (top = stack.Pop()) != "(") {
output.Add(top);
}
if (top != "(") throw new ArgumentException("No matching left parenthesis.");
Print(token);
}
}
while (stack.Count > 0) {
var top = stack.Pop();
if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis.");
output.Add(top);
}
Print("pop");
return string.Join(" ", output);
void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}");
void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]");
}
}
| #include <sys/types.h>
#include <regex.h>
#include <stdio.h>
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};
pat_t pat_ops[] = {
{"^\\)", A_NONE, -1},
{"^\\*\\*", A_R, 3},
{"^\\^", A_R, 3},
{"^\\*", A_L, 2},
{"^/", A_L, 2},
{"^\\+", A_L, 1},
{"^-", A_L, 1},
{0}
};
pat_t pat_arg[] = {
{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
{"^[a-zA-Z_][a-zA-Z_0-9]*"},
{"^\\(", A_L, -1},
{0}
};
str_tok_t stack[256];
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop() stack[--l_stack]
void display(const char *s)
{
int i;
printf("\033[1;1H\033[JText | %s", s);
printf("\nStack| ");
for (i = 0; i < l_stack; i++)
printf("%.*s ", stack[i].len, stack[i].s);
printf("\nQueue| ");
for (i = 0; i < l_queue; i++)
printf("%.*s ", queue[i].len, queue[i].s);
puts("\n\n<press enter>");
getchar();
}
int prec_booster;
#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}
int init(void)
{
int i;
pat_t *p;
for (i = 0, p = pat_ops; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
for (i = 0, p = pat_arg; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
return 1;
}
pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
int i;
regmatch_t m;
while (*s == ' ') s++;
*e = s;
if (!*s) return &pat_eos;
for (i = 0; p[i].str; i++) {
if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
continue;
t->s = s;
*e = s + (t->len = m.rm_eo - m.rm_so);
return p + i;
}
return 0;
}
int parse(const char *s) {
pat_t *p;
str_tok_t *t, tok;
prec_booster = l_queue = l_stack = 0;
display(s);
while (*s) {
p = match(s, pat_arg, &tok, &s);
if (!p || p == &pat_eos) fail("parse arg", s);
if (p->prec == -1) {
prec_booster += 100;
continue;
}
qpush(tok);
display(s);
re_op: p = match(s, pat_ops, &tok, &s);
if (!p) fail("parse op", s);
tok.assoc = p->assoc;
tok.prec = p->prec;
if (p->prec > 0)
tok.prec = p->prec + prec_booster;
else if (p->prec == -1) {
if (prec_booster < 100)
fail("unmatched )", s);
tok.prec = prec_booster;
}
while (l_stack) {
t = stack + l_stack - 1;
if (!(t->prec == tok.prec && t->assoc == A_L)
&& t->prec <= tok.prec)
break;
qpush(spop());
display(s);
}
if (p->prec == -1) {
prec_booster -= 100;
goto re_op;
}
if (!p->prec) {
display(s);
if (prec_booster)
fail("unmatched (", s);
return 1;
}
spush(tok);
display(s);
}
if (p->prec > 0)
fail("unexpected eol", s);
return 1;
}
int main()
{
int i;
const char *tests[] = {
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"123",
"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14",
"(((((((1+2+3**(4 + 5))))))",
"a^(b + c/d * .1e5)!",
"(1**2)**3",
"2 + 2 *",
0
};
if (!init()) return 1;
for (i = 0; tests[i]; i++) {
printf("Testing string `%s' <enter>\n", tests[i]);
getchar();
printf("string `%s': %s\n\n", tests[i],
parse(tests[i]) ? "Ok" : "Error");
}
return 0;
}
|
Can you help me rewrite this code in C instead of C#, keeping it the same logically? | using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * mid3(int n)
{
static char buf[32];
int l;
sprintf(buf, "%d", n > 0 ? n : -n);
l = strlen(buf);
if (l < 3 || !(l & 1)) return 0;
l = l / 2 - 1;
buf[l + 3] = 0;
return buf + l;
}
int main(void)
{
int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
1234567890};
int i;
char *m;
for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
if (!(m = mid3(x[i])))
m = "error";
printf("%d: %s\n", x[i], m);
}
return 0;
}
|
Write the same code in C as shown below in C#. | using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static List<int> l = new List<int>() { 1, 1 };
static int gcd(int a, int b) {
return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }
static void Main(string[] args) {
int max = 1000; int take = 15; int i = 1;
int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };
do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }
while (l.Count < max || l[l.Count - 2] != selection.Last());
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take);
Console.WriteLine("{0}\n", string.Join(", ", l.Take(take)));
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:");
foreach (int ii in selection) {
int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); }
Console.WriteLine(); bool good = true;
for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" +
" series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
}
}
| k=2; i=1; j=2;
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
}
|
Change the programming language of this snippet from C# to C without modifying what it does. | using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static List<int> l = new List<int>() { 1, 1 };
static int gcd(int a, int b) {
return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }
static void Main(string[] args) {
int max = 1000; int take = 15; int i = 1;
int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 };
do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; }
while (l.Count < max || l[l.Count - 2] != selection.Last());
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take);
Console.WriteLine("{0}\n", string.Join(", ", l.Take(take)));
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:");
foreach (int ii in selection) {
int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); }
Console.WriteLine(); bool good = true;
for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } }
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" +
" series up to the {0}th item is {1}always one.", max, good ? "" : "not ");
}
}
| k=2; i=1; j=2;
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
}
|
Rewrite the snippet below in C so it works the same as the original C# code. |
public static class XMLSystem
{
static XMLSystem()
{
}
public static XmlDocument GetXML(string name)
{
return null;
}
}
|
int add(int a, int b) {
return a + b;
}
|
Change the following C# code into C without altering its purpose. | using System;
namespace ApolloniusProblemCalc
{
class Program
{
static float rs = 0;
static float xs = 0;
static float ys = 0;
public static void Main(string[] args)
{
float gx1;
float gy1;
float gr1;
float gx2;
float gy2;
float gr2;
float gx3;
float gy3;
float gr3;
gx1 = 0;
gy1 = 0;
gr1 = 1;
gx2 = 4;
gy2 = 0;
gr2 = 1;
gx3 = 2;
gy3 = 4;
gr3 = 2;
for (int i = 1; i <= 8; i++)
{
SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3);
if (i == 1)
{
Console.WriteLine("X of point of the " + i + "st solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "st solution: " + ys.ToString());
Console.WriteLine(i + "st Solution circle's radius: " + rs.ToString());
}
else if (i == 2)
{
Console.WriteLine("X of point of the " + i + "ed solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "ed solution: " + ys.ToString());
Console.WriteLine(i + "ed Solution circle's radius: " + rs.ToString());
}
else if(i == 3)
{
Console.WriteLine("X of point of the " + i + "rd solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "rd solution: " + ys.ToString());
Console.WriteLine(i + "rd Solution circle's radius: " + rs.ToString());
}
else
{
Console.WriteLine("X of point of the " + i + "th solution: " + xs.ToString());
Console.WriteLine("Y of point of the " + i + "th solution: " + ys.ToString());
Console.WriteLine(i + "th Solution circle's radius: " + rs.ToString());
}
Console.WriteLine();
}
Console.ReadKey(true);
}
private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3)
{
float s1 = 1;
float s2 = 1;
float s3 = 1;
if (calcCounter == 2)
{
s1 = -1;
s2 = -1;
s3 = -1;
}
else if (calcCounter == 3)
{
s1 = 1;
s2 = -1;
s3 = -1;
}
else if (calcCounter == 4)
{
s1 = -1;
s2 = 1;
s3 = -1;
}
else if (calcCounter == 5)
{
s1 = -1;
s2 = -1;
s3 = 1;
}
else if (calcCounter == 6)
{
s1 = 1;
s2 = 1;
s3 = -1;
}
else if (calcCounter == 7)
{
s1 = -1;
s2 = 1;
s3 = 1;
}
else if (calcCounter == 8)
{
s1 = 1;
s2 = -1;
s3 = 1;
}
float v11 = 2 * x2 - 2 * x1;
float v12 = 2 * y2 - 2 * y1;
float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2;
float v14 = 2 * s2 * r2 - 2 * s1 * r1;
float v21 = 2 * x3 - 2 * x2;
float v22 = 2 * y3 - 2 * y2;
float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3;
float v24 = 2 * s3 * r3 - 2 * s2 * r2;
float w12 = v12 / v11;
float w13 = v13 / v11;
float w14 = v14 / v11;
float w22 = v22 / v21 - w12;
float w23 = v23 / v21 - w13;
float w24 = v24 / v21 - w14;
float P = -w23 / w22;
float Q = w24 / w22;
float M = -w12 * P - w13;
float N = w14 - w12 * Q;
float a = N * N + Q * Q - 1;
float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1;
float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1;
float D = b * b - 4 * a * c;
rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString()));
xs = M + N * rs;
ys = P + Q * rs;
}
}
}
| #include <stdio.h>
#include <tgmath.h>
#define VERBOSE 0
#define for3 for(int i = 0; i < 3; i++)
typedef complex double vec;
typedef struct { vec c; double r; } circ;
#define re(x) creal(x)
#define im(x) cimag(x)
#define cp(x) re(x), im(x)
#define CPLX "(%6.3f,%6.3f)"
#define CPLX3 CPLX" "CPLX" "CPLX
double cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); }
double abs2(vec a) { return a * conj(a); }
int apollonius_in(circ aa[], int ss[], int flip, int divert)
{
vec n[3], x[3], t[3], a, b, center;
int s[3], iter = 0, res = 0;
double diff = 1, diff_old = -1, axb, d, r;
for3 {
s[i] = ss[i] ? 1 : -1;
x[i] = aa[i].c;
}
while (diff > 1e-20) {
a = x[0] - x[2], b = x[1] - x[2];
diff = 0;
axb = -cross(a, b);
d = sqrt(abs2(a) * abs2(b) * abs2(a - b));
if (VERBOSE) {
const char *z = 1 + "-0+";
printf("%c%c%c|%c%c|",
z[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]);
printf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2]));
}
r = fabs(d / (2 * axb));
center = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2];
if (!axb && flip != -1 && !divert) {
if (!d) {
printf("Given conditions confused me.\n");
return 0;
}
if (VERBOSE) puts("\n[divert]");
divert = 1;
res = apollonius_in(aa, ss, -1, 1);
}
for3 n[i] = axb ? aa[i].c - center : a * I * flip;
for3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i];
for3 diff += abs2(t[i] - x[i]), x[i] = t[i];
if (VERBOSE) printf(" %g\n", diff);
if (diff >= diff_old && diff_old >= 0)
if (iter++ > 20) return res;
diff_old = diff;
}
printf("found: ");
if (axb) printf("circle "CPLX", r = %f\n", cp(center), r);
else printf("line "CPLX3"\n", cp(x[0]), cp(x[1]), cp(x[2]));
return res + 1;
}
int apollonius(circ aa[])
{
int s[3], i, sum = 0;
for (i = 0; i < 8; i++) {
s[0] = i & 1, s[1] = i & 2, s[2] = i & 4;
if (s[0] && !aa[0].r) continue;
if (s[1] && !aa[1].r) continue;
if (s[2] && !aa[2].r) continue;
sum += apollonius_in(aa, s, 1, 0);
}
return sum;
}
int main()
{
circ a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}};
circ b[3] = {{-3, 2}, {0, 1}, {3, 2}};
circ c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}};
puts("set 1"); apollonius(a);
puts("set 2"); apollonius(b);
puts("set 3"); apollonius(c);
}
|
Write the same algorithm in C as shown in this C# implementation. | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::string lcs(const std::vector<std::string>& strs) {
std::vector<std::string::const_reverse_iterator> backs;
std::string s;
if (strs.size() == 0) return "";
if (strs.size() == 1) return strs[0];
for (auto& str : strs) backs.push_back(str.crbegin());
while (backs[0] != strs[0].crend()) {
char ch = *backs[0]++;
for (std::size_t i = 1; i<strs.size(); i++) {
if (backs[i] == strs[i].crend()) goto done;
if (*backs[i] != ch) goto done;
backs[i]++;
}
s.push_back(ch);
}
done:
reverse(s.begin(), s.end());
return s;
}
void test(const std::vector<std::string>& strs) {
std::cout << "[";
for (std::size_t i = 0; i<strs.size(); i++) {
std::cout << '"' << strs[i] << '"';
if (i != strs.size()-1) std::cout << ", ";
}
std::cout << "] -> `" << lcs(strs) << "`\n";
}
int main() {
std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"};
std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"};
std::vector<std::string> t3 =
{"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"};
std::vector<std::string> t4 = {"longest", "common", "suffix"};
std::vector<std::string> t5 = {""};
std::vector<std::string> t6 = {};
std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"};
std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};
for (auto t : tests) test(t);
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node_t {
char *elem;
int length;
struct node_t *next;
} node;
node *make_node(char *s) {
node *t = malloc(sizeof(node));
t->elem = s;
t->length = strlen(s);
t->next = NULL;
return t;
}
void append_node(node *head, node *elem) {
while (head->next != NULL) {
head = head->next;
}
head->next = elem;
}
void print_node(node *n) {
putc('[', stdout);
while (n != NULL) {
printf("`%s` ", n->elem);
n = n->next;
}
putc(']', stdout);
}
char *lcs(node *list) {
int minLen = INT_MAX;
int i;
char *res;
node *ptr;
if (list == NULL) {
return "";
}
if (list->next == NULL) {
return list->elem;
}
for (ptr = list; ptr != NULL; ptr = ptr->next) {
minLen = min(minLen, ptr->length);
}
if (minLen == 0) {
return "";
}
res = "";
for (i = 1; i < minLen; i++) {
char *suffix = &list->elem[list->length - i];
for (ptr = list->next; ptr != NULL; ptr = ptr->next) {
char *e = &ptr->elem[ptr->length - i];
if (strcmp(suffix, e) != 0) {
return res;
}
}
res = suffix;
}
return res;
}
void test(node *n) {
print_node(n);
printf(" -> `%s`\n", lcs(n));
}
void case1() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbabc"));
test(n);
}
void case2() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbazc"));
test(n);
}
void case3() {
node *n = make_node("Sunday");
append_node(n, make_node("Monday"));
append_node(n, make_node("Tuesday"));
append_node(n, make_node("Wednesday"));
append_node(n, make_node("Thursday"));
append_node(n, make_node("Friday"));
append_node(n, make_node("Saturday"));
test(n);
}
void case4() {
node *n = make_node("longest");
append_node(n, make_node("common"));
append_node(n, make_node("suffix"));
test(n);
}
void case5() {
node *n = make_node("suffix");
test(n);
}
void case6() {
node *n = make_node("");
test(n);
}
int main() {
case1();
case2();
case3();
case4();
case5();
case6();
return 0;
}
|
Generate an equivalent C version of this C# code. | using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ChatServer {
class State {
private TcpClient client;
private StringBuilder sb = new StringBuilder();
public string Name { get; }
public State(string name, TcpClient client) {
Name = name;
this.client = client;
}
public void Add(byte b) {
sb.Append((char)b);
}
public void Send(string text) {
var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text));
client.GetStream().Write(bytes, 0, bytes.Length);
}
}
class Program {
static TcpListener listen;
static Thread serverthread;
static Dictionary<int, State> connections = new Dictionary<int, State>();
static void Main(string[] args) {
listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004);
serverthread = new Thread(new ThreadStart(DoListen));
serverthread.Start();
}
private static void DoListen() {
listen.Start();
Console.WriteLine("Server: Started server");
while (true) {
Console.WriteLine("Server: Waiting...");
TcpClient client = listen.AcceptTcpClient();
Console.WriteLine("Server: Waited");
Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));
clientThread.Start(client);
}
}
private static void DoClient(object client) {
TcpClient tClient = (TcpClient)client;
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId);
byte[] bytes = Encoding.ASCII.GetBytes("Enter name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
string name = string.Empty;
bool done = false;
do {
if (!tClient.Connected) {
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
name = Receive(tClient);
done = true;
if (done) {
foreach (var cl in connections) {
var state = cl.Value;
if (state.Name == name) {
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
done = false;
}
}
}
} while (!done);
connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));
Console.WriteLine("\tTotal connections: {0}", connections.Count);
Broadcast(string.Format("+++ {0} arrived +++", name));
do {
string text = Receive(tClient);
if (text == "/quit") {
Broadcast(string.Format("Connection from {0} closed.", name));
connections.Remove(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("\tTotal connections: {0}", connections.Count);
break;
}
if (!tClient.Connected) {
break;
}
Broadcast(string.Format("{0}> {1}", name, text));
} while (true);
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
private static string Receive(TcpClient client) {
StringBuilder sb = new StringBuilder();
do {
if (client.Available > 0) {
while (client.Available > 0) {
char ch = (char)client.GetStream().ReadByte();
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.ToString();
}
sb.Append(ch);
}
}
Thread.Sleep(100);
} while (true);
}
private static void Broadcast(string text) {
Console.WriteLine(text);
foreach (var oClient in connections) {
if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {
State state = oClient.Value;
state.Send(text);
}
}
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h>
int tsocket;
struct sockaddr_in tsockinfo;
fd_set status, current;
void ClientText(int handle, char *buf, int buf_len);
struct client
{
char buffer[4096];
int pos;
char name[32];
} *connections[FD_SETSIZE];
void AddConnection(int handle)
{
connections[handle] = malloc(sizeof(struct client));
connections[handle]->buffer[0] = '\0';
connections[handle]->pos = 0;
connections[handle]->name[0] = '\0';
}
void CloseConnection(int handle)
{
char buf[512];
int j;
FD_CLR(handle, &status);
if (connections[handle]->name[0])
{
sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name);
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, buf, strlen(buf)) < 0)
{
CloseConnection(j);
}
}
}
} else
{
printf ("-- Connection %d disconnected\n", handle);
}
if (connections[handle])
{
free(connections[handle]);
}
close(handle);
}
void strip(char *buf)
{
char *x;
x = strchr(buf, '\n');
if (x) { *x='\0'; }
x = strchr(buf, '\r');
if (x) { *x='\0'; }
}
int RelayText(int handle)
{
char *begin, *end;
int ret = 0;
begin = connections[handle]->buffer;
if (connections[handle]->pos == 4000)
{
if (begin[3999] != '\n')
begin[4000] = '\0';
else {
begin[4000] = '\n';
begin[4001] = '\0';
}
} else {
begin[connections[handle]->pos] = '\0';
}
end = strchr(begin, '\n');
while (end != NULL)
{
char output[8000];
output[0] = '\0';
if (!connections[handle]->name[0])
{
strncpy(connections[handle]->name, begin, 31);
connections[handle]->name[31] = '\0';
strip(connections[handle]->name);
sprintf(output, "* Connected: %s\r\n", connections[handle]->name);
ret = 1;
} else
{
sprintf(output, "%s: %.*s\r\n", connections[handle]->name,
end-begin, begin);
ret = 1;
}
if (output[0])
{
int j;
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, output, strlen(output)) < 0)
{
CloseConnection(j);
}
}
}
}
begin = end+1;
end = strchr(begin, '\n');
}
strcpy(connections[handle]->buffer, begin);
connections[handle]->pos -= begin - connections[handle]->buffer;
return ret;
}
void ClientText(int handle, char *buf, int buf_len)
{
int i, j;
if (!connections[handle])
return;
j = connections[handle]->pos;
for (i = 0; i < buf_len; ++i, ++j)
{
connections[handle]->buffer[j] = buf[i];
if (j == 4000)
{
while (RelayText(handle));
j = connections[handle]->pos;
}
}
connections[handle]->pos = j;
while (RelayText(handle));
}
int ChatLoop()
{
int i, j;
FD_ZERO(&status);
FD_SET(tsocket, &status);
FD_SET(0, &status);
while(1)
{
current = status;
if (select(FD_SETSIZE, ¤t, NULL, NULL, NULL)==-1)
{
perror("Select");
return 0;
}
for (i = 0; i < FD_SETSIZE; ++i)
{
if (FD_ISSET(i, ¤t))
{
if (i == tsocket)
{
struct sockaddr_in cliinfo;
socklen_t addrlen = sizeof(cliinfo);
int handle;
handle = accept(tsocket, &cliinfo, &addrlen);
if (handle == -1)
{
perror ("Couldn't accept connection");
} else if (handle > FD_SETSIZE)
{
printf ("Unable to accept new connection.\n");
close(handle);
}
else
{
if (write(handle, "Enter name: ", 12) >= 0)
{
printf("-- New connection %d from %s:%hu\n",
handle,
inet_ntoa (cliinfo.sin_addr),
ntohs(cliinfo.sin_port));
FD_SET(handle, &status);
AddConnection(handle);
}
}
}
else
{
char buf[512];
int b;
b = read(i, buf, 500);
if (b <= 0)
{
CloseConnection(i);
}
else
{
ClientText(i, buf, b);
}
}
}
}
}
}
int main (int argc, char*argv[])
{
tsocket = socket(PF_INET, SOCK_STREAM, 0);
tsockinfo.sin_family = AF_INET;
tsockinfo.sin_port = htons(7070);
if (argc > 1)
{
tsockinfo.sin_port = htons(atoi(argv[1]));
}
tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);
printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));
if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)
{
perror("Couldn't bind socket");
return -1;
}
if (listen(tsocket, 10) == -1)
{
perror("Couldn't listen to port");
}
ChatLoop();
return 0;
}
|
Convert the following code from C# to C, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ChatServer {
class State {
private TcpClient client;
private StringBuilder sb = new StringBuilder();
public string Name { get; }
public State(string name, TcpClient client) {
Name = name;
this.client = client;
}
public void Add(byte b) {
sb.Append((char)b);
}
public void Send(string text) {
var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text));
client.GetStream().Write(bytes, 0, bytes.Length);
}
}
class Program {
static TcpListener listen;
static Thread serverthread;
static Dictionary<int, State> connections = new Dictionary<int, State>();
static void Main(string[] args) {
listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004);
serverthread = new Thread(new ThreadStart(DoListen));
serverthread.Start();
}
private static void DoListen() {
listen.Start();
Console.WriteLine("Server: Started server");
while (true) {
Console.WriteLine("Server: Waiting...");
TcpClient client = listen.AcceptTcpClient();
Console.WriteLine("Server: Waited");
Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));
clientThread.Start(client);
}
}
private static void DoClient(object client) {
TcpClient tClient = (TcpClient)client;
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId);
byte[] bytes = Encoding.ASCII.GetBytes("Enter name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
string name = string.Empty;
bool done = false;
do {
if (!tClient.Connected) {
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
name = Receive(tClient);
done = true;
if (done) {
foreach (var cl in connections) {
var state = cl.Value;
if (state.Name == name) {
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ");
tClient.GetStream().Write(bytes, 0, bytes.Length);
done = false;
}
}
}
} while (!done);
connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient));
Console.WriteLine("\tTotal connections: {0}", connections.Count);
Broadcast(string.Format("+++ {0} arrived +++", name));
do {
string text = Receive(tClient);
if (text == "/quit") {
Broadcast(string.Format("Connection from {0} closed.", name));
connections.Remove(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("\tTotal connections: {0}", connections.Count);
break;
}
if (!tClient.Connected) {
break;
}
Broadcast(string.Format("{0}> {1}", name, text));
} while (true);
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId);
tClient.Close();
Thread.CurrentThread.Abort();
}
private static string Receive(TcpClient client) {
StringBuilder sb = new StringBuilder();
do {
if (client.Available > 0) {
while (client.Available > 0) {
char ch = (char)client.GetStream().ReadByte();
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.ToString();
}
sb.Append(ch);
}
}
Thread.Sleep(100);
} while (true);
}
private static void Broadcast(string text) {
Console.WriteLine(text);
foreach (var oClient in connections) {
if (oClient.Key != Thread.CurrentThread.ManagedThreadId) {
State state = oClient.Value;
state.Send(text);
}
}
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/ip.h>
int tsocket;
struct sockaddr_in tsockinfo;
fd_set status, current;
void ClientText(int handle, char *buf, int buf_len);
struct client
{
char buffer[4096];
int pos;
char name[32];
} *connections[FD_SETSIZE];
void AddConnection(int handle)
{
connections[handle] = malloc(sizeof(struct client));
connections[handle]->buffer[0] = '\0';
connections[handle]->pos = 0;
connections[handle]->name[0] = '\0';
}
void CloseConnection(int handle)
{
char buf[512];
int j;
FD_CLR(handle, &status);
if (connections[handle]->name[0])
{
sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name);
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, buf, strlen(buf)) < 0)
{
CloseConnection(j);
}
}
}
} else
{
printf ("-- Connection %d disconnected\n", handle);
}
if (connections[handle])
{
free(connections[handle]);
}
close(handle);
}
void strip(char *buf)
{
char *x;
x = strchr(buf, '\n');
if (x) { *x='\0'; }
x = strchr(buf, '\r');
if (x) { *x='\0'; }
}
int RelayText(int handle)
{
char *begin, *end;
int ret = 0;
begin = connections[handle]->buffer;
if (connections[handle]->pos == 4000)
{
if (begin[3999] != '\n')
begin[4000] = '\0';
else {
begin[4000] = '\n';
begin[4001] = '\0';
}
} else {
begin[connections[handle]->pos] = '\0';
}
end = strchr(begin, '\n');
while (end != NULL)
{
char output[8000];
output[0] = '\0';
if (!connections[handle]->name[0])
{
strncpy(connections[handle]->name, begin, 31);
connections[handle]->name[31] = '\0';
strip(connections[handle]->name);
sprintf(output, "* Connected: %s\r\n", connections[handle]->name);
ret = 1;
} else
{
sprintf(output, "%s: %.*s\r\n", connections[handle]->name,
end-begin, begin);
ret = 1;
}
if (output[0])
{
int j;
for (j = 0; j < FD_SETSIZE; j++)
{
if (handle != j && j != tsocket && FD_ISSET(j, &status))
{
if (write(j, output, strlen(output)) < 0)
{
CloseConnection(j);
}
}
}
}
begin = end+1;
end = strchr(begin, '\n');
}
strcpy(connections[handle]->buffer, begin);
connections[handle]->pos -= begin - connections[handle]->buffer;
return ret;
}
void ClientText(int handle, char *buf, int buf_len)
{
int i, j;
if (!connections[handle])
return;
j = connections[handle]->pos;
for (i = 0; i < buf_len; ++i, ++j)
{
connections[handle]->buffer[j] = buf[i];
if (j == 4000)
{
while (RelayText(handle));
j = connections[handle]->pos;
}
}
connections[handle]->pos = j;
while (RelayText(handle));
}
int ChatLoop()
{
int i, j;
FD_ZERO(&status);
FD_SET(tsocket, &status);
FD_SET(0, &status);
while(1)
{
current = status;
if (select(FD_SETSIZE, ¤t, NULL, NULL, NULL)==-1)
{
perror("Select");
return 0;
}
for (i = 0; i < FD_SETSIZE; ++i)
{
if (FD_ISSET(i, ¤t))
{
if (i == tsocket)
{
struct sockaddr_in cliinfo;
socklen_t addrlen = sizeof(cliinfo);
int handle;
handle = accept(tsocket, &cliinfo, &addrlen);
if (handle == -1)
{
perror ("Couldn't accept connection");
} else if (handle > FD_SETSIZE)
{
printf ("Unable to accept new connection.\n");
close(handle);
}
else
{
if (write(handle, "Enter name: ", 12) >= 0)
{
printf("-- New connection %d from %s:%hu\n",
handle,
inet_ntoa (cliinfo.sin_addr),
ntohs(cliinfo.sin_port));
FD_SET(handle, &status);
AddConnection(handle);
}
}
}
else
{
char buf[512];
int b;
b = read(i, buf, 500);
if (b <= 0)
{
CloseConnection(i);
}
else
{
ClientText(i, buf, b);
}
}
}
}
}
}
int main (int argc, char*argv[])
{
tsocket = socket(PF_INET, SOCK_STREAM, 0);
tsockinfo.sin_family = AF_INET;
tsockinfo.sin_port = htons(7070);
if (argc > 1)
{
tsockinfo.sin_port = htons(atoi(argv[1]));
}
tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);
printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));
if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1)
{
perror("Couldn't bind socket");
return -1;
}
if (listen(tsocket, 10) == -1)
{
perror("Couldn't listen to port");
}
ChatLoop();
return 0;
}
|
Convert the following code from C# to C, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Program
{
public class FastaEntry
{
public string Name { get; set; }
public StringBuilder Sequence { get; set; }
}
static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile)
{
FastaEntry f = null;
string line;
while ((line = fastaFile.ReadLine()) != null)
{
if (line.StartsWith(";"))
continue;
if (line.StartsWith(">"))
{
if (f != null)
yield return f;
f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() };
}
else if (f != null)
f.Sequence.Append(line);
}
yield return f;
}
static void Main(string[] args)
{
try
{
using (var fastaFile = new StreamReader("fasta.txt"))
{
foreach (FastaEntry f in ParseFasta(fastaFile))
Console.WriteLine("{0}: {1}", f.Name, f.Sequence);
}
}
catch (FileNotFoundException e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("fasta.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
int state = 0;
while ((read = getline(&line, &len, fp)) != -1) {
if (line[read - 1] == '\n')
line[read - 1] = 0;
if (line[0] == '>') {
if (state == 1)
printf("\n");
printf("%s: ", line+1);
state = 1;
} else {
printf("%s", line);
}
}
printf("\n");
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
|
Generate an equivalent C version of this C# code. | using System;
using System.Collections.Generic;
using System.Linq;
public class FindPalindromicNumbers
{
static void Main(string[] args)
{
var query =
PalindromicTernaries()
.Where(IsPalindromicBinary)
.Take(6);
foreach (var x in query) {
Console.WriteLine("Decimal: " + x);
Console.WriteLine("Ternary: " + ToTernary(x));
Console.WriteLine("Binary: " + Convert.ToString(x, 2));
Console.WriteLine();
}
}
public static IEnumerable<long> PalindromicTernaries() {
yield return 0;
yield return 1;
yield return 13;
yield return 23;
var f = new List<long> {0};
long fMiddle = 9;
while (true) {
for (long edge = 1; edge < 3; edge++) {
int i;
do {
long result = fMiddle;
long fLeft = fMiddle * 3;
long fRight = fMiddle / 3;
for (int j = f.Count - 1; j >= 0; j--) {
result += (fLeft + fRight) * f[j];
fLeft *= 3;
fRight /= 3;
}
result += (fLeft + fRight) * edge;
yield return result;
for (i = f.Count - 1; i >= 0; i--) {
if (f[i] == 2) {
f[i] = 0;
} else {
f[i]++;
break;
}
}
} while (i >= 0);
}
f.Add(0);
fMiddle *= 3;
}
}
public static bool IsPalindromicBinary(long number) {
long n = number;
long reverse = 0;
while (n != 0) {
reverse <<= 1;
if ((n & 1) == 1) reverse++;
n >>= 1;
}
return reverse == number;
}
public static string ToTernary(long n)
{
if (n == 0) return "0";
string result = "";
while (n > 0) { {
result = (n % 3) + result;
n /= 3;
}
return result;
}
}
| #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
Write the same algorithm in C as shown in this C# implementation. | using System;
using System.Collections.Generic;
using System.Linq;
public class FindPalindromicNumbers
{
static void Main(string[] args)
{
var query =
PalindromicTernaries()
.Where(IsPalindromicBinary)
.Take(6);
foreach (var x in query) {
Console.WriteLine("Decimal: " + x);
Console.WriteLine("Ternary: " + ToTernary(x));
Console.WriteLine("Binary: " + Convert.ToString(x, 2));
Console.WriteLine();
}
}
public static IEnumerable<long> PalindromicTernaries() {
yield return 0;
yield return 1;
yield return 13;
yield return 23;
var f = new List<long> {0};
long fMiddle = 9;
while (true) {
for (long edge = 1; edge < 3; edge++) {
int i;
do {
long result = fMiddle;
long fLeft = fMiddle * 3;
long fRight = fMiddle / 3;
for (int j = f.Count - 1; j >= 0; j--) {
result += (fLeft + fRight) * f[j];
fLeft *= 3;
fRight /= 3;
}
result += (fLeft + fRight) * edge;
yield return result;
for (i = f.Count - 1; i >= 0; i--) {
if (f[i] == 2) {
f[i] = 0;
} else {
f[i]++;
break;
}
}
} while (i >= 0);
}
f.Add(0);
fMiddle *= 3;
}
}
public static bool IsPalindromicBinary(long number) {
long n = number;
long reverse = 0;
while (n != 0) {
reverse <<= 1;
if ((n & 1) == 1) reverse++;
n >>= 1;
}
return reverse == number;
}
public static string ToTernary(long n)
{
if (n == 0) return "0";
string result = "";
while (n > 0) { {
result = (n % 3) + result;
n /= 3;
}
return result;
}
}
| #include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
Produce a language-to-language conversion: from C# to C, same semantics. | static void Main(string[] args)
{
int bufferHeight = Console.BufferHeight;
int bufferWidth = Console.BufferWidth;
int windowHeight = Console.WindowHeight;
int windowWidth = Console.WindowWidth;
Console.Write("Buffer Height: ");
Console.WriteLine(bufferHeight);
Console.Write("Buffer Width: ");
Console.WriteLine(bufferWidth);
Console.Write("Window Height: ");
Console.WriteLine(windowHeight);
Console.Write("Window Width: ");
Console.WriteLine(windowWidth);
Console.ReadLine();
}
| #include <sys/ioctl.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int
main()
{
struct winsize ws;
int fd;
fd = open("/dev/tty", O_RDWR);
if (fd < 0)
err(1, "/dev/tty");
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, "/dev/tty");
printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.