Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert this Python snippet to C and keep its semantics consistent. |
import os
from math import pi, sin
au_header = bytearray(
[46, 115, 110, 100,
0, 0, 0, 24,
255, 255, 255, 255,
0, 0, 0, 3,
0, 0, 172, 68,
0, 0, 0, 1])
def f(x, freq):
"Compute sine wave as 16-bit integer"
return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536
def play_sine(freq=440, duration=5, oname="pysine.au"):
"Play a sine wave for `duration` seconds"
out = open(oname, 'wb')
out.write(au_header)
v = [f(x, freq) for x in range(duration * 44100 + 1)]
s = []
for i in v:
s.append(i >> 8)
s.append(i % 256)
out.write(bytearray(s))
out.close()
os.system("vlc " + oname)
play_sine()
| #include <stdio.h>
#include <math.h>
#include <stdlib.h>
int header[] = {46, 115, 110, 100, 0, 0, 0, 24,
255, 255, 255, 255, 0, 0, 0, 3,
0, 0, 172, 68, 0, 0, 0, 1};
int main(int argc, char *argv[]){
float freq, dur;
long i, v;
if (argc < 3) {
printf("Usage:\n");
printf(" csine <frequency> <duration>\n");
exit(1);
}
freq = atof(argv[1]);
dur = atof(argv[2]);
for (i = 0; i < 24; i++)
putchar(header[i]);
for (i = 0; i < dur * 44100; i++) {
v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));
v = v % 65536;
putchar(v >> 8);
putchar(v % 256);
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the Python version. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return None
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Rewrite the snippet below in C so it works the same as the original Python code. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return None
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Write a version of this Python function in C with identical behavior. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return None
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
| 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++;
}
|
Write the same algorithm in C as shown in this Python implementation. | from collections import namedtuple
import math
class I(namedtuple('Imprecise', 'value, delta')):
'Imprecise type: I(value=0.0, delta=0.0)'
__slots__ = ()
def __new__(_cls, value=0.0, delta=0.0):
'Defaults to 0.0 ± delta'
return super().__new__(_cls, float(value), abs(float(delta)))
def reciprocal(self):
return I(1. / self.value, self.delta / (self.value**2))
def __str__(self):
'Shorter form of Imprecise as string'
return 'I(%g, %g)' % self
def __neg__(self):
return I(-self.value, self.delta)
def __add__(self, other):
if type(other) == I:
return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )
try:
c = float(other)
except:
return NotImplemented
return I(self.value + c, self.delta)
def __sub__(self, other):
return self + (-other)
def __radd__(self, other):
return I.__add__(self, other)
def __mul__(self, other):
if type(other) == I:
a1,b1 = self
a2,b2 = other
f = a1 * a2
return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )
try:
c = float(other)
except:
return NotImplemented
return I(self.value * c, self.delta * c)
def __pow__(self, other):
if type(other) == I:
return NotImplemented
try:
c = float(other)
except:
return NotImplemented
f = self.value ** c
return I(f, f * c * (self.delta / self.value))
def __rmul__(self, other):
return I.__mul__(self, other)
def __truediv__(self, other):
if type(other) == I:
return self.__mul__(other.reciprocal())
try:
c = float(other)
except:
return NotImplemented
return I(self.value / c, self.delta / c)
def __rtruediv__(self, other):
return other * self.reciprocal()
__div__, __rdiv__ = __truediv__, __rtruediv__
Imprecise = I
def distance(p1, p2):
x1, y1 = p1
x2, y2 = p2
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
x1 = I(100, 1.1)
x2 = I(200, 2.2)
y1 = I( 50, 1.2)
y2 = I(100, 2.3)
p1, p2 = (x1, y1), (x2, y2)
print("Distance between points\n p1: %s\n and p2: %s\n = %r" % (
p1, p2, distance(p1, p2)))
| #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef struct{
double value;
double delta;
}imprecise;
#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value + b.value;
ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));
return ret;
}
imprecise imprecise_mul(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value * b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));
return ret;
}
imprecise imprecise_div(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value / b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);
return ret;
}
imprecise imprecise_pow(imprecise a, double c)
{
imprecise ret;
ret.value = pow(a.value, c);
ret.delta = fabs(ret.value * c * a.delta / a.value);
return ret;
}
char* printImprecise(imprecise val)
{
char principal[30],error[30],*string,sign[2];
sign[0] = 241;
sign[1] = 00;
sprintf(principal,"%f",val.value);
sprintf(error,"%f",val.delta);
string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));
strcpy(string,principal);
strcat(string,sign);
strcat(string,error);
return string;
}
int main(void) {
imprecise x1 = {100, 1.1};
imprecise y1 = {50, 1.2};
imprecise x2 = {-200, 2.2};
imprecise y2 = {-100, 2.3};
imprecise d;
d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);
printf("Distance, d, between the following points :");
printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1));
printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2));
printf("\nis d = %s", printImprecise(d));
return 0;
}
|
Translate this program into C but keep the logic exactly as in Python. | from itertools import groupby
def soundex(word):
codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r")
soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)
cmap2 = lambda kar: soundDict.get(kar, '9')
sdx = ''.join(cmap2(kar) for kar in word.lower())
sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')
sdx3 = sdx2[0:4].ljust(4,'0')
return sdx3
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
static char code[128] = { 0 };
void add_code(const char *s, int c)
{
while (*s) {
code[(int)*s] = code[0x20 ^ (int)*s] = c;
s++;
}
}
void init()
{
static const char *cls[] =
{ "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0};
int i;
for (i = 0; cls[i]; i++)
add_code(cls[i], i - 1);
}
const char* soundex(const char *s)
{
static char out[5];
int c, prev, i;
out[0] = out[4] = 0;
if (!s || !*s) return out;
out[0] = *s++;
prev = code[(int)out[0]];
for (i = 1; *s && i < 4; s++) {
if ((c = code[(int)*s]) == prev) continue;
if (c == -1) prev = 0;
else if (c > 0) {
out[i++] = c + '0';
prev = c;
}
}
while (i < 4) out[i++] = '0';
return out;
}
int main()
{
int i;
const char *sdx, *names[][2] = {
{"Soundex", "S532"},
{"Example", "E251"},
{"Sownteks", "S532"},
{"Ekzampul", "E251"},
{"Euler", "E460"},
{"Gauss", "G200"},
{"Hilbert", "H416"},
{"Knuth", "K530"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"Ellery", "E460"},
{"Ghosh", "G200"},
{"Heilbronn", "H416"},
{"Kant", "K530"},
{"Ladd", "L300"},
{"Lissajous", "L222"},
{"Wheaton", "W350"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"O'Hara", "O600"},
{"Washington", "W252"},
{"Lee", "L000"},
{"Gutierrez", "G362"},
{"Pfister", "P236"},
{"Jackson", "J250"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Ashcraft", "A261"},
{0, 0}
};
init();
puts(" Test name Code Got\n----------------------");
for (i = 0; names[i][0]; i++) {
sdx = soundex(names[i][0]);
printf("%11s %s %s ", names[i][0], names[i][1], sdx);
printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok");
}
return 0;
}
|
Port the following code from Python to C with equivalent syntax and logic. | def bags(n,cache={}):
if not n: return [(0, "")]
upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)]
def bagchain(x, n, bb, start=0):
if not n: return [x]
out = []
for i in range(start, len(bb)):
c,s = bb[i]
if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)
return out
def replace_brackets(s):
depth,out = 0,[]
for c in s:
if c == '(':
out.append("([{"[depth%3])
depth += 1
else:
depth -= 1
out.append(")]}"[depth%3])
return "".join(out)
for x in bags(5): print(replace_brackets(x[1]))
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))
tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};
void append(tree t)
{
if (len == cap) {
cap = cap ? cap*2 : 2;
list = realloc(list, cap*sizeof(tree));
}
list[len++] = 1 | t<<1;
}
void show(tree t, uint len)
{
for (; len--; t >>= 1)
putchar(t&1 ? '(' : ')');
}
void listtrees(uint n)
{
uint i;
for (i = offset[n]; i < offset[n+1]; i++) {
show(list[i], n*2);
putchar('\n');
}
}
void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
if (!rem) {
append(t);
return;
}
if (sl > rem)
pos = offset[sl = rem];
else if (pos >= offset[sl + 1]) {
if (!--sl) return;
pos = offset[sl];
}
assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
assemble(n, t, sl, pos + 1, rem);
}
void mktrees(uint n)
{
if (offset[n + 1]) return;
if (n) mktrees(n - 1);
assemble(n, 0, n-1, offset[n-1], n-1);
offset[n+1] = len;
}
int main(int c, char**v)
{
int n;
if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;
append(0);
mktrees((uint)n);
fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
listtrees((uint)n);
return 0;
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | class Doc(object):
def method(self, num):
pass
|
int add(int a, int b) {
return a + b;
}
|
Preserve the algorithm and functionality while converting the code from Python to C. | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>>
c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]:
c.execute('insert into stocks values (?,?,?,?,?)', t)
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
>>>
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
<sqlite3.Cursor object at 0x01326530>
>>> for row in c:
print row
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)
>>>
| #include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
sqlite3 *db = NULL;
char *errmsg;
const char *code =
"CREATE TABLE employee (\n"
" empID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" firstName TEXT NOT NULL,\n"
" lastName TEXT NOT NULL,\n"
" AGE INTEGER NOT NULL,\n"
" DOB DATE NOT NULL)\n" ;
if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
sqlite3_exec(db, code, NULL, NULL, &errmsg);
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return 0;
}
|
Please provide an equivalent version of this Python code in C. | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>>
c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]:
c.execute('insert into stocks values (?,?,?,?,?)', t)
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
>>>
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
<sqlite3.Cursor object at 0x01326530>
>>> for row in c:
print row
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)
>>>
| #include <sqlite3.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
sqlite3 *db = NULL;
char *errmsg;
const char *code =
"CREATE TABLE employee (\n"
" empID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" firstName TEXT NOT NULL,\n"
" lastName TEXT NOT NULL,\n"
" AGE INTEGER NOT NULL,\n"
" DOB DATE NOT NULL)\n" ;
if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
sqlite3_exec(db, code, NULL, NULL, &errmsg);
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. | from collections import namedtuple
import math
Circle = namedtuple('Circle', 'x, y, r')
def solveApollonius(c1, c2, c3, s1, s2, s3):
x1, y1, r1 = c1
x2, y2, r2 = c2
x3, y3, r3 = c3
v11 = 2*x2 - 2*x1
v12 = 2*y2 - 2*y1
v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2
v14 = 2*s2*r2 - 2*s1*r1
v21 = 2*x3 - 2*x2
v22 = 2*y3 - 2*y2
v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3
v24 = 2*s3*r3 - 2*s2*r2
w12 = v12/v11
w13 = v13/v11
w14 = v14/v11
w22 = v22/v21-w12
w23 = v23/v21-w13
w24 = v24/v21-w14
P = -w23/w22
Q = w24/w22
M = -w12*P-w13
N = w14 - w12*Q
a = N*N + Q*Q - 1
b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1
c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1
D = b*b-4*a*c
rs = (-b-math.sqrt(D))/(2*a)
xs = M+N*rs
ys = P+Q*rs
return Circle(xs, ys, rs)
if __name__ == '__main__':
c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)
print(solveApollonius(c1, c2, c3, 1, 1, 1))
print(solveApollonius(c1, c2, c3, -1, -1, -1))
| #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);
}
|
Preserve the algorithm and functionality while converting the code from Python to C. | list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]
print([
''.join(str(n) for n in z) for z
in zip(list1, list2, list3)
])
| #include<stdio.h>
#include<stdlib.h>
int main(void) {
int list[3][9], i;
for(i=0;i<27;i++) list[i/9][i%9]=1+i;
for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] );
return 0;
}
|
Translate the given Python code snippet into C without altering its behavior. | list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]
print([
''.join(str(n) for n in z) for z
in zip(list1, list2, list3)
])
| #include<stdio.h>
#include<stdlib.h>
int main(void) {
int list[3][9], i;
for(i=0;i<27;i++) list[i/9][i%9]=1+i;
for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] );
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]
print([
''.join(str(n) for n in z) for z
in zip(list1, list2, list3)
])
| #include<stdio.h>
#include<stdlib.h>
int main(void) {
int list[3][9], i;
for(i=0;i<27;i++) list[i/9][i%9]=1+i;
for(i=0;i<9;i++) printf( "%d%d%d ", list[0][i], list[1][i], list[2][i] );
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. |
from itertools import takewhile
from functools import reduce
def longestCommonSuffix(xs):
def allSame(cs):
h = cs[0]
return all(h == c for c in cs[1:])
def firstCharPrepended(s, cs):
return cs[0] + s
return reduce(
firstCharPrepended,
takewhile(
allSame,
zip(*(reversed(x) for x in xs))
),
''
)
def main():
samples = [
[
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
], [
"Sondag", "Maandag", "Dinsdag", "Woensdag",
"Donderdag", "Vrydag", "Saterdag"
]
]
for xs in samples:
print(
longestCommonSuffix(xs)
)
if __name__ == '__main__':
main()
| #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;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. |
from itertools import takewhile
from functools import reduce
def longestCommonSuffix(xs):
def allSame(cs):
h = cs[0]
return all(h == c for c in cs[1:])
def firstCharPrepended(s, cs):
return cs[0] + s
return reduce(
firstCharPrepended,
takewhile(
allSame,
zip(*(reversed(x) for x in xs))
),
''
)
def main():
samples = [
[
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
], [
"Sondag", "Maandag", "Dinsdag", "Woensdag",
"Donderdag", "Vrydag", "Saterdag"
]
]
for xs in samples:
print(
longestCommonSuffix(xs)
)
if __name__ == '__main__':
main()
| #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;
}
|
Port the provided Python code into C while preserving the original functionality. |
import socket
import thread
import time
HOST = ""
PORT = 4004
def accept(conn):
def threaded():
while True:
conn.send("Please enter your name: ")
try:
name = conn.recv(1024).strip()
except socket.error:
continue
if name in users:
conn.send("Name entered is already in use.\n")
elif name:
conn.setblocking(False)
users[name] = conn
broadcast(name, "+++ %s arrived +++" % name)
break
thread.start_new_thread(threaded, ())
def broadcast(name, message):
print message
for to_name, conn in users.items():
if to_name != name:
try:
conn.send(message + "\n")
except socket.error:
pass
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((HOST, PORT))
server.listen(1)
print "Listening on %s" % ("%s:%s" % server.getsockname())
users = {}
while True:
try:
while True:
try:
conn, addr = server.accept()
except socket.error:
break
accept(conn)
for name, conn in users.items():
try:
message = conn.recv(1024)
except socket.error:
continue
if not message:
del users[name]
broadcast(name, "--- %s leaves ---" % name)
else:
broadcast(name, "%s> %s" % (name, message.strip()))
time.sleep(.1)
except (SystemExit, KeyboardInterrupt):
break
| #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;
}
|
Produce a functionally identical C code for the snippet given in Python. | classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,
str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,
str.isspace, str.istitle)
for stringclass in classes:
chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))
print('\nString class %s has %i characters the first of which are:\n %r'
% (stringclass.__name__, len(chars), chars[:100]))
| #include <stdio.h>
int main(int argc, char const *argv[]) {
for (char c = 0x41; c < 0x5b; c ++) putchar(c);
putchar('\n');
for (char c = 0x61; c < 0x7b; c ++) putchar(c);
putchar('\n');
return 0;
}
|
Change the programming language of this snippet from Python to C without modifying what it does. | from numpy import array, tril, sum
A = [[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
print(sum(tril(A, -1)))
| #include<stdlib.h>
#include<stdio.h>
typedef struct{
int rows,cols;
int** dataSet;
}matrix;
matrix readMatrix(char* dataFile){
FILE* fp = fopen(dataFile,"r");
matrix rosetta;
int i,j;
fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);
rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
for(i=0;i<rosetta.rows;i++){
rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
for(j=0;j<rosetta.cols;j++)
fscanf(fp,"%d",&rosetta.dataSet[i][j]);
}
fclose(fp);
return rosetta;
}
void printMatrix(matrix rosetta){
int i,j;
for(i=0;i<rosetta.rows;i++){
printf("\n");
for(j=0;j<rosetta.cols;j++)
printf("%3d",rosetta.dataSet[i][j]);
}
}
int findSum(matrix rosetta){
int i,j,sum = 0;
for(i=1;i<rosetta.rows;i++){
for(j=0;j<i;j++){
sum += rosetta.dataSet[i][j];
}
}
return sum;
}
int main(int argC,char* argV[])
{
if(argC!=2)
return printf("Usage : %s <filename>",argV[0]);
matrix data = readMatrix(argV[1]);
printf("\n\nMatrix is : \n\n");
printMatrix(data);
printf("\n\nSum below main diagonal : %d",findSum(data));
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. |
import datetime
import re
import urllib.request
import sys
def get(url):
with urllib.request.urlopen(url) as response:
html = response.read().decode('utf-8')
if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html):
return None
return html
def main():
template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'
today = datetime.datetime.utcnow()
back = 10
needle = sys.argv[1]
for i in range(-back, 2):
day = today + datetime.timedelta(days=i)
url = day.strftime(template)
haystack = get(url)
if haystack:
mentions = [x for x in haystack.split('\n') if needle in x]
if mentions:
print('{}\n------\n{}\n------\n'
.format(url, '\n'.join(mentions)))
main()
| #include<curl/curl.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
void searchChatLogs(char* searchString){
char* baseURL = "http:
time_t t;
struct tm* currentDate;
char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];
int i,flag;
FILE *fp;
CURL *curl;
CURLcode res;
time(&t);
currentDate = localtime(&t);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
printf("Today is : %s",dateString);
if((curl = curl_easy_init())!=NULL){
for(i=0;i<=10;i++){
flag = 0;
sprintf(targetURL,"%s%s.tcl",baseURL,dateString);
strcpy(dateStringFile,dateString);
printf("\nRetrieving chat logs from %s\n",targetURL);
if((fp = fopen("nul","w"))==0){
printf("Cant's read from %s",targetURL);
}
else{
curl_easy_setopt(curl, CURLOPT_URL, targetURL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
if(res == CURLE_OK){
while(fgets(lineData,MAX_LEN,fp)!=NULL){
if(strstr(lineData,searchString)!=NULL){
flag = 1;
fputs(lineData,stdout);
}
}
if(flag==0)
printf("\nNo matching lines found.");
}
fflush(fp);
fclose(fp);
}
currentDate->tm_mday--;
mktime(currentDate);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
}
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <followed by search string, enclosed by \" if it contains spaces>",argV[0]);
else
searchChatLogs(argV[1]);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C. |
import requests
URL = "http://rosettacode.org/mw/api.php"
PARAMS = {
"action": "query",
"format": "json",
"formatversion": 2,
"generator": "categorymembers",
"gcmtitle": "Category:Language users",
"gcmlimit": 500,
"prop": "categoryinfo",
}
def fetch_data():
counts = {}
continue_ = {"continue": ""}
while continue_:
resp = requests.get(URL, params={**PARAMS, **continue_})
resp.raise_for_status()
data = resp.json()
counts.update(
{
p["title"]: p.get("categoryinfo", {}).get("size", 0)
for p in data["query"]["pages"]
}
)
continue_ = data.get("continue", {})
return counts
if __name__ == "__main__":
counts = fetch_data()
at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]
top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)
for i, lang in enumerate(top_languages):
print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_rank_languages_by_number_of_users.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. |
import requests
URL = "http://rosettacode.org/mw/api.php"
PARAMS = {
"action": "query",
"format": "json",
"formatversion": 2,
"generator": "categorymembers",
"gcmtitle": "Category:Language users",
"gcmlimit": 500,
"prop": "categoryinfo",
}
def fetch_data():
counts = {}
continue_ = {"continue": ""}
while continue_:
resp = requests.get(URL, params={**PARAMS, **continue_})
resp.raise_for_status()
data = resp.json()
counts.update(
{
p["title"]: p.get("categoryinfo", {}).get("size", 0)
for p in data["query"]["pages"]
}
)
continue_ = data.get("continue", {})
return counts
if __name__ == "__main__":
counts = fetch_data()
at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]
top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)
for i, lang in enumerate(top_languages):
print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
void C_bufferAllocate(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct));
ms->memory = malloc(1);
ms->size = 0;
}
void C_bufferFinalize(void* data) {
struct MemoryStruct *ms = (struct MemoryStruct *)data;
free(ms->memory);
}
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_value(WrenVM* vm) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0);
wrenSetSlotString(vm, 0, ms->memory);
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_perform(curl);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else if (opt < 20000) {
if (opt == CURLOPT_WRITEDATA) {
struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2);
curl_easy_setopt(curl, opt, (void *)ms);
} else if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
}
} else if (opt < 30000) {
if (opt == CURLOPT_WRITEFUNCTION) {
curl_easy_setopt(curl, opt, &WriteMemoryCallback);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
methods.allocate = C_bufferAllocate;
methods.finalize = C_bufferFinalize;
} else if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Buffer") == 0) {
if (!isStatic && strcmp(signature, "value") == 0) return C_value;
} else if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "rc_rank_languages_by_number_of_users.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Python. |
from math import sqrt
from numpy import array
from mpmath import mpf
class AdditionChains:
def __init__(self):
self.chains, self.idx, self.pos = [[1]], 0, 0
self.pat, self.lvl = {1: 0}, [[1]]
def add_chain(self):
newchain = self.chains[self.idx].copy()
newchain.append(self.chains[self.idx][-1] +
self.chains[self.idx][self.pos])
self.chains.append(newchain)
if self.pos == len(self.chains[self.idx])-1:
self.idx += 1
self.pos = 0
else:
self.pos += 1
return newchain
def find_chain(self, nexp):
assert nexp > 0
if nexp == 1:
return [1]
chn = next((a for a in self.chains if a[-1] == nexp), None)
if chn is None:
while True:
chn = self.add_chain()
if chn[-1] == nexp:
break
return chn
def knuth_path(self, ngoal):
if ngoal < 1:
return []
while not ngoal in self.pat:
new_lvl = []
for i in self.lvl[0]:
for j in self.knuth_path(i):
if not i + j in self.pat:
self.pat[i + j] = i
new_lvl.append(i + j)
self.lvl[0] = new_lvl
returnpath = self.knuth_path(self.pat[ngoal])
returnpath.append(ngoal)
return returnpath
def cpow(xbase, chain):
pows, products = 0, {0: 1, 1: xbase}
for i in chain:
products[i] = products[pows] * products[i - pows]
pows = i
return products[chain[-1]]
if __name__ == '__main__':
acs = AdditionChains()
print('First one hundred addition chain lengths:')
for k in range(1, 101):
print(f'{len(acs.find_chain(k))-1:3}', end='\n'if k % 10 == 0 else '')
print('\nKnuth chains for addition chains of 31415 and 27182:')
chns = {m: acs.knuth_path(m) for m in [31415, 27182]}
for (num, cha) in chns.items():
print(f'Exponent: {num:10}\n Addition Chain: {cha[:-1]}')
print('\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415]))
print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182]))
print('1.000025 + 0.000058i)^27182 =',
cpow(complex(1.000025, 0.000058), chns[27182]))
print('1.000022 + 0.000050i)^31415 =',
cpow(complex(1.000022, 0.000050), chns[31415]))
sq05 = mpf(sqrt(0.5))
mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0],
[-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]])
print('matrix A ^ 27182 =')
print(cpow(mat, chns[27182]))
print('matrix A ^ 31415 =')
print(cpow(mat, chns[31415]))
print('(matrix A ** 27182) ** 31415 =')
print(cpow(cpow(mat, chns[27182]), chns[31415]))
| #include <stdio.h>
#include "achain.c"
typedef struct {double u, v;} cplx;
inline cplx c_mul(cplx a, cplx b)
{
cplx c;
c.u = a.u * b.u - a.v * b.v;
c.v = a.u * b.v + a.v * b.u;
return c;
}
cplx chain_expo(cplx x, int n)
{
int i, j, k, l, e[32];
cplx v[32];
l = seq(n, 0, e);
puts("Exponents:");
for (i = 0; i <= l; i++)
printf("%d%c", e[i], i == l ? '\n' : ' ');
v[0] = x; v[1] = c_mul(x, x);
for (i = 2; i <= l; i++) {
for (j = i - 1; j; j--) {
for (k = j; k >= 0; k--) {
if (e[k] + e[j] < e[i]) break;
if (e[k] + e[j] > e[i]) continue;
v[i] = c_mul(v[j], v[k]);
j = 1;
break;
}
}
}
printf("(%f + i%f)^%d = %f + i%f\n",
x.u, x.v, n, v[l].u, v[l].v);
return x;
}
int bin_len(int n)
{
int r, o;
for (r = o = -1; n; n >>= 1, r++)
if (n & 1) o++;
return r + o;
}
int main()
{
cplx r1 = {1.0000254989, 0.0000577896},
r2 = {1.0000220632, 0.0000500026};
int n1 = 27182, n2 = 31415, i;
init();
puts("Precompute chain lengths");
seq_len(n2);
chain_expo(r1, n1);
chain_expo(r2, n2);
puts("\nchain lengths: shortest binary");
printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1));
printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2));
for (i = 1; i < 100; i++)
printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i));
return 0;
}
|
Convert this Python snippet to C and keep its semantics consistent. |
from math import sqrt
from numpy import array
from mpmath import mpf
class AdditionChains:
def __init__(self):
self.chains, self.idx, self.pos = [[1]], 0, 0
self.pat, self.lvl = {1: 0}, [[1]]
def add_chain(self):
newchain = self.chains[self.idx].copy()
newchain.append(self.chains[self.idx][-1] +
self.chains[self.idx][self.pos])
self.chains.append(newchain)
if self.pos == len(self.chains[self.idx])-1:
self.idx += 1
self.pos = 0
else:
self.pos += 1
return newchain
def find_chain(self, nexp):
assert nexp > 0
if nexp == 1:
return [1]
chn = next((a for a in self.chains if a[-1] == nexp), None)
if chn is None:
while True:
chn = self.add_chain()
if chn[-1] == nexp:
break
return chn
def knuth_path(self, ngoal):
if ngoal < 1:
return []
while not ngoal in self.pat:
new_lvl = []
for i in self.lvl[0]:
for j in self.knuth_path(i):
if not i + j in self.pat:
self.pat[i + j] = i
new_lvl.append(i + j)
self.lvl[0] = new_lvl
returnpath = self.knuth_path(self.pat[ngoal])
returnpath.append(ngoal)
return returnpath
def cpow(xbase, chain):
pows, products = 0, {0: 1, 1: xbase}
for i in chain:
products[i] = products[pows] * products[i - pows]
pows = i
return products[chain[-1]]
if __name__ == '__main__':
acs = AdditionChains()
print('First one hundred addition chain lengths:')
for k in range(1, 101):
print(f'{len(acs.find_chain(k))-1:3}', end='\n'if k % 10 == 0 else '')
print('\nKnuth chains for addition chains of 31415 and 27182:')
chns = {m: acs.knuth_path(m) for m in [31415, 27182]}
for (num, cha) in chns.items():
print(f'Exponent: {num:10}\n Addition Chain: {cha[:-1]}')
print('\n1.00002206445416^31415 =', cpow(1.00002206445416, chns[31415]))
print('1.00002550055251^27182 =', cpow(1.00002550055251, chns[27182]))
print('1.000025 + 0.000058i)^27182 =',
cpow(complex(1.000025, 0.000058), chns[27182]))
print('1.000022 + 0.000050i)^31415 =',
cpow(complex(1.000022, 0.000050), chns[31415]))
sq05 = mpf(sqrt(0.5))
mat = array([[sq05, 0, sq05, 0, 0, 0], [0, sq05, 0, sq05, 0, 0], [0, sq05, 0, -sq05, 0, 0],
[-sq05, 0, sq05, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]])
print('matrix A ^ 27182 =')
print(cpow(mat, chns[27182]))
print('matrix A ^ 31415 =')
print(cpow(mat, chns[31415]))
print('(matrix A ** 27182) ** 31415 =')
print(cpow(cpow(mat, chns[27182]), chns[31415]))
| #include <stdio.h>
#include "achain.c"
typedef struct {double u, v;} cplx;
inline cplx c_mul(cplx a, cplx b)
{
cplx c;
c.u = a.u * b.u - a.v * b.v;
c.v = a.u * b.v + a.v * b.u;
return c;
}
cplx chain_expo(cplx x, int n)
{
int i, j, k, l, e[32];
cplx v[32];
l = seq(n, 0, e);
puts("Exponents:");
for (i = 0; i <= l; i++)
printf("%d%c", e[i], i == l ? '\n' : ' ');
v[0] = x; v[1] = c_mul(x, x);
for (i = 2; i <= l; i++) {
for (j = i - 1; j; j--) {
for (k = j; k >= 0; k--) {
if (e[k] + e[j] < e[i]) break;
if (e[k] + e[j] > e[i]) continue;
v[i] = c_mul(v[j], v[k]);
j = 1;
break;
}
}
}
printf("(%f + i%f)^%d = %f + i%f\n",
x.u, x.v, n, v[l].u, v[l].v);
return x;
}
int bin_len(int n)
{
int r, o;
for (r = o = -1; n; n >>= 1, r++)
if (n & 1) o++;
return r + o;
}
int main()
{
cplx r1 = {1.0000254989, 0.0000577896},
r2 = {1.0000220632, 0.0000500026};
int n1 = 27182, n2 = 31415, i;
init();
puts("Precompute chain lengths");
seq_len(n2);
chain_expo(r1, n1);
chain_expo(r2, n2);
puts("\nchain lengths: shortest binary");
printf("%14d %7d %7d\n", n1, seq_len(n1), bin_len(n1));
printf("%14d %7d %7d\n", n2, seq_len(n2), bin_len(n2));
for (i = 1; i < 100; i++)
printf("%14d %7d %7d\n", i, seq_len(i), bin_len(i));
return 0;
}
|
Convert this Python block to C, preserving its control flow and logic. | import sys
if "UTF-8" in sys.stdout.encoding:
print("△")
else:
raise Exception("Terminal can't handle UTF-8")
| #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Unicode is supported on this terminal and U+25B3 is : \u25b3");
i = -1;
break;
}
}
if (i != -1)
printf ("Unicode is not supported on this terminal.");
return 0;
}
|
Port the following code from Python to C with equivalent syntax and logic. | import sys
if "UTF-8" in sys.stdout.encoding:
print("△")
else:
raise Exception("Terminal can't handle UTF-8")
| #include<stdlib.h>
#include<stdio.h>
int
main ()
{
int i;
char *str = getenv ("LANG");
for (i = 0; str[i + 2] != 00; i++)
{
if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
|| (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
{
printf
("Unicode is supported on this terminal and U+25B3 is : \u25b3");
i = -1;
break;
}
}
if (i != -1)
printf ("Unicode is not supported on this terminal.");
return 0;
}
|
Generate an equivalent C version of this Python code. | import math
print("working...")
limit = 1000000
Primes = []
oldPrime = 0
newPrime = 0
x = 0
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(x):
if (x == n*n):
return 1
return 0
for n in range(limit):
if isPrime(n):
Primes.append(n)
for n in range(2,len(Primes)):
pr1 = Primes[n]
pr2 = Primes[n-1]
diff = pr1 - pr2
flag = issquare(diff)
if (flag == 1 and diff > 36):
print(str(pr1) + " " + str(pr2) + " diff = " + str(diff))
print("done...")
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int issquare( int p ) {
int i;
for(i=0;i*i<p;i++);
return i*i==p;
}
int main(void) {
int i=3, j=2;
for(i=3;j<=1000000;i=j) {
j=nextprime(i);
if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
}
return 0;
}
|
Convert this Python snippet to C and keep its semantics consistent. | import math
print("working...")
limit = 1000000
Primes = []
oldPrime = 0
newPrime = 0
x = 0
def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(x):
if (x == n*n):
return 1
return 0
for n in range(limit):
if isPrime(n):
Primes.append(n)
for n in range(2,len(Primes)):
pr1 = Primes[n]
pr2 = Primes[n-1]
diff = pr1 - pr2
flag = issquare(diff)
if (flag == 1 and diff > 36):
print(str(pr1) + " " + str(pr2) + " diff = " + str(diff))
print("done...")
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int issquare( int p ) {
int i;
for(i=0;i*i<p;i++);
return i*i==p;
}
int main(void) {
int i=3, j=2;
for(i=3;j<=1000000;i=j) {
j=nextprime(i);
if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
}
return 0;
}
|
Translate the given Python code snippet into C without altering its behavior. | def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
| #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
|
Write a version of this Python function in C with identical behavior. | def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
| #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
|
Change the following Python code into C without altering its purpose. | def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
| #include <windows.h>
#include <stdio.h>
#include <wchar.h>
void
oops(const wchar_t *message)
{
wchar_t *buf;
DWORD error;
buf = NULL;
error = GetLastError();
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) {
fwprintf(stderr, L"%ls: %ls", message, buf);
LocalFree(buf);
} else {
fwprintf(stderr, L"%ls: unknown error 0x%x\n",
message, error);
}
}
int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
HANDLE fh;
fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE) {
oops(fn);
return 1;
}
if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
SetEndOfFile(fh) == 0) {
oops(fn);
CloseHandle(fh);
return 1;
}
CloseHandle(fh);
return 0;
}
int
main()
{
LARGE_INTEGER fp;
int argc;
wchar_t **argv, *fn, junk[2];
argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argv == NULL) {
oops(L"CommandLineToArgvW");
return 1;
}
if (argc != 3) {
fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
return 1;
}
fn = argv[1];
if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
fwprintf(stderr, L"%ls: not a number\n", argv[2]);
return 1;
}
return dotruncate(fn, fp);
}
|
Convert this Python block to C, preserving its control flow and logic. | import win32api
import win32con
import pywintypes
devmode=pywintypes.DEVMODEType()
devmode.PelsWidth=640
devmode.PelsHeight=480
devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT
win32api.ChangeDisplaySettings(devmode,0)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_xrandr(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 8];
strcpy(command, "xrandr ");
strcat(command, arg);
system(command);
}
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr;
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "video_display_modes.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
|
Generate an equivalent C version of this Python code. | import win32api
import win32con
import pywintypes
devmode=pywintypes.DEVMODEType()
devmode.PelsWidth=640
devmode.PelsHeight=480
devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT
win32api.ChangeDisplaySettings(devmode,0)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"
void C_xrandr(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 8];
strcpy(command, "xrandr ");
strcat(command, arg);
system(command);
}
void C_usleep(WrenVM* vm) {
useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
usleep(usec);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr;
if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "video_display_modes.wren";
char *script = readFile(fileName);
wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}
|
Convert this Python snippet to C and keep its semantics consistent. | def flush_input():
try:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch()
except ImportError:
import sys, termios
termios.tcflush(sys.stdin, termios.TCIOFLUSH)
| #include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char text[256];
getchar();
fseek(stdin, 0, SEEK_END);
fgets(text, sizeof(text), stdin);
puts(text);
return EXIT_SUCCESS;
}
|
Generate a C translation of this Python snippet without changing its computational steps. |
import math
import collections
triple = collections.namedtuple('triple', 'm fm simp')
def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:
m = a + (b - a) / 2
fm = f(m)
simp = abs(b - a) / 6 * (fa + 4*fm + fb)
return triple(m, fm, simp,)
def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:
lt = _quad_simpsons_mem(f, a, fa, m, fm)
rt = _quad_simpsons_mem(f, m, fm, b, fb)
delta = lt.simp + rt.simp - whole
return (lt.simp + rt.simp + delta/15
if (abs(delta) <= eps * 15) else
_quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)
)
def quad_asr(f: callable, a: float, b: float, eps: float)->float:
fa = f(a)
fb = f(b)
t = _quad_simpsons_mem(f, a, fa, b, fb)
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)
def main():
(a, b,) = (0.0, 1.0,)
sinx = quad_asr(math.sin, a, b, 1e-09);
print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx))
main()
| #include <stdio.h>
#include <math.h>
typedef struct { double m; double fm; double simp; } triple;
triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = f(m);
double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);
triple t = {m, fm, simp};
return t;
}
double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {
triple lt = _quad_simpsons_mem(f, a, fa, m, fm);
triple rt = _quad_simpsons_mem(f, m, fm, b, fb);
double delta = lt.simp + rt.simp - whole;
if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;
return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);
}
double quad_asr(double (*f)(double), double a, double b, double eps) {
double fa = f(a);
double fb = f(b);
triple t = _quad_simpsons_mem(f, a, fa, b, fb);
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);
}
int main(){
double a = 0.0, b = 1.0;
double sinx = quad_asr(sin, a, b, 1e-09);
printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx);
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. |
import math
import collections
triple = collections.namedtuple('triple', 'm fm simp')
def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:
m = a + (b - a) / 2
fm = f(m)
simp = abs(b - a) / 6 * (fa + 4*fm + fb)
return triple(m, fm, simp,)
def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:
lt = _quad_simpsons_mem(f, a, fa, m, fm)
rt = _quad_simpsons_mem(f, m, fm, b, fb)
delta = lt.simp + rt.simp - whole
return (lt.simp + rt.simp + delta/15
if (abs(delta) <= eps * 15) else
_quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)
)
def quad_asr(f: callable, a: float, b: float, eps: float)->float:
fa = f(a)
fb = f(b)
t = _quad_simpsons_mem(f, a, fa, b, fb)
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)
def main():
(a, b,) = (0.0, 1.0,)
sinx = quad_asr(math.sin, a, b, 1e-09);
print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx))
main()
| #include <stdio.h>
#include <math.h>
typedef struct { double m; double fm; double simp; } triple;
triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {
double m = (a + b) / 2;
double fm = f(m);
double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);
triple t = {m, fm, simp};
return t;
}
double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {
triple lt = _quad_simpsons_mem(f, a, fa, m, fm);
triple rt = _quad_simpsons_mem(f, m, fm, b, fb);
double delta = lt.simp + rt.simp - whole;
if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;
return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
_quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);
}
double quad_asr(double (*f)(double), double a, double b, double eps) {
double fa = f(a);
double fb = f(b);
triple t = _quad_simpsons_mem(f, a, fa, b, fb);
return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);
}
int main(){
double a = 0.0, b = 1.0;
double sinx = quad_asr(sin, a, b, 1e-09);
printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Python code. | import io
FASTA=
infile = io.StringIO(FASTA)
def fasta_parse(infile):
key = ''
for line in infile:
if line.startswith('>'):
if key:
yield key, val
key, val = line[1:].rstrip().split()[0], ''
elif key:
val += line.rstrip()
if key:
yield key, val
print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
| #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);
}
|
Rewrite the snippet below in C so it works the same as the original Python code. |
from itertools import chain, takewhile
def cousinPrimes():
def go(x):
n = 4 + x
return [(x, n)] if isPrime(n) else []
return chain.from_iterable(
map(go, primes())
)
def main():
pairs = list(
takewhile(
lambda ab: 1000 > ab[1],
cousinPrimes()
)
)
print(f'{len(pairs)} cousin pairs below 1000:\n')
print(
spacedTable(list(
chunksOf(4)([
repr(x) for x in pairs
])
))
)
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
def listTranspose(xss):
def go(xss):
if xss:
h, *t = xss
return (
[[h[0]] + [xs[0] for xs in t if xs]] + (
go([h[1:]] + [xs[1:] for xs in t])
)
) if h and isinstance(h, list) else go(t)
else:
return []
return go(xss)
def spacedTable(rows):
columnWidths = [
len(str(row[-1])) for row in listTranspose(rows)
]
return '\n'.join([
' '.join(
map(
lambda w, s: s.rjust(w, ' '),
columnWidths, row
)
) for row in rows
])
if __name__ == '__main__':
main()
| #include <stdio.h>
#include <string.h>
#define LIMIT 1000
void sieve(int max, char *s) {
int p, k;
memset(s, 0, max);
for (p=2; p*p<=max; p++)
if (!s[p])
for (k=p*p; k<=max; k+=p)
s[k]=1;
}
int main(void) {
char primes[LIMIT+1];
int p, count=0;
sieve(LIMIT, primes);
for (p=2; p<=LIMIT; p++) {
if (!primes[p] && !primes[p+4]) {
count++;
printf("%4d: %4d\n", p, p+4);
}
}
printf("There are %d cousin prime pairs below %d.\n", count, LIMIT);
return 0;
}
|
Convert this Python snippet to C and keep its semantics consistent. |
from itertools import chain, takewhile
def cousinPrimes():
def go(x):
n = 4 + x
return [(x, n)] if isPrime(n) else []
return chain.from_iterable(
map(go, primes())
)
def main():
pairs = list(
takewhile(
lambda ab: 1000 > ab[1],
cousinPrimes()
)
)
print(f'{len(pairs)} cousin pairs below 1000:\n')
print(
spacedTable(list(
chunksOf(4)([
repr(x) for x in pairs
])
))
)
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
def listTranspose(xss):
def go(xss):
if xss:
h, *t = xss
return (
[[h[0]] + [xs[0] for xs in t if xs]] + (
go([h[1:]] + [xs[1:] for xs in t])
)
) if h and isinstance(h, list) else go(t)
else:
return []
return go(xss)
def spacedTable(rows):
columnWidths = [
len(str(row[-1])) for row in listTranspose(rows)
]
return '\n'.join([
' '.join(
map(
lambda w, s: s.rjust(w, ' '),
columnWidths, row
)
) for row in rows
])
if __name__ == '__main__':
main()
| #include <stdio.h>
#include <string.h>
#define LIMIT 1000
void sieve(int max, char *s) {
int p, k;
memset(s, 0, max);
for (p=2; p*p<=max; p++)
if (!s[p])
for (k=p*p; k<=max; k+=p)
s[k]=1;
}
int main(void) {
char primes[LIMIT+1];
int p, count=0;
sieve(LIMIT, primes);
for (p=2; p<=LIMIT; p++) {
if (!primes[p] && !primes[p+4]) {
count++;
printf("%4d: %4d\n", p, p+4);
}
}
printf("There are %d cousin prime pairs below %d.\n", count, LIMIT);
return 0;
}
|
Convert this Python block to C, preserving its control flow and logic. | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
| #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;
}
|
Change the following Python code into C without altering its purpose. | from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
| #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;
}
|
Change the programming language of this snippet from Python to C without modifying what it does. | from sys import stdin
if stdin.isatty():
print("Input comes from tty.")
else:
print("Input doesn't come from tty.")
| #include <unistd.h>
#include <stdio.h>
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
}
|
Write a version of this Python function in C with identical behavior. | from sys import stdin
if stdin.isatty():
print("Input comes from tty.")
else:
print("Input doesn't come from tty.")
| #include <unistd.h>
#include <stdio.h>
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
}
|
Convert this Python block to C, preserving its control flow and logic. | from Xlib import X, display
class Window:
def __init__(self, display, msg):
self.display = display
self.msg = msg
self.screen = self.display.screen()
self.window = self.screen.root.create_window(
10, 10, 100, 100, 1,
self.screen.root_depth,
background_pixel=self.screen.white_pixel,
event_mask=X.ExposureMask | X.KeyPressMask,
)
self.gc = self.window.create_gc(
foreground = self.screen.black_pixel,
background = self.screen.white_pixel,
)
self.window.map()
def loop(self):
while True:
e = self.display.next_event()
if e.type == X.Expose:
self.window.fill_rectangle(self.gc, 20, 20, 10, 10)
self.window.draw_text(self.gc, 10, 50, self.msg)
elif e.type == X.KeyPress:
raise SystemExit
if __name__ == "__main__":
Window(display.Display(), "Hello, World!").loop()
| '--- added a flush to exit cleanly
PRAGMA LDFLAGS `pkg-config --cflags --libs x11`
PRAGMA INCLUDE <X11/Xlib.h>
PRAGMA INCLUDE <X11/Xutil.h>
OPTION PARSE FALSE
'---XLIB is so ugly
ALIAS XNextEvent TO EVENT
ALIAS XOpenDisplay TO DISPLAY
ALIAS DefaultScreen TO SCREEN
ALIAS XCreateSimpleWindow TO CREATE
ALIAS XCloseDisplay TO CLOSE_DISPLAY
ALIAS XSelectInput TO EVENT_TYPE
ALIAS XMapWindow TO MAP_EVENT
ALIAS XFillRectangle TO FILL_RECTANGLE
ALIAS XDrawString TO DRAW_STRING
ALIAS XFlush TO FLUSH
'---pointer to X Display structure
DECLARE d TYPE Display*
'---pointer to the newly created window
'DECLARE w TYPE WINDOW
'---pointer to the XEvent
DECLARE e TYPE XEvent
DECLARE msg TYPE char*
'--- number of screen to place the window on
DECLARE s TYPE int
msg = "Hello, World!"
d = DISPLAY(NULL)
IF d == NULL THEN
EPRINT "Cannot open display" FORMAT "%s%s\n"
END
END IF
s = SCREEN(d)
w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))
EVENT_TYPE(d, w, ExposureMask | KeyPressMask)
MAP_EVENT(d, w)
WHILE (1)
EVENT(d, &e)
IF e.type == Expose THEN
FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)
DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))
END IF
IF e.type == KeyPress THEN
BREAK
END IF
WEND
FLUSH(d)
CLOSE_DISPLAY(d)
|
Maintain the same structure and functionality when rewriting this code in C. | from elementary_cellular_automaton import eca, eca_wrap
def rule30bytes(lencells=100):
cells = '1' + '0' * (lencells - 1)
gen = eca(cells, 30)
while True:
yield int(''.join(next(gen)[0] for i in range(8)), 2)
if __name__ == '__main__':
print([b for i,b in zip(range(10), rule30bytes())])
| #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++)
if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
state |= B(i);
}
printf(" %d", b);
}
putchar('\n');
return;
}
int main(void)
{
evolve(1, 30);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C. | import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
| #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;
}
|
Please provide an equivalent version of this Python code in C. |
states = { 'ready':{
'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
'responses' : ['d','q']},
'waiting':{
'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
'responses' : ['s','r']},
'dispense' : {
'prompt' : 'Machine dispensing: please (r)emove product',
'responses' : ['r']},
'refunding' : {
'prompt' : 'Refunding money',
'responses' : []},
'exit' :{}
}
transitions = { 'ready': {
'd': 'waiting',
'q': 'exit'},
'waiting' : {
's' : 'dispense',
'r' : 'refunding'},
'dispense' : {
'r' : 'ready'},
'refunding' : {
'' : 'ready'}}
def Acceptor(prompt, valids):
if not valids:
print(prompt)
return ''
else:
while True:
resp = input(prompt)[0].lower()
if resp in valids:
return resp
def finite_state_machine(initial_state, exit_state):
response = True
next_state = initial_state
current_state = states[next_state]
while response != exit_state:
response = Acceptor(current_state['prompt'], current_state['responses'])
next_state = transitions[next_state][response]
current_state = states[next_state]
if __name__ == "__main__":
finite_state_machine('ready','q')
| #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State;
typedef struct statechange {
const int in;
const State out;
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State state;
void (*Action)(void);
const statechange table[MAXINPUTS];
} FSM;
char str[10];
void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); }
void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); }
void Refund(void) { fprintf(stderr, "Please collect refund.\n"); }
void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); }
void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); }
void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); }
const FSM fsm[] = {
{ READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }},
{ WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }},
{ REFUND, &Refund, {{ -1, READY} }},
{ DISPENSE, &Dispense, {{ -1, COLLECT} }},
{ COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }},
{ QUIT, &Quit, {{ -1, QUIT} }},
};
int each;
State state = READY;
for (;;) {
fsm[state].Action();
each = 0;
while (!( ((fsm[state].table[each].in == -1)
|| (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++;
state = fsm[state].table[each].out;
}
return 0;
}
|
Port the provided Python code into C while preserving the original functionality. | import turtle
from itertools import cycle
from time import sleep
def rect(t, x, y):
x2, y2 = x/2, y/2
t.setpos(-x2, -y2)
t.pendown()
for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]:
t.goto(pos)
t.penup()
def rects(t, colour, wait_between_rect=0.1):
for x in range(550, 0, -25):
t.color(colour)
rect(t, x, x*.75)
sleep(wait_between_rect)
tl=turtle.Turtle()
screen=turtle.Screen()
screen.setup(620,620)
screen.bgcolor('black')
screen.title('Rosetta Code Vibrating Rectangles')
tl.pensize(3)
tl.speed(0)
tl.penup()
tl.ht()
colours = 'red green blue orange white yellow'.split()
for colour in cycle(colours):
rects(tl, colour)
sleep(0.5)
|
#include<graphics.h>
void vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)
{
int color = 1,i,x = winWidth/2, y = winHeight/2;
while(!kbhit()){
setcolor(color++);
for(i=num;i>0;i--){
rectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);
delay(msec);
}
if(color>MAXCOLORS){
color = 1;
}
}
}
int main()
{
initwindow(1000,1000,"Vibrating Rectangles...");
vibratingRectangles(1000,1000,30,15,20,500);
closegraph();
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. |
def add_least_reduce(lis):
while len(lis) > 1:
lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))
print('Interim list:', lis)
return lis
LIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]
print(LIST, ' ==> ', add_least_reduce(LIST.copy()))
| #include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
int aa = *(const int *)a;
int bb = *(const int *)b;
if (aa < bb) return -1;
if (aa > bb) return 1;
return 0;
}
int main() {
int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};
int isize = sizeof(int);
int asize = sizeof(a) / isize;
int i, sum;
while (asize > 1) {
qsort(a, asize, isize, compare);
printf("Sorted list: ");
for (i = 0; i < asize; ++i) printf("%d ", a[i]);
printf("\n");
sum = a[0] + a[1];
printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum);
for (i = 2; i < asize; ++i) a[i-2] = a[i];
a[asize - 2] = sum;
asize--;
}
printf("Last item is %d.\n", a[0]);
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. | numbers1 = [5,45,23,21,67]
numbers2 = [43,22,78,46,38]
numbers3 = [9,98,12,98,53]
numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]
print(numbers)
| #include <stdio.h>
int min(int a, int b) {
if (a < b) return a;
return b;
}
int main() {
int n;
int numbers1[5] = {5, 45, 23, 21, 67};
int numbers2[5] = {43, 22, 78, 46, 38};
int numbers3[5] = {9, 98, 12, 98, 53};
int numbers[5] = {};
for (n = 0; n < 5; ++n) {
numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);
printf("%d ", numbers[n]);
}
printf("\n");
return 0;
}
|
Translate the given Python code snippet into C without altering its behavior. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
Convert this Python block to C, preserving its control flow and logic. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct fp2 {
int64_t x, y;
};
uint64_t randULong(uint64_t min, uint64_t max) {
uint64_t t = (uint64_t)rand();
return min + t % (max - min);
}
uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) {
uint64_t x = 0, y = a % modulus;
while (b > 0) {
if ((b & 1) == 1) {
x = (x + y) % modulus;
}
y = (y << 1) % modulus;
b = b >> 1;
}
return x;
}
uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) {
uint64_t x = 1;
while (power > 0) {
if ((power & 1) == 1) {
x = mul_mod(x, b, modulus);
}
b = mul_mod(b, b, modulus);
power = power >> 1;
}
return x;
}
bool isPrime(uint64_t n, int64_t k) {
uint64_t a, x, n_one = n - 1, d = n_one;
uint32_t s = 0;
uint32_t r;
if (n < 2) {
return false;
}
if (n > 9223372036854775808ull) {
printf("The number is too big, program will end.\n");
exit(1);
}
if ((n % 2) == 0) {
return n == 2;
}
while ((d & 1) == 0) {
d = d >> 1;
s = s + 1;
}
while (k > 0) {
k = k - 1;
a = randULong(2, n);
x = pow_mod(a, d, n);
if (x == 1 || x == n_one) {
continue;
}
for (r = 1; r < s; r++) {
x = pow_mod(x, 2, n);
if (x == 1) return false;
if (x == n_one) goto continue_while;
}
if (x != n_one) {
return false;
}
continue_while: {}
}
return true;
}
int64_t legendre_symbol(int64_t a, int64_t p) {
int64_t x = pow_mod(a, (p - 1) / 2, p);
if ((p - 1) == x) {
return x - p;
} else {
return x;
}
}
struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) {
struct fp2 answer;
uint64_t tmp1, tmp2;
tmp1 = mul_mod(a.x, b.x, p);
tmp2 = mul_mod(a.y, b.y, p);
tmp2 = mul_mod(tmp2, w2, p);
answer.x = (tmp1 + tmp2) % p;
tmp1 = mul_mod(a.x, b.y, p);
tmp2 = mul_mod(a.y, b.x, p);
answer.y = (tmp1 + tmp2) % p;
return answer;
}
struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) {
return fp2mul(a, a, p, w2);
}
struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) {
struct fp2 ret;
if (n == 0) {
ret.x = 1;
ret.y = 0;
return ret;
}
if (n == 1) {
return a;
}
if ((n & 1) == 0) {
return fp2square(fp2pow(a, n / 2, p, w2), p, w2);
} else {
return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2);
}
}
void test(int64_t n, int64_t p) {
int64_t a, w2;
int64_t x1, x2;
struct fp2 answer;
printf("Find solution for n = %lld and p = %lld\n", n, p);
if (p == 2 || !isPrime(p, 15)) {
printf("No solution, p is not an odd prime.\n\n");
return;
}
if (legendre_symbol(n, p) != 1) {
printf(" %lld is not a square in F%lld\n\n", n, p);
return;
}
while (true) {
do {
a = randULong(2, p);
w2 = a * a - n;
} while (legendre_symbol(w2, p) != -1);
answer.x = a;
answer.y = 1;
answer = fp2pow(answer, (p + 1) / 2, p, w2);
if (answer.y != 0) {
continue;
}
x1 = answer.x;
x2 = p - x1;
if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) {
printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2);
return;
}
}
}
int main() {
srand((size_t)time(0));
test(10, 13);
test(56, 101);
test(8218, 10007);
test(8219, 10007);
test(331575, 1000003);
test(665165880, 1000000007);
return 0;
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005
class PCG32():
def __init__(self, seed_state=None, seed_sequence=None):
if all(type(x) == int for x in (seed_state, seed_sequence)):
self.seed(seed_state, seed_sequence)
else:
self.state = self.inc = 0
def seed(self, seed_state, seed_sequence):
self.state = 0
self.inc = ((seed_sequence << 1) | 1) & mask64
self.next_int()
self.state = (self.state + seed_state)
self.next_int()
def next_int(self):
"return random 32 bit unsigned int"
old = self.state
self.state = ((old * CONST) + self.inc) & mask64
xorshifted = (((old >> 18) ^ old) >> 27) & mask32
rot = (old >> 59) & mask32
answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
answer = answer &mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = PCG32()
random_gen.seed(42, 54)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321, 1)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist)
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
const uint64_t N = 6364136223846793005;
static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;
uint32_t pcg32_int() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double pcg32_float() {
return ((double)pcg32_int()) / (1LL << 32);
}
void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
pcg32_int();
state = state + seed_state;
pcg32_int();
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
pcg32_seed(42, 54);
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("\n");
pcg32_seed(987654321, 1);
for (i = 0; i < 100000; i++) {
int j = (int)floor(pcg32_float() * 5.0);
counts[j]++;
}
printf("The counts for 100,000 repetitions are:\n");
for (i = 0; i < 5; i++) {
printf(" %d : %d\n", i, counts[i]);
}
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | def ToReducedRowEchelonForm( M ):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
lead += 1
if columnCount == lead:
return
M[i],M[r] = M[r],M[i]
lv = M[r][lead]
M[r] = [ mrx / lv for mrx in M[r]]
for i in range(rowCount):
if i != r:
lv = M[i][lead]
M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
lead += 1
return M
def pmtx(mtx):
print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx))
def convolve(f, h):
g = [0] * (len(f) + len(h) - 1)
for hindex, hval in enumerate(h):
for findex, fval in enumerate(f):
g[hindex + findex] += fval * hval
return g
def deconvolve(g, f):
lenh = len(g) - len(f) + 1
mtx = [[0 for x in range(lenh+1)] for y in g]
for hindex in range(lenh):
for findex, fval in enumerate(f):
gindex = hindex + findex
mtx[gindex][hindex] = fval
for gindex, gval in enumerate(g):
mtx[gindex][lenh] = gval
ToReducedRowEchelonForm( mtx )
return [mtx[i][lenh] for i in range(lenh)]
if __name__ == '__main__':
h = [-8,-9,-3,-1,-6,7]
f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]
g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]
assert convolve(f,h) == g
assert deconvolve(g, f) == h
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
double PI;
typedef double complex cplx;
void _fft(cplx buf[], cplx out[], int n, int step)
{
if (step < n) {
_fft(out, buf, n, step * 2);
_fft(out + step, buf + step, n, step * 2);
for (int i = 0; i < n; i += 2 * step) {
cplx t = cexp(-I * PI * i / n) * out[i + step];
buf[i / 2] = out[i] + t;
buf[(i + n)/2] = out[i] - t;
}
}
}
void fft(cplx buf[], int n)
{
cplx out[n];
for (int i = 0; i < n; i++) out[i] = buf[i];
_fft(buf, out, n, 1);
}
cplx *pad_two(double g[], int len, int *ns)
{
int n = 1;
if (*ns) n = *ns;
else while (n < len) n *= 2;
cplx *buf = calloc(sizeof(cplx), n);
for (int i = 0; i < len; i++) buf[i] = g[i];
*ns = n;
return buf;
}
void deconv(double g[], int lg, double f[], int lf, double out[]) {
int ns = 0;
cplx *g2 = pad_two(g, lg, &ns);
cplx *f2 = pad_two(f, lf, &ns);
fft(g2, ns);
fft(f2, ns);
cplx h[ns];
for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i];
fft(h, ns);
for (int i = 0; i >= lf - lg; i--)
out[-i] = h[(i + ns) % ns]/32;
free(g2);
free(f2);
}
int main()
{
PI = atan2(1,1) * 4;
double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7};
double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 };
double h[] = { -8,-9,-3,-1,-6,7 };
int lg = sizeof(g)/sizeof(double);
int lf = sizeof(f)/sizeof(double);
int lh = sizeof(h)/sizeof(double);
double h2[lh];
double f2[lf];
printf("f[] data is : ");
for (int i = 0; i < lf; i++) printf(" %g", f[i]);
printf("\n");
printf("deconv(g, h): ");
deconv(g, lg, h, lh, f2);
for (int i = 0; i < lf; i++) printf(" %g", f2[i]);
printf("\n");
printf("h[] data is : ");
for (int i = 0; i < lh; i++) printf(" %g", h[i]);
printf("\n");
printf("deconv(g, f): ");
deconv(g, lg, f, lf, h2);
for (int i = 0; i < lh; i++) printf(" %g", h2[i]);
printf("\n");
}
|
Produce a functionally identical C code for the snippet given in Python. |
from PIL import Image
im = Image.open("boxes_1.ppm")
im.save("boxes_1.jpg")
|
void print_jpg(image img, int qual);
|
Please provide an equivalent version of this Python code in C. |
import binascii
import functools
import hashlib
digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def b58(n):
return b58(n//58) + digits58[n%58:n%58+1] if n else b''
def public_point_to_address(x, y):
c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)
r = hashlib.new('ripemd160')
r.update(hashlib.sha256(c).digest())
c = b'\x00' + r.digest()
d = hashlib.sha256(hashlib.sha256(c).digest()).digest()
return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))
if __name__ == '__main__':
print(public_point_to_address(
b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',
b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))
| #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
|
Convert this Python block to C, preserving its control flow and logic. |
import binascii
import functools
import hashlib
digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def b58(n):
return b58(n//58) + digits58[n%58:n%58+1] if n else b''
def public_point_to_address(x, y):
c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)
r = hashlib.new('ripemd160')
r.update(hashlib.sha256(c).digest())
c = b'\x00' + r.digest()
d = hashlib.sha256(hashlib.sha256(c).digest()).digest()
return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))
if __name__ == '__main__':
print(public_point_to_address(
b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',
b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))
| #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#define COIN_VER 0
const char *coin_err;
typedef unsigned char byte;
int is_hex(const char *s) {
int i;
for (i = 0; i < 64; i++)
if (!isxdigit(s[i])) return 0;
return 1;
}
void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
char* base58(byte *s, char *out) {
static const char *tmpl = "123456789"
"ABCDEFGHJKLMNPQRSTUVWXYZ"
"abcdefghijkmnopqrstuvwxyz";
static char buf[40];
int c, i, n;
if (!out) out = buf;
out[n = 34] = 0;
while (n--) {
for (c = i = 0; i < 25; i++) {
c = c * 256 + s[i];
s[i] = c / 58;
c %= 58;
}
out[n] = tmpl[c];
}
for (n = 0; out[n] == '1'; n++);
memmove(out, out + n, 34 - n);
return out;
}
char *coin_encode(const char *x, const char *y, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
if (!is_hex(x) || !(is_hex(y))) {
coin_err = "bad public point string";
return 0;
}
s[0] = 4;
str_to_byte(x, s + 1, 32);
str_to_byte(y, s + 33, 32);
rmd[0] = COIN_VER;
RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);
memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);
return base58(rmd, out);
}
int main(void) {
puts(coin_encode(
"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
0));
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | import re
_vowels = 'AEIOU'
def replace_at(text, position, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text[position:].startswith(f):
return ''.join([text[:position],
t,
text[position+len(f):]])
return text
def replace_end(text, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text.endswith(f):
return text[:-len(f)] + t
return text
def nysiis(name):
name = re.sub(r'\W', '', name).upper()
name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],
['MCC', 'N', 'C', 'FF', 'FF', 'SSS'])
name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],
['Y', 'Y', 'D', 'D', 'D', 'D', 'D'])
key, key1 = name[0], ''
i = 1
while i < len(name):
n_1, n = name[i-1], name[i]
n1_ = name[i+1] if i+1 < len(name) else ''
name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)
name = replace_at(name, i, 'QZM', 'GSN')
name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])
name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])
if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):
name = ''.join([name[:i], n_1, name[i+1:]])
if n == 'W' and n_1 in _vowels:
name = ''.join([name[:i], 'A', name[i+1:]])
if key and key[-1] != name[i]:
key += name[i]
i += 1
key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])
return key1 + key
if __name__ == '__main__':
names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',
'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',
'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',
'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',
"O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins',
'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',
'knight', 'mitchell', "o'daniel"]
for name in names:
print('%15s: %s' % (name, nysiis(name)))
| #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
|
Change the following Python code into C without altering its purpose. | import re
_vowels = 'AEIOU'
def replace_at(text, position, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text[position:].startswith(f):
return ''.join([text[:position],
t,
text[position+len(f):]])
return text
def replace_end(text, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text.endswith(f):
return text[:-len(f)] + t
return text
def nysiis(name):
name = re.sub(r'\W', '', name).upper()
name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'],
['MCC', 'N', 'C', 'FF', 'FF', 'SSS'])
name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'],
['Y', 'Y', 'D', 'D', 'D', 'D', 'D'])
key, key1 = name[0], ''
i = 1
while i < len(name):
n_1, n = name[i-1], name[i]
n1_ = name[i+1] if i+1 < len(name) else ''
name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5)
name = replace_at(name, i, 'QZM', 'GSN')
name = replace_at(name, i, ['KN', 'K'], ['N', 'C'])
name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF'])
if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels):
name = ''.join([name[:i], n_1, name[i+1:]])
if n == 'W' and n_1 in _vowels:
name = ''.join([name[:i], 'A', name[i+1:]])
if key and key[-1] != name[i]:
key += name[i]
i += 1
key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', ''])
return key1 + key
if __name__ == '__main__':
names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin',
'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence',
'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews',
'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison',
"O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins',
'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV',
'knight', 'mitchell', "o'daniel"]
for name in names:
print('%15s: %s' % (name, nysiis(name)))
| #include <iostream>
#include <iomanip>
#include <string>
std::string NYSIIS( std::string const& str )
{
std::string s, out;
s.reserve( str.length() );
for( auto const c : str )
{
if( c >= 'a' && c <= 'z' )
s += c - ('a' - 'A');
else if( c >= 'A' && c <= 'Z' )
s += c;
}
auto replace = []( char const * const from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( from );
if( strncmp( from, dst, n ) == 0 )
{
strncpy( dst, to, n );
return true;
}
return false;
};
auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool
{
auto const n = strlen( *from );
for( ; *from; ++from )
if( strncmp( *from, dst, n ) == 0 )
{
memcpy( dst, to, n );
return true;
}
return false;
};
auto isVowel = []( char const c ) -> bool
{
return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
};
size_t n = s.length();
replace( "MAC", "MCC", &s[0] );
replace( "KN", "NN", &s[0] );
replace( "K", "C", &s[0] );
char const* const prefix[] = { "PH", "PF", 0 };
multiReplace( prefix, "FF", &s[0] );
replace( "SCH", "SSS", &s[0] );
char const* const suffix1[] = { "EE", "IE", 0 };
char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 };
if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] ))
{
s.pop_back();
--n;
}
out += s[0];
char* vowels[] = { "A", "E", "I", "O", "U", 0 };
for( unsigned i = 1; i < n; ++i )
{
char* const c = &s[i];
if( !replace( "EV", "AV", c ) )
multiReplace( vowels, "A", c );
replace( "Q", "G", c );
replace( "Z", "S", c );
replace( "M", "N", c );
if( !replace( "KN", "NN", c ))
replace( "K", "C", c );
replace( "SCH", "SSS", c );
replace( "PH", "FF", c );
if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] )))
*c = s[i - 1];
if( *c == 'W' && isVowel( s[i - 1] ))
*c = 'A';
if( out.back() != *c )
out += *c;
}
if( out.back() == 'S' || out.back() == 'A' )
out.pop_back();
n = out.length() - 2;
if( out[n] == 'A' && out[n + 1] == 'Y' )
out = out.substr( 0, n ) + "Y";
return out;
}
int main()
{
static char const * const names[][2] = {
{ "Bishop", "BASAP" },
{ "Carlson", "CARLSAN" },
{ "Carr", "CAR" },
{ "Chapman", "CAPNAN" },
{ "Franklin", "FRANCLAN" },
{ "Greene", "GRAN" },
{ "Harper", "HARPAR" },
{ "Jacobs", "JACAB" },
{ "Larson", "LARSAN" },
{ "Lawrence", "LARANC" },
{ "Lawson", "LASAN" },
{ "Louis, XVI", "LASXV" },
{ "Lynch", "LYNC" },
{ "Mackenzie", "MCANSY" },
{ "Matthews", "MATA" },
{ "McCormack", "MCARNAC" },
{ "McDaniel", "MCDANAL" },
{ "McDonald", "MCDANALD" },
{ "Mclaughlin", "MCLAGLAN" },
{ "Morrison", "MARASAN" },
{ "O'Banion", "OBANAN" },
{ "O'Brien", "OBRAN" },
{ "Richards", "RACARD" },
{ "Silva", "SALV" },
{ "Watkins", "WATCAN" },
{ "Wheeler", "WALAR" },
{ "Willis", "WALA" },
{ "brown, sr", "BRANSR" },
{ "browne, III", "BRAN" },
{ "browne, IV", "BRANAV" },
{ "knight", "NAGT" },
{ "mitchell", "MATCAL" },
{ "o'daniel", "ODANAL" } };
for( auto const& name : names )
{
auto const code = NYSIIS( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code;
if( code == std::string( name[1] ))
std::cout << " ok";
else
std::cout << " ERROR: " << name[1] << " expected";
std::cout << std::endl;
}
return 0;
}
|
Write a version of this Python function in C with identical behavior. |
def isDisarium(n):
digitos = len(str(n))
suma = 0
x = n
while x != 0:
suma += (x % 10) ** digitos
digitos -= 1
x //= 10
if suma == n:
return True
else:
return False
if __name__ == '__main__':
limite = 19
cont = 0
n = 0
print("The first",limite,"Disarium numbers are:")
while cont < limite:
if isDisarium(n):
print(n, end = " ")
cont += 1
n += 1
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
|
Convert this Python snippet to C and keep its semantics consistent. |
def isDisarium(n):
digitos = len(str(n))
suma = 0
x = n
while x != 0:
suma += (x % 10) ** digitos
digitos -= 1
x //= 10
if suma == n:
return True
else:
return False
if __name__ == '__main__':
limite = 19
cont = 0
n = 0
print("The first",limite,"Disarium numbers are:")
while cont < limite:
if isDisarium(n):
print(n, end = " ")
cont += 1
n += 1
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int power (int base, int exponent) {
int result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
int is_disarium (int num) {
int n = num;
int sum = 0;
int len = n <= 9 ? 1 : floor(log10(n)) + 1;
while (n > 0) {
sum += power(n % 10, len);
n /= 10;
len--;
}
return num == sum;
}
int main() {
int count = 0;
int i = 0;
while (count < 19) {
if (is_disarium(i)) {
printf("%d ", i);
count++;
}
i++;
}
printf("%s\n", "\n");
}
|
Translate this program into C but keep the logic exactly as in Python. | from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i in range(5):
t.forward(s)
t.right(72)
t.end_fill()
def sierpinski(i, t, s):
t.setheading(0)
new_size = s * side_ratio
if i > 1:
i -= 1
for j in range(4):
t.right(36)
short = s * side_ratio / part_ratio
dist = [short, s, s, short][j]
spawn = Turtle()
if hide_turtles:spawn.hideturtle()
spawn.penup()
spawn.setposition(t.position())
spawn.setheading(t.heading())
spawn.forward(dist)
sierpinski(i, spawn, new_size)
sierpinski(i, t, new_size)
else:
pentagon(t, s)
del t
def main():
t = Turtle()
t.hideturtle()
t.penup()
screen = t.getscreen()
y = screen.window_height()
t.goto(0, y/2-20)
i = 5
size = 300
size *= part_ratio
sierpinski(i, t, size)
main()
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
initwindow(windowSide,windowSide,"Polygon Chaos");
vertices = (double**)malloc(numSides*sizeof(double*));
for(i=0;i<numSides;i++){
vertices[i] = (double*)malloc(2 * sizeof(double));
vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
sumX+= vertices[i][0];
sumY+= vertices[i][1];
putpixel(vertices[i][0],vertices[i][1],15);
}
srand((unsigned)time(&t));
seedX = sumX/numSides;
seedY = sumY/numSides;
putpixel(seedX,seedY,15);
for(i=0;i<iter;i++){
choice = rand()%numSides;
seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
putpixel(seedX,seedY,15);
}
free(vertices);
getch();
closegraph();
return 0;
}
|
Can you help me rewrite this code in C instead of Python, keeping it the same logically? | from PIL import Image
image = Image.open("lena.jpg")
width, height = image.size
amount = width * height
total = 0
bw_image = Image.new('L', (width, height), 0)
bm_image = Image.new('1', (width, height), 0)
for h in range(0, height):
for w in range(0, width):
r, g, b = image.getpixel((w, h))
greyscale = int((r + g + b) / 3)
total += greyscale
bw_image.putpixel((w, h), gray_scale)
avg = total / amount
black = 0
white = 1
for h in range(0, height):
for w in range(0, width):
v = bw_image.getpixel((w, h))
if v >= avg:
bm_image.putpixel((w, h), white)
else:
bm_image.putpixel((w, h), black)
bw_image.show()
bm_image.show()
| typedef unsigned int histogram_t;
typedef histogram_t *histogram;
#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )
histogram get_histogram(grayimage im);
luminance histogram_median(histogram h);
|
Ensure the translated C code behaves exactly like the original Python snippet. | def pad_like(max_n=8, t=15):
start = [[], [1, 1, 1]]
for n in range(2, max_n+1):
this = start[n-1][:n+1]
while len(this) < t:
this.append(sum(this[i] for i in range(-2, -n - 2, -1)))
start.append(this)
return start[2:]
def pr(p):
print(.strip())
for n, seq in enumerate(p, 2):
print(f"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\n|-")
print('|}')
if __name__ == '__main__':
p = pad_like()
pr(p)
| #include <stdio.h>
void padovanN(int n, size_t t, int *p) {
int i, j;
if (n < 2 || t < 3) {
for (i = 0; i < t; ++i) p[i] = 1;
return;
}
padovanN(n-1, t, p);
for (i = n + 1; i < t; ++i) {
p[i] = 0;
for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
}
}
int main() {
int n, i;
const size_t t = 15;
int p[t];
printf("First %ld terms of the Padovan n-step number sequences:\n", t);
for (n = 2; n <= 8; ++n) {
for (i = 0; i < t; ++i) p[i] = 0;
padovanN(n, t, p);
printf("%d: ", n);
for (i = 0; i < t; ++i) printf("%3d ", p[i]);
printf("\n");
}
return 0;
}
|
Generate an equivalent C version of this Python code. | import threading
from time import sleep
res = 2
sema = threading.Semaphore(res)
class res_thread(threading.Thread):
def run(self):
global res
n = self.getName()
for i in range(1, 4):
sema.acquire()
res = res - 1
print n, "+ res count", res
sleep(2)
res = res + 1
print n, "- res count", res
sema.release()
for i in range(1, 5):
t = res_thread()
t.start()
| HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
|
Rewrite this program in C while keeping its functionality equivalent to the Python version. |
import time
def main(bpm = 72, bpb = 4):
sleep = 60.0 / bpm
counter = 0
while True:
counter += 1
if counter % bpb:
print 'tick'
else:
print 'TICK'
time.sleep(sleep)
main()
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
struct timeval start, last;
inline int64_t tv_to_u(struct timeval s)
{
return s.tv_sec * 1000000 + s.tv_usec;
}
inline struct timeval u_to_tv(int64_t x)
{
struct timeval s;
s.tv_sec = x / 1000000;
s.tv_usec = x % 1000000;
return s;
}
void draw(int dir, int64_t period, int64_t cur, int64_t next)
{
int len = 40 * (next - cur) / period;
int s, i;
if (len > 20) len = 40 - len;
s = 20 + (dir ? len : -len);
printf("\033[H");
for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');
}
void beat(int delay)
{
struct timeval tv = start;
int dir = 0;
int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;
int64_t draw_interval = 20000;
printf("\033[H\033[J");
while (1) {
gettimeofday(&tv, 0);
slp = next - tv_to_u(tv) - corr;
usleep(slp);
gettimeofday(&tv, 0);
putchar(7);
fflush(stdout);
printf("\033[5;1Hdrift: %d compensate: %d (usec) ",
(int)d, (int)corr);
dir = !dir;
cur = tv_to_u(tv);
d = cur - next;
corr = (corr + d) / 2;
next += delay;
while (cur + d + draw_interval < next) {
usleep(draw_interval);
gettimeofday(&tv, 0);
cur = tv_to_u(tv);
draw(dir, delay, cur, next);
fflush(stdout);
}
}
}
int main(int c, char**v)
{
int bpm;
if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;
if (bpm > 600) {
fprintf(stderr, "frequency %d too high\n", bpm);
exit(1);
}
gettimeofday(&start, 0);
last = start;
beat(60 * 1000000 / bpm);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Python version. |
import sys
print " ".join(sys.argv[1:])
| #!/usr/local/bin/script_gcc.sh
#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef char *STRING;
typedef enum{FALSE=0, TRUE=1} BOOL;
const STRING ENDCAT = NULL;
#define DIALECT "c"
const STRING
CC="gcc",
COPTS="-lm -x "DIALECT,
IEXT="."DIALECT,
OEXT=".out";
const BOOL OPT_CACHE = TRUE;
char strcat_out[BUFSIZ];
STRING STRCAT(STRING argv, ... ){
va_list ap;
va_start(ap, argv);
STRING arg;
strcat_out[0]='\0';
for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){
strncat(strcat_out, arg, sizeof strcat_out);
}
va_end(ap);
return strndup(strcat_out, sizeof strcat_out);
}
char itoa_out[BUFSIZ];
STRING itoa_(int i){
sprintf(itoa_out, "%d", i);
return itoa_out;
}
time_t modtime(STRING filename){
struct stat buf;
if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);
return buf.st_mtime;
}
BOOL compile(STRING srcpath, STRING binpath){
int out;
STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT);
FILE *src=fopen(srcpath, "r"),
*compiler=popen(compiler_command, "w");
char buf[BUFSIZ];
BOOL shebang;
for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)
if(!shebang)fwrite(buf, strlen(buf), 1, compiler);
out=pclose(compiler);
return out;
}
void main(int argc, STRING *argv, STRING *envp){
STRING binpath,
srcpath=argv[1],
argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),
*dirnamew, *dirnamex;
argv++;
STRING paths[] = {
dirname(strdup(srcpath)),
STRCAT(getenv("HOME"), "/bin", ENDCAT),
"/usr/local/bin",
".",
STRCAT(getenv("HOME"), "/tmp", ENDCAT),
getenv("HOME"),
STRCAT(getenv("HOME"), "/Desktop", ENDCAT),
ENDCAT
};
for(dirnamew = paths; *dirnamew; dirnamew++){
if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;
}
if(OPT_CACHE == FALSE){
binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS){
if(fork()){
sleep(0.1); unlink(binpath);
} else {
execvp(binpath, argv);
}
}
} else {
time_t modtime_srcpath = modtime(srcpath);
for(dirnamex = paths; *dirnamex; dirnamex++){
binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT);
if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))
execvp(binpath, argv);
}
}
binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS)
execvp(binpath, argv);
perror(STRCAT(binpath, ": executable not available", ENDCAT));
exit(errno);
}
|
Maintain the same structure and functionality when rewriting this code in C. |
import sys
print " ".join(sys.argv[1:])
| #!/usr/local/bin/script_gcc.sh
#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
typedef char *STRING;
typedef enum{FALSE=0, TRUE=1} BOOL;
const STRING ENDCAT = NULL;
#define DIALECT "c"
const STRING
CC="gcc",
COPTS="-lm -x "DIALECT,
IEXT="."DIALECT,
OEXT=".out";
const BOOL OPT_CACHE = TRUE;
char strcat_out[BUFSIZ];
STRING STRCAT(STRING argv, ... ){
va_list ap;
va_start(ap, argv);
STRING arg;
strcat_out[0]='\0';
for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){
strncat(strcat_out, arg, sizeof strcat_out);
}
va_end(ap);
return strndup(strcat_out, sizeof strcat_out);
}
char itoa_out[BUFSIZ];
STRING itoa_(int i){
sprintf(itoa_out, "%d", i);
return itoa_out;
}
time_t modtime(STRING filename){
struct stat buf;
if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);
return buf.st_mtime;
}
BOOL compile(STRING srcpath, STRING binpath){
int out;
STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT);
FILE *src=fopen(srcpath, "r"),
*compiler=popen(compiler_command, "w");
char buf[BUFSIZ];
BOOL shebang;
for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)
if(!shebang)fwrite(buf, strlen(buf), 1, compiler);
out=pclose(compiler);
return out;
}
void main(int argc, STRING *argv, STRING *envp){
STRING binpath,
srcpath=argv[1],
argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),
*dirnamew, *dirnamex;
argv++;
STRING paths[] = {
dirname(strdup(srcpath)),
STRCAT(getenv("HOME"), "/bin", ENDCAT),
"/usr/local/bin",
".",
STRCAT(getenv("HOME"), "/tmp", ENDCAT),
getenv("HOME"),
STRCAT(getenv("HOME"), "/Desktop", ENDCAT),
ENDCAT
};
for(dirnamew = paths; *dirnamew; dirnamew++){
if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;
}
if(OPT_CACHE == FALSE){
binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS){
if(fork()){
sleep(0.1); unlink(binpath);
} else {
execvp(binpath, argv);
}
}
} else {
time_t modtime_srcpath = modtime(srcpath);
for(dirnamex = paths; *dirnamex; dirnamex++){
binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT);
if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))
execvp(binpath, argv);
}
}
binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT);
if(compile(srcpath, binpath) == EXIT_SUCCESS)
execvp(binpath, argv);
perror(STRCAT(binpath, ": executable not available", ENDCAT));
exit(errno);
}
|
Generate an equivalent C version of this Python code. | from itertools import count, islice, takewhile
from math import gcd
def EKG_gen(start=2):
c = count(start + 1)
last, so_far = start, list(range(2, start))
yield 1, []
yield last, []
while True:
for index, sf in enumerate(so_far):
if gcd(last, sf) > 1:
last = so_far.pop(index)
yield last, so_far[::]
break
else:
so_far.append(next(c))
def find_convergence(ekgs=(5,7)):
"Returns the convergence point or zero if not found within the limit"
ekg = [EKG_gen(n) for n in ekgs]
for e in ekg:
next(e)
return 2 + len(list(takewhile(lambda state: not all(state[0] == s for s in state[1:]),
zip(*ekg))))
if __name__ == '__main__':
for start in 2, 5, 7, 9, 10:
print(f"EKG({start}):", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])
print(f"\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!")
| #include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define LIMIT 100
typedef int bool;
int compareInts(const void *a, const void *b) {
int aa = *(int *)a;
int bb = *(int *)b;
return aa - bb;
}
bool contains(int a[], int b, size_t len) {
int i;
for (i = 0; i < len; ++i) {
if (a[i] == b) return TRUE;
}
return FALSE;
}
int gcd(int a, int b) {
while (a != b) {
if (a > b)
a -= b;
else
b -= a;
}
return a;
}
bool areSame(int s[], int t[], size_t len) {
int i;
qsort(s, len, sizeof(int), compareInts);
qsort(t, len, sizeof(int), compareInts);
for (i = 0; i < len; ++i) {
if (s[i] != t[i]) return FALSE;
}
return TRUE;
}
int main() {
int s, n, i;
int starts[5] = {2, 5, 7, 9, 10};
int ekg[5][LIMIT];
for (s = 0; s < 5; ++s) {
ekg[s][0] = 1;
ekg[s][1] = starts[s];
for (n = 2; n < LIMIT; ++n) {
for (i = 2; ; ++i) {
if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {
ekg[s][n] = i;
break;
}
}
}
printf("EKG(%2d): [", starts[s]);
for (i = 0; i < 30; ++i) printf("%d ", ekg[s][i]);
printf("\b]\n");
}
for (i = 2; i < LIMIT; ++i) {
if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {
printf("\nEKG(5) and EKG(7) converge at term %d\n", i + 1);
return 0;
}
}
printf("\nEKG5(5) and EKG(7) do not converge within %d terms\n", LIMIT);
return 0;
}
|
Change the programming language of this snippet from Python to C without modifying what it does. | def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr =
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of %i i.e. %s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
| #include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1" };
size_t strslen = sizeof(strs) / sizeof(strs[0]);
size_t i;
for (i = 0; i < strslen; ++i) {
int n = repstr(strs[i]);
if (n)
printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
else
printf("\"%s\" = not a rep-string\n", strs[i]);
}
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. |
import time
print "\033[?1049h\033[H"
print "Alternate buffer!"
for i in xrange(5, 0, -1):
print "Going back in:", i
time.sleep(1)
print "\033[?1049l"
| #include <stdio.h>
#include <unistd.h>
int main()
{
int i;
printf("\033[?1049h\033[H");
printf("Alternate screen buffer\n");
for (i = 5; i; i--) {
printf("\rgoing back in %d...", i);
fflush(stdout);
sleep(1);
}
printf("\033[?1049l");
return 0;
}
|
Write the same code in C as shown below in Python. | 'c' == "c"
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
| char ch = 'z';
|
Convert the following code from Python to C, ensuring the logic remains intact. | from collections import defaultdict, Counter
def getwords(minlength=11, fname='unixdict.txt'):
"Return set of lowercased words of > given number of characters"
with open(fname) as f:
words = f.read().strip().lower().split()
return {w for w in words if len(w) > minlength}
words11 = getwords()
word_minus_1 = defaultdict(list)
minus_1_to_word = defaultdict(list)
for w in words11:
for i in range(len(w)):
minus_1 = w[:i] + w[i+1:]
word_minus_1[minus_1].append((w, i))
if minus_1 in words11:
minus_1_to_word[minus_1].append(w)
cwords = set()
for _, v in word_minus_1.items():
if len(v) >1:
change_indices = Counter(i for wrd, i in v)
change_words = set(wrd for wrd, i in v)
words_changed = None
if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
words_changed = [wrd for wrd, i in v
if change_indices[i] > 1]
if words_changed:
cwords.add(tuple(sorted(words_changed)))
print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
print(f" {k:12} From {', '.join(v)}")
print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
print(f" {v[0]:12} From {', '.join(v[1:])}")
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 32
typedef struct string_tag {
size_t length;
char str[MAX_WORD_SIZE];
} string_t;
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int hamming_distance(const string_t* str1, const string_t* str2) {
size_t len1 = str1->length;
size_t len2 = str2->length;
if (len1 != len2)
return 0;
int count = 0;
const char* s1 = str1->str;
const char* s2 = str2->str;
for (size_t i = 0; i < len1; ++i) {
if (s1[i] != s2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
string_t* dictionary = xmalloc(sizeof(string_t) * capacity);
while (fgets(line, sizeof(line), in)) {
if (size == capacity) {
capacity *= 2;
dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);
}
size_t len = strlen(line) - 1;
if (len > 11) {
string_t* str = &dictionary[size];
str->length = len;
memcpy(str->str, line, len);
str->str[len] = '\0';
++size;
}
}
fclose(in);
printf("Changeable words in %s:\n", filename);
int n = 1;
for (size_t i = 0; i < size; ++i) {
const string_t* str1 = &dictionary[i];
for (size_t j = 0; j < size; ++j) {
const string_t* str2 = &dictionary[j];
if (i != j && hamming_distance(str1, str2) == 1)
printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str);
}
}
free(dictionary);
return EXIT_SUCCESS;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | from collections import defaultdict, Counter
def getwords(minlength=11, fname='unixdict.txt'):
"Return set of lowercased words of > given number of characters"
with open(fname) as f:
words = f.read().strip().lower().split()
return {w for w in words if len(w) > minlength}
words11 = getwords()
word_minus_1 = defaultdict(list)
minus_1_to_word = defaultdict(list)
for w in words11:
for i in range(len(w)):
minus_1 = w[:i] + w[i+1:]
word_minus_1[minus_1].append((w, i))
if minus_1 in words11:
minus_1_to_word[minus_1].append(w)
cwords = set()
for _, v in word_minus_1.items():
if len(v) >1:
change_indices = Counter(i for wrd, i in v)
change_words = set(wrd for wrd, i in v)
words_changed = None
if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
words_changed = [wrd for wrd, i in v
if change_indices[i] > 1]
if words_changed:
cwords.add(tuple(sorted(words_changed)))
print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
print(f" {k:12} From {', '.join(v)}")
print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
print(f" {v[0]:12} From {', '.join(v[1:])}")
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 32
typedef struct string_tag {
size_t length;
char str[MAX_WORD_SIZE];
} string_t;
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int hamming_distance(const string_t* str1, const string_t* str2) {
size_t len1 = str1->length;
size_t len2 = str2->length;
if (len1 != len2)
return 0;
int count = 0;
const char* s1 = str1->str;
const char* s2 = str2->str;
for (size_t i = 0; i < len1; ++i) {
if (s1[i] != s2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
string_t* dictionary = xmalloc(sizeof(string_t) * capacity);
while (fgets(line, sizeof(line), in)) {
if (size == capacity) {
capacity *= 2;
dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);
}
size_t len = strlen(line) - 1;
if (len > 11) {
string_t* str = &dictionary[size];
str->length = len;
memcpy(str->str, line, len);
str->str[len] = '\0';
++size;
}
}
fclose(in);
printf("Changeable words in %s:\n", filename);
int n = 1;
for (size_t i = 0; i < size; ++i) {
const string_t* str1 = &dictionary[i];
for (size_t j = 0; j < size; ++j) {
const string_t* str2 = &dictionary[j];
if (i != j && hamming_distance(str1, str2) == 1)
printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str);
}
}
free(dictionary);
return EXIT_SUCCESS;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | from tkinter import *
import tkinter.messagebox
def maximise():
root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))
def minimise():
root.iconify()
def delete():
if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"):
root.quit()
root = Tk()
mx=Button(root,text="maximise",command=maximise)
mx.grid()
mx.bind(maximise)
mn=Button(root,text="minimise",command=minimise)
mn.grid()
mn.bind(minimise)
root.protocol("WM_DELETE_WINDOW",delete)
mainloop()
| #include<windows.h>
#include<unistd.h>
#include<stdio.h>
const char g_szClassName[] = "weirdWindow";
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd[3];
MSG Msg;
int i,x=0,y=0;
char str[3][100];
int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.",
"If you can see two blank windows just behind this message box, you are in luck.",
"Let's get started....",
"Yes, you will be seeing a lot of me :)",
"Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)",
"Let's compare the windows for equality.",
"Now let's hide Window 1.",
"Now let's see Window 1 again.",
"Let's close Window 2, bye, bye, Number 2 !",
"Let's minimize Window 1.",
"Now let's maximize Window 1.",
"And finally we come to the fun part, watch Window 1 move !",
"Let's double Window 1 in size for all the good work.",
"That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if(!RegisterClassEx(&wc))
{
MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK);
return 0;
}
for(i=0;i<2;i++){
sprintf(str[i],"Window Number %d",i+1);
hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL);
if(hwnd[i] == NULL)
{
MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd[i], nCmdShow);
UpdateWindow(hwnd[i]);
}
for(i=0;i<6;i++){
MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
}
if(hwnd[0]==hwnd[1])
MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
else
MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_HIDE);
MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_SHOW);
MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[1], SW_HIDE);
MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_MINIMIZE);
MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_MAXIMIZE);
MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
ShowWindow(hwnd[0], SW_RESTORE);
while(x!=maxX/2||y!=maxY/2){
if(x<maxX/2)
x++;
if(y<maxY/2)
y++;
MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0);
sleep(10);
}
MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
MoveWindow(hwnd[0],0,0,maxX, maxY,0);
MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK);
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
|
Write the same algorithm in C as shown in this Python implementation. |
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar("T")
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return cls(value)
def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return MList(chain.from_iterable(map(func, self)))
def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return self.bind(func)
if __name__ == "__main__":
print(
MList([1, 99, 4])
.bind(lambda val: MList([val + 1]))
.bind(lambda val: MList([f"${val}.00"]))
)
print(
MList([1, 99, 4])
>> (lambda val: MList([val + 1]))
>> (lambda val: MList([f"${val}.00"]))
)
print(
MList(range(1, 6)).bind(
lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
)
)
print(
MList(range(1, 26)).bind(
lambda x: MList(range(x + 1, 26)).bind(
lambda y: MList(range(y + 1, 26)).bind(
lambda z: MList([(x, y, z)])
if x * x + y * y == z * z
else MList([])
)
)
)
)
| #include <stdio.h>
#include <stdlib.h>
#define MONAD void*
#define INTBIND(f, g, x) (f((int*)g(x)))
#define RETURN(type,x) &((type)*)(x)
MONAD boundInt(int *x) {
return (MONAD)(x);
}
MONAD boundInt2str(int *x) {
char buf[100];
char*str= malloc(1+sprintf(buf, "%d", *x));
sprintf(str, "%d", *x);
return (MONAD)(str);
}
void task(int y) {
char *z= INTBIND(boundInt2str, boundInt, &y);
printf("%s\n", z);
free(z);
}
int main() {
task(13);
}
|
Convert this Python block to C, preserving its control flow and logic. | limit = 1000
print("working...")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
print("done...")
| #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Python code. | limit = 1000
print("working...")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
print("done...")
| #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Python version. | limit = 1000
print("working...")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def issquare(x):
for n in range(1,x+1):
if (x == n*n):
return 1
return 0
for n in range(limit-1):
if issquare(n) and isprime(n+1):
print(n,end=" ")
print()
print("done...")
| #include <stdio.h>
#include <stdbool.h>
#include <math.h>
#define MAX 1000
void sieve(int n, bool *prime) {
prime[0] = prime[1] = false;
for (int i=2; i<=n; i++) prime[i] = true;
for (int p=2; p*p<=n; p++)
if (prime[p])
for (int c=p*p; c<=n; c+=p) prime[c] = false;
}
bool square(int n) {
int sq = sqrt(n);
return (sq * sq == n);
}
int main() {
bool prime[MAX + 1];
sieve(MAX, prime);
for (int i=2; i<=MAX; i++) if (prime[i]) {
int sq = i-1;
if (square(sq)) printf("%d ", sq);
}
printf("\n");
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
p = 3
i = 2
print("2 3", end = " ");
while True:
if isPrime(p + i) == 1:
p += i
print(p, end = " ");
i += 2
if p + i >= 1050:
break
| #include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
int 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;
}
int main() {
int i, lastSpecial = 3, lastGap = 1;
printf("Special primes under 1,050:\n");
printf("Prime1 Prime2 Gap\n");
printf("%6d %6d %3d\n", 2, 3, lastGap);
for (i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
|
Convert the following code from Python to C, ensuring the logic remains intact. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
p = 3
i = 2
print("2 3", end = " ");
while True:
if isPrime(p + i) == 1:
p += i
print(p, end = " ");
i += 2
if p + i >= 1050:
break
| #include <stdio.h>
#include <stdbool.h>
bool isPrime(int n) {
int 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;
}
int main() {
int i, lastSpecial = 3, lastGap = 1;
printf("Special primes under 1,050:\n");
printf("Prime1 Prime2 Gap\n");
printf("%6d %6d %3d\n", 2, 3, lastGap);
for (i = 5; i < 1050; i += 2) {
if (isPrime(i) && (i-lastSpecial) > lastGap) {
lastGap = i - lastSpecial;
printf("%6d %6d %3d\n", lastSpecial, i, lastGap);
lastSpecial = i;
}
}
}
|
Rewrite the snippet below in C so it works the same as the original Python code. |
from functools import (reduce)
def mayanNumerals(n):
return showIntAtBase(20)(
mayanDigit
)(n)([])
def mayanDigit(n):
if 0 < n:
r = n % 5
return [
(['●' * r] if 0 < r else []) +
(['━━'] * (n // 5))
]
else:
return ['Θ']
def mayanFramed(n):
return 'Mayan ' + str(n) + ':\n\n' + (
wikiTable({
'class': 'wikitable',
'style': cssFromDict({
'text-align': 'center',
'background-color': '
'color': '
'border': '2px solid silver'
}),
'colwidth': '3em',
'cell': 'vertical-align: bottom;'
})([[
'<br>'.join(col) for col in mayanNumerals(n)
]])
)
def main():
print(
main.__doc__ + ':\n\n' +
'\n'.join(mayanFramed(n) for n in [
4005, 8017, 326205, 886205, 1081439556,
1000000, 1000000000
])
)
def wikiTable(opts):
def colWidth():
return 'width:' + opts['colwidth'] + '; ' if (
'colwidth' in opts
) else ''
def cellStyle():
return opts['cell'] if 'cell' in opts else ''
return lambda rows: '{| ' + reduce(
lambda a, k: (
a + k + '="' + opts[k] + '" ' if (
k in opts
) else a
),
['class', 'style'],
''
) + '\n' + '\n|-\n'.join(
'\n'.join(
('|' if (
0 != i and ('cell' not in opts)
) else (
'|style="' + colWidth() + cellStyle() + '"|'
)) + (
str(x) or ' '
) for x in row
) for i, row in enumerate(rows)
) + '\n|}\n\n'
def cssFromDict(dct):
return reduce(
lambda a, k: a + k + ':' + dct[k] + '; ',
dct.keys(),
''
)
def showIntAtBase(base):
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
if __name__ == '__main__':
main()
| #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
size_t base20(unsigned int n, uint8_t *out) {
uint8_t *start = out;
do {*out++ = n % 20;} while (n /= 20);
size_t length = out - start;
while (out > start) {
uint8_t x = *--out;
*out = *start;
*start++ = x;
}
return length;
}
void make_digit(int n, char *place, size_t line_length) {
static const char *parts[] = {" "," . "," .. ","... ","....","----"};
int i;
for (i=4; i>0; i--, n -= 5)
memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);
if (n == -20) place[4 * line_length + 1] = '@';
}
char *mayan(unsigned int n) {
if (n == 0) return NULL;
uint8_t digits[15];
size_t n_digits = base20(n, digits);
size_t line_length = n_digits*5 + 2;
char *str = malloc(line_length * 6 + 1);
if (str == NULL) return NULL;
str[line_length * 6] = 0;
char *ptr;
unsigned int i;
for (ptr=str, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "+----", 5);
memcpy(ptr-5, "+\n", 2);
memcpy(str+5*line_length, str, line_length);
for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "| ", 5);
memcpy(ptr-5, "|\n", 2);
memcpy(str+2*line_length, str+line_length, line_length);
memcpy(str+3*line_length, str+line_length, 2*line_length);
for (i=0; i<n_digits; i++)
make_digit(digits[i], str+1+5*i, line_length);
return str;
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: mayan <number>\n");
return 1;
}
int i = atoi(argv[1]);
if (i <= 0) {
fprintf(stderr, "number must be positive\n");
return 1;
}
char *m = mayan(i);
printf("%s",m);
free(m);
return 0;
}
|
Generate an equivalent C version of this Python code. |
from functools import (reduce)
def mayanNumerals(n):
return showIntAtBase(20)(
mayanDigit
)(n)([])
def mayanDigit(n):
if 0 < n:
r = n % 5
return [
(['●' * r] if 0 < r else []) +
(['━━'] * (n // 5))
]
else:
return ['Θ']
def mayanFramed(n):
return 'Mayan ' + str(n) + ':\n\n' + (
wikiTable({
'class': 'wikitable',
'style': cssFromDict({
'text-align': 'center',
'background-color': '
'color': '
'border': '2px solid silver'
}),
'colwidth': '3em',
'cell': 'vertical-align: bottom;'
})([[
'<br>'.join(col) for col in mayanNumerals(n)
]])
)
def main():
print(
main.__doc__ + ':\n\n' +
'\n'.join(mayanFramed(n) for n in [
4005, 8017, 326205, 886205, 1081439556,
1000000, 1000000000
])
)
def wikiTable(opts):
def colWidth():
return 'width:' + opts['colwidth'] + '; ' if (
'colwidth' in opts
) else ''
def cellStyle():
return opts['cell'] if 'cell' in opts else ''
return lambda rows: '{| ' + reduce(
lambda a, k: (
a + k + '="' + opts[k] + '" ' if (
k in opts
) else a
),
['class', 'style'],
''
) + '\n' + '\n|-\n'.join(
'\n'.join(
('|' if (
0 != i and ('cell' not in opts)
) else (
'|style="' + colWidth() + cellStyle() + '"|'
)) + (
str(x) or ' '
) for x in row
) for i, row in enumerate(rows)
) + '\n|}\n\n'
def cssFromDict(dct):
return reduce(
lambda a, k: a + k + ':' + dct[k] + '; ',
dct.keys(),
''
)
def showIntAtBase(base):
def wrap(toChr, n, rs):
def go(nd, r):
n, d = nd
r_ = toChr(d) + r
return go(divmod(n, base), r_) if 0 != n else r_
return 'unsupported base' if 1 >= base else (
'negative number' if 0 > n else (
go(divmod(n, base), rs))
)
return lambda toChr: lambda n: lambda rs: (
wrap(toChr, n, rs)
)
if __name__ == '__main__':
main()
| #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#define MIN(x,y) ((x) < (y) ? (x) : (y))
size_t base20(unsigned int n, uint8_t *out) {
uint8_t *start = out;
do {*out++ = n % 20;} while (n /= 20);
size_t length = out - start;
while (out > start) {
uint8_t x = *--out;
*out = *start;
*start++ = x;
}
return length;
}
void make_digit(int n, char *place, size_t line_length) {
static const char *parts[] = {" "," . "," .. ","... ","....","----"};
int i;
for (i=4; i>0; i--, n -= 5)
memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4);
if (n == -20) place[4 * line_length + 1] = '@';
}
char *mayan(unsigned int n) {
if (n == 0) return NULL;
uint8_t digits[15];
size_t n_digits = base20(n, digits);
size_t line_length = n_digits*5 + 2;
char *str = malloc(line_length * 6 + 1);
if (str == NULL) return NULL;
str[line_length * 6] = 0;
char *ptr;
unsigned int i;
for (ptr=str, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "+----", 5);
memcpy(ptr-5, "+\n", 2);
memcpy(str+5*line_length, str, line_length);
for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5)
memcpy(ptr, "| ", 5);
memcpy(ptr-5, "|\n", 2);
memcpy(str+2*line_length, str+line_length, line_length);
memcpy(str+3*line_length, str+line_length, 2*line_length);
for (i=0; i<n_digits; i++)
make_digit(digits[i], str+1+5*i, line_length);
return str;
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: mayan <number>\n");
return 1;
}
int i = atoi(argv[1]);
if (i <= 0) {
fprintf(stderr, "number must be positive\n");
return 1;
}
char *m = mayan(i);
printf("%s",m);
free(m);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. |
from math import prod
def superFactorial(n):
return prod([prod(range(1,i+1)) for i in range(1,n+1)])
def hyperFactorial(n):
return prod([i**i for i in range(1,n+1)])
def alternatingFactorial(n):
return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])
def exponentialFactorial(n):
if n in [0,1]:
return 1
else:
return n**exponentialFactorial(n-1)
def inverseFactorial(n):
i = 1
while True:
if n == prod(range(1,i)):
return i-1
elif n < prod(range(1,i)):
return "undefined"
i+=1
print("Superfactorials for [0,9] :")
print({"sf(" + str(i) + ") " : superFactorial(i) for i in range(0,10)})
print("\nHyperfactorials for [0,9] :")
print({"H(" + str(i) + ") " : hyperFactorial(i) for i in range(0,10)})
print("\nAlternating factorials for [0,9] :")
print({"af(" + str(i) + ") " : alternatingFactorial(i) for i in range(0,10)})
print("\nExponential factorials for [0,4] :")
print({str(i) + "$ " : exponentialFactorial(i) for i in range(0,5)})
print("\nDigits in 5$ : " , len(str(exponentialFactorial(5))))
factorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
print("\nInverse factorials for " , factorialSet)
print({"rf(" + str(i) + ") ":inverseFactorial(i) for i in factorialSet})
print("\nrf(119) : " + inverseFactorial(119))
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int inverse_factorial(uint64_t f) {
int p = 1;
int i = 1;
if (f == 1) {
return 0;
}
while (p < f) {
p *= i;
i++;
}
if (p == f) {
return i - 1;
}
return -1;
}
uint64_t super_factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= factorial(i);
}
return result;
}
uint64_t hyper_factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= (uint64_t)powl(i, i);
}
return result;
}
uint64_t alternating_factorial(int n) {
uint64_t result = 0;
int i;
for (i = 1; i <= n; i++) {
if ((n - i) % 2 == 0) {
result += factorial(i);
} else {
result -= factorial(i);
}
}
return result;
}
uint64_t exponential_factorial(int n) {
uint64_t result = 0;
int i;
for (i = 1; i <= n; i++) {
result = (uint64_t)powl(i, (long double)result);
}
return result;
}
void test_factorial(int count, uint64_t(*func)(int), char *name) {
int i;
printf("First %d %s:\n", count, name);
for (i = 0; i < count ; i++) {
printf("%llu ", func(i));
}
printf("\n");
}
void test_inverse(uint64_t f) {
int n = inverse_factorial(f);
if (n < 0) {
printf("rf(%llu) = No Solution\n", f);
} else {
printf("rf(%llu) = %d\n", f, n);
}
}
int main() {
int i;
test_factorial(9, super_factorial, "super factorials");
printf("\n");
test_factorial(8, super_factorial, "hyper factorials");
printf("\n");
test_factorial(10, alternating_factorial, "alternating factorials");
printf("\n");
test_factorial(5, exponential_factorial, "exponential factorials");
printf("\n");
test_inverse(1);
test_inverse(2);
test_inverse(6);
test_inverse(24);
test_inverse(120);
test_inverse(720);
test_inverse(5040);
test_inverse(40320);
test_inverse(362880);
test_inverse(3628800);
test_inverse(119);
return 0;
}
|
Transform the following Python implementation into C, maintaining the same output and logic. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def nextPrime(n):
if n == 0:
return 2
if n < 3:
return n + 1
q = n + 2
while not isPrime(q):
q += 2
return q
if __name__ == "__main__":
for p1 in range(3,100,2):
p2 = nextPrime(p1)
if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):
print(p1,'\t', p2,'\t', p1 + p2 - 1)
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int main(void) {
int p1, p2;
for(p1=3;p1<=99;p1+=2) {
p2=nextprime(p1);
if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {
printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 );
}
}
return 0;
}
|
Write the same code in C as shown below in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def nextPrime(n):
if n == 0:
return 2
if n < 3:
return n + 1
q = n + 2
while not isPrime(q):
q += 2
return q
if __name__ == "__main__":
for p1 in range(3,100,2):
p2 = nextPrime(p1)
if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):
print(p1,'\t', p2,'\t', p1 + p2 - 1)
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int nextprime( int p ) {
int i=0;
if(p==0) return 2;
if(p<3) return p+1;
while(!isprime(++i + p));
return i+p;
}
int main(void) {
int p1, p2;
for(p1=3;p1<=99;p1+=2) {
p2=nextprime(p1);
if(p2<100&&isprime(p1)&&isprime(p2+p1-1)) {
printf( "%d + %d - 1 = %d\n", p1, p2, p1+p2-1 );
}
}
return 0;
}
|
Translate this program into C but keep the logic exactly as in Python. | range17 = range(17)
a = [['0'] * 17 for i in range17]
idx = [0] * 4
def find_group(mark, min_n, max_n, depth=1):
if (depth == 4):
prefix = "" if (mark == '1') else "un"
print("Fail, found totally {}connected group:".format(prefix))
for i in range(4):
print(idx[i])
return True
for i in range(min_n, max_n):
n = 0
while (n < depth):
if (a[idx[n]][i] != mark):
break
n += 1
if (n == depth):
idx[n] = i
if (find_group(mark, 1, max_n, depth + 1)):
return True
return False
if __name__ == '__main__':
for i in range17:
a[i][i] = '-'
for k in range(4):
for i in range17:
j = (i + pow(2, k)) % 17
a[i][j] = a[j][i] = '1'
for row in a:
print(' '.join(row))
for i in range17:
idx[0] = i
if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):
print("no good")
exit()
print("all good")
| #include <stdio.h>
int a[17][17], idx[4];
int find_group(int type, int min_n, int max_n, int depth)
{
int i, n;
if (depth == 4) {
printf("totally %sconnected group:", type ? "" : "un");
for (i = 0; i < 4; i++) printf(" %d", idx[i]);
putchar('\n');
return 1;
}
for (i = min_n; i < max_n; i++) {
for (n = 0; n < depth; n++)
if (a[idx[n]][i] != type) break;
if (n == depth) {
idx[n] = i;
if (find_group(type, 1, max_n, depth + 1))
return 1;
}
}
return 0;
}
int main()
{
int i, j, k;
const char *mark = "01-";
for (i = 0; i < 17; i++)
a[i][i] = 2;
for (k = 1; k <= 8; k <<= 1) {
for (i = 0; i < 17; i++) {
j = (i + k) % 17;
a[i][j] = a[j][i] = 1;
}
}
for (i = 0; i < 17; i++) {
for (j = 0; j < 17; j++)
printf("%c ", mark[a[i][j]]);
putchar('\n');
}
for (i = 0; i < 17; i++) {
idx[0] = i;
if (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) {
puts("no good");
return 0;
}
}
puts("all good");
return 0;
}
|
Port the following code from Python to C with equivalent syntax and logic. |
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack()
root.mainloop()
| #include<windows.h>
#include<stdio.h>
int main()
{
printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. |
print "\033[7mReversed\033[m Normal"
| #include <stdio.h>
int main()
{
printf("\033[7mReversed\033[m Normal\n");
return 0;
}
|
Generate an equivalent C version of this Python code. | import random
from collections import OrderedDict
numbers = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
10 ** 6: 'million',
10 ** 9: 'billion',
10 ** 12: 'trillion',
10 ** 15: 'quadrillion',
10 ** 18: 'quintillion',
10 ** 21: 'sextillion',
10 ** 24: 'septillion',
10 ** 27: 'octillion',
10 ** 30: 'nonillion',
10 ** 33: 'decillion',
10 ** 36: 'undecillion',
10 ** 39: 'duodecillion',
10 ** 42: 'tredecillion',
10 ** 45: 'quattuordecillion',
10 ** 48: 'quinquadecillion',
10 ** 51: 'sedecillion',
10 ** 54: 'septendecillion',
10 ** 57: 'octodecillion',
10 ** 60: 'novendecillion',
10 ** 63: 'vigintillion',
10 ** 66: 'unvigintillion',
10 ** 69: 'duovigintillion',
10 ** 72: 'tresvigintillion',
10 ** 75: 'quattuorvigintillion',
10 ** 78: 'quinquavigintillion',
10 ** 81: 'sesvigintillion',
10 ** 84: 'septemvigintillion',
10 ** 87: 'octovigintillion',
10 ** 90: 'novemvigintillion',
10 ** 93: 'trigintillion',
10 ** 96: 'untrigintillion',
10 ** 99: 'duotrigintillion',
10 ** 102: 'trestrigintillion',
10 ** 105: 'quattuortrigintillion',
10 ** 108: 'quinquatrigintillion',
10 ** 111: 'sestrigintillion',
10 ** 114: 'septentrigintillion',
10 ** 117: 'octotrigintillion',
10 ** 120: 'noventrigintillion',
10 ** 123: 'quadragintillion',
10 ** 153: 'quinquagintillion',
10 ** 183: 'sexagintillion',
10 ** 213: 'septuagintillion',
10 ** 243: 'octogintillion',
10 ** 273: 'nonagintillion',
10 ** 303: 'centillion',
10 ** 306: 'uncentillion',
10 ** 309: 'duocentillion',
10 ** 312: 'trescentillion',
10 ** 333: 'decicentillion',
10 ** 336: 'undecicentillion',
10 ** 363: 'viginticentillion',
10 ** 366: 'unviginticentillion',
10 ** 393: 'trigintacentillion',
10 ** 423: 'quadragintacentillion',
10 ** 453: 'quinquagintacentillion',
10 ** 483: 'sexagintacentillion',
10 ** 513: 'septuagintacentillion',
10 ** 543: 'octogintacentillion',
10 ** 573: 'nonagintacentillion',
10 ** 603: 'ducentillion',
10 ** 903: 'trecentillion',
10 ** 1203: 'quadringentillion',
10 ** 1503: 'quingentillion',
10 ** 1803: 'sescentillion',
10 ** 2103: 'septingentillion',
10 ** 2403: 'octingentillion',
10 ** 2703: 'nongentillion',
10 ** 3003: 'millinillion'
}
numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))
def string_representation(i: int) -> str:
if i == 0:
return 'zero'
words = ['negative'] if i < 0 else []
working_copy = abs(i)
for key, value in numbers.items():
if key <= working_copy:
times = int(working_copy / key)
if key >= 100:
words.append(string_representation(times))
words.append(value)
working_copy -= times * key
if working_copy == 0:
break
return ' '.join(words)
def next_phrase(i: int):
while not i == 4:
str_i = string_representation(i)
len_i = len(str_i)
yield str_i, 'is', string_representation(len_i)
i = len_i
yield string_representation(i), 'is', 'magic'
def magic(i: int) -> str:
phrases = []
for phrase in next_phrase(i):
phrases.append(' '.join(phrase))
return f'{", ".join(phrases)}.'.capitalize()
if __name__ == '__main__':
for j in (random.randint(0, 10 ** 3) for i in range(5)):
print(j, ':\n', magic(j), '\n')
for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):
print(j, ':\n', magic(j), '\n')
| #include <stdint.h>
#include <stdio.h>
#include <glib.h>
typedef struct named_number_tag {
const char* name;
uint64_t number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 1000000000000 },
{ "quadrillion", 1000000000000000ULL },
{ "quintillion", 1000000000000000000ULL }
};
const named_number* get_named_number(uint64_t n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_number);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
size_t append_number_name(GString* str, uint64_t n) {
static const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
static const char* tens[] = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
size_t len = str->len;
if (n < 20) {
g_string_append(str, small[n]);
}
else if (n < 100) {
g_string_append(str, tens[n/10 - 2]);
if (n % 10 != 0) {
g_string_append_c(str, '-');
g_string_append(str, small[n % 10]);
}
} else {
const named_number* num = get_named_number(n);
uint64_t p = num->number;
append_number_name(str, n/p);
g_string_append_c(str, ' ');
g_string_append(str, num->name);
if (n % p != 0) {
g_string_append_c(str, ' ');
append_number_name(str, n % p);
}
}
return str->len - len;
}
GString* magic(uint64_t n) {
GString* str = g_string_new(NULL);
for (unsigned int i = 0; ; ++i) {
size_t count = append_number_name(str, n);
if (i == 0)
str->str[0] = g_ascii_toupper(str->str[0]);
if (n == 4) {
g_string_append(str, " is magic.");
break;
}
g_string_append(str, " is ");
append_number_name(str, count);
g_string_append(str, ", ");
n = count;
}
return str;
}
void test_magic(uint64_t n) {
GString* str = magic(n);
printf("%s\n", str->str);
g_string_free(str, TRUE);
}
int main() {
test_magic(5);
test_magic(13);
test_magic(78);
test_magic(797);
test_magic(2739);
test_magic(4000);
test_magic(7893);
test_magic(93497412);
test_magic(2673497412U);
test_magic(10344658531277200972ULL);
return 0;
}
|
Port the provided Python code into C while preserving the original functionality. | In [6]: def dec(n):
...: return len(n.rsplit('.')[-1]) if '.' in n else 0
In [7]: dec('12.345')
Out[7]: 3
In [8]: dec('12.3450')
Out[8]: 4
In [9]:
| #include <stdio.h>
int findNumOfDec(double x) {
char buffer[128];
int pos, num;
sprintf(buffer, "%.14f", x);
pos = 0;
num = 0;
while (buffer[pos] != 0 && buffer[pos] != '.') {
pos++;
}
if (buffer[pos] != 0) {
pos++;
while (buffer[pos] != 0) {
pos++;
}
pos--;
while (buffer[pos] == '0') {
pos--;
}
while (buffer[pos] != '.') {
num++;
pos--;
}
}
return num;
}
void test(double x) {
int num = findNumOfDec(x);
printf("%f has %d decimals\n", x, num);
}
int main() {
test(12.0);
test(12.345);
test(12.345555555555);
test(12.3450);
test(12.34555555555555555555);
test(1.2345e+54);
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>>
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
| enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
|
Translate the given Python code snippet into C without altering its behavior. | try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
if l * 2 >= sum and b >= BRANCH:
return
if b == br + 1:
c = ra[n] * cnt
else:
c = c * (ra[n] + (b - br - 1)) / (b - br)
if l * 2 < sum:
unrooted[sum] += c
if b < BRANCH:
ra[sum] += c;
for m in range(1, n):
tree(b, m, l, sum, c)
def bicenter(s):
global ra, unrooted
if not (s & 1):
aux = ra[s / 2]
unrooted[s] += aux * (aux + 1) / 2
def main():
global ra, unrooted, MAX_N
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1
for n in xrange(1, MAX_N):
tree(0, n, n)
bicenter(n)
print "%d: %d" % (n, unrooted[n])
main()
| #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
for (b = br + 1; b <= BRANCH; b++) {
s = sum + (b - br) * n;
if (s >= MAX_N) return;
c = choose(rooted[n], b - br) * cnt;
if (l * 2 < s) unrooted[s] += c;
if (b == BRANCH) return;
rooted[s] += c;
for (m = n; --m; ) tree(b, m, c, s, l);
}
}
void bicenter(int s)
{
if (s & 1) return;
unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}
int main()
{
xint n;
for (n = 1; n < MAX_N; n++) {
tree(0, n, 1, 1, n);
bicenter(n);
printf("%"FMT": %"FMT"\n", n, unrooted[n]);
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
if l * 2 >= sum and b >= BRANCH:
return
if b == br + 1:
c = ra[n] * cnt
else:
c = c * (ra[n] + (b - br - 1)) / (b - br)
if l * 2 < sum:
unrooted[sum] += c
if b < BRANCH:
ra[sum] += c;
for m in range(1, n):
tree(b, m, l, sum, c)
def bicenter(s):
global ra, unrooted
if not (s & 1):
aux = ra[s / 2]
unrooted[s] += aux * (aux + 1) / 2
def main():
global ra, unrooted, MAX_N
ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1
for n in xrange(1, MAX_N):
tree(0, n, n)
bicenter(n)
print "%d: %d" % (n, unrooted[n])
main()
| #include <stdio.h>
#define MAX_N 33
#define BRANCH 4
typedef unsigned long long xint;
#define FMT "llu"
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
for (b = br + 1; b <= BRANCH; b++) {
s = sum + (b - br) * n;
if (s >= MAX_N) return;
c = choose(rooted[n], b - br) * cnt;
if (l * 2 < s) unrooted[s] += c;
if (b == BRANCH) return;
rooted[s] += c;
for (m = n; --m; ) tree(b, m, c, s, l);
}
}
void bicenter(int s)
{
if (s & 1) return;
unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2;
}
int main()
{
xint n;
for (n = 1; n < MAX_N; n++) {
tree(0, n, 1, 1, n);
bicenter(n);
printf("%"FMT": %"FMT"\n", n, unrooted[n]);
}
return 0;
}
|
Please provide an equivalent version of this Python code in C. | def min_cells_matrix(siz):
return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]
def display_matrix(mat):
siz = len(mat)
spaces = 2 if siz < 20 else 3 if siz < 200 else 4
print(f"\nMinimum number of cells after, before, above and below {siz} x {siz} square:")
for row in range(siz):
print("".join([f"{n:{spaces}}" for n in mat[row]]))
def test_min_mat():
for siz in [23, 10, 9, 2, 1]:
display_matrix(min_cells_matrix(siz))
if __name__ == "__main__":
test_min_mat()
| #include<stdio.h>
#include<stdlib.h>
#define min(a, b) (a<=b?a:b)
void minab( unsigned int n ) {
int i, j;
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
printf( "%2d ", min( min(i, n-1-i), min(j, n-1-j) ));
}
printf( "\n" );
}
return;
}
int main(void) {
minab(10);
return 0;
}
|
Please provide an equivalent version of this Python code in C. | import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY",
"LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" };
int stroke=0,fill=0,back=0,i;
double centerX = 300,centerY = 300,coreSide,armLength,pentaLength;
printf("Enter core pentagon side length : ");
scanf("%lf",&coreSide);
printf("Enter pentagram arm length : ");
scanf("%lf",&armLength);
printf("Available colours are :\n");
for(i=0;i<16;i++){
printf("%d. %s\t",i+1,colourNames[i]);
if((i+1) % 3 == 0){
printf("\n");
}
}
while(stroke==fill && fill==back){
printf("\nEnter three diffrenet options for stroke, fill and background : ");
scanf("%d%d%d",&stroke,&fill,&back);
}
pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4);
initwindow(2*centerX,2*centerY,"Pentagram");
setcolor(stroke-1);
setfillstyle(SOLID_FILL,back-1);
bar(0,0,2*centerX,2*centerY);
floodfill(centerX,centerY,back-1);
setfillstyle(SOLID_FILL,fill-1);
for(i=0;i<5;i++){
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)));
line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5));
floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1);
}
floodfill(centerX,centerY,stroke-1);
getch();
closegraph();
}
|
Change the programming language of this snippet from Python to C without modifying what it does. | from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port ))
| #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f,
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10;
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
if ( bIsIPv6local )
{
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else
{
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
abyAddrLocal = abyAddr;
if ( NULL == abyAddrLocal )
abyAddrLocal = abyDummyAddr;
if ( ! bIsIPv6local )
{
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort )
{
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
else
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
if ( NULL != pchOpenBracket )
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL;
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx )
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText );
if ( pszTextBefore == *ppszText )
{
if ( NULL != pbyZerosLoc )
{
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0;
}
if ( ':' != **ppszText )
return 0;
if ( 0 == nIdx )
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText )
{
const char* pszTextlocal = pszTextBefore;
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal;
if ( ! bParseResultlocal || bIsIPv6local )
return 0;
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx;
bIPv4Detected = 1;
break;
}
if ( nVal > 65535 )
return 0;
*(pbyAddrCursor++) = nVal >> 8;
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText )
{
++(*ppszText);
}
else
{
break;
}
}
}
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal );
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
int nZeros = 16 - nTail - nHead;
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
memset ( pbyZerosLoc, 0, nZeros );
}
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort )
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
}
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}
|
Preserve the algorithm and functionality while converting the code from Python to C. | import curses
import random
import time
ROW_DELAY=.0001
def get_rand_in_range(min, max):
return random.randrange(min,max+1)
try:
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
total_chars = len(chars)
stdscr = curses.initscr()
curses.noecho()
curses.curs_set(False)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
stdscr.attron(curses.color_pair(1))
max_x = curses.COLS - 1
max_y = curses.LINES - 1
columns_row = []
columns_active = []
for i in range(max_x+1):
columns_row.append(-1)
columns_active.append(0)
while(True):
for i in range(max_x):
if columns_row[i] == -1:
columns_row[i] = get_rand_in_range(0, max_y)
columns_active[i] = get_rand_in_range(0, 1)
for i in range(max_x):
if columns_active[i] == 1:
char_index = get_rand_in_range(0, total_chars-1)
stdscr.addstr(columns_row[i], i, chars[char_index])
else:
stdscr.addstr(columns_row[i], i, " ");
columns_row[i]+=1
if columns_row[i] >= max_y:
columns_row[i] = -1
if get_rand_in_range(0, 1000) == 0:
if columns_active[i] == 0:
columns_active[i] = 1
else:
columns_active[i] = 0
time.sleep(ROW_DELAY)
stdscr.refresh()
except KeyboardInterrupt as err:
curses.endwin()
|
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#define ROW_DELAY 40000
int get_rand_in_range(int min, int max)
{
return (rand() % ((max + 1) - min) + min);
}
int main(void)
{
srand(time(NULL));
char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int total_chars = sizeof(chars);
initscr();
noecho();
curs_set(FALSE);
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
attron(COLOR_PAIR(1));
int max_x = 0, max_y = 0;
getmaxyx(stdscr, max_y, max_x);
int columns_row[max_x];
int columns_active[max_x];
int i;
for (i = 0; i < max_x; i++)
{
columns_row[i] = -1;
columns_active[i] = 0;
}
while (1)
{
for (i = 0; i < max_x; i++)
{
if (columns_row[i] == -1)
{
columns_row[i] = get_rand_in_range(0, max_y);
columns_active[i] = get_rand_in_range(0, 1);
}
}
for (i = 0; i < max_x; i++)
{
if (columns_active[i] == 1)
{
int char_index = get_rand_in_range(0, total_chars);
mvprintw(columns_row[i], i, "%c", chars[char_index]);
}
else
{
mvprintw(columns_row[i], i, " ");
}
columns_row[i]++;
if (columns_row[i] >= max_y)
{
columns_row[i] = -1;
}
if (get_rand_in_range(0, 1000) == 0)
{
columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
}
}
usleep(ROW_DELAY);
refresh();
}
endwin();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.