Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in C as shown in this Python implementation. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
typedef double Fp;
typedef struct { Fp x, y, r; } Circle;
Circle circles[] = {
{ 1.6417233788, 1.6121789534, 0.0848270516},
{-1.4944608174, 1.2077959613, 1.1039549836},
{ 0.6110294452, -0.6907087527, 0.908916... |
Translate this program into C but keep the logic exactly as in Python. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
typedef double Fp;
typedef struct { Fp x, y, r; } Circle;
Circle circles[] = {
{ 1.6417233788, 1.6121789534, 0.0848270516},
{-1.4944608174, 1.2077959613, 1.1039549836},
{ 0.6110294452, -0.6907087527, 0.908916... |
Rewrite the snippet below in C so it works the same as the original Python code. | from math import hypot, pi, cos, sin
from PIL import Image
def hough(im, ntx=460, mry=360):
"Calculate Hough transform."
pim = im.load()
nimx, mimy = im.size
mry = int(mry/2)*2
him = Image.new("L", (ntx, mry), 255)
phim = him.load()
rmax = hypot(nimx, mimy)
dr = rmax / (mry/... | #include "SL_Generated.h"
#include "CImg.h"
using namespace cimg_library;
int main( int argc, char** argv )
{
string fileName = "Pentagon.bmp";
if(argc > 1) fileName = argv[1];
int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]);
int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[... |
Rewrite the snippet below in C so it works the same as the original Python code. | import math
import random
def GammaInc_Q( a, x):
a1 = a-1
a2 = a-2
def f0( t ):
return t**a1*math.exp(-t)
def df0(t):
return (a1-t)*t**a2*math.exp(-t)
y = a1
while f0(y)*(x-y) >2.0e-8 and y < x: y += .3
if y > x: y = x
h = 3.0e-4
n = int(y/h)
h = y/n
h... | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
typedef double (* Ifctn)( double t);
double Simpson3_8( Ifctn f, double a, double b, int N)
{
int j;
double l1;
double h = (b-a)/N;
double h1 = h/3.0;
double sum = f(a) + f(b);
for... |
Convert this Python block to C, preserving its control flow and logic. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - ... | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {
if (ARRAY1_SIZE <= 1) {
return 1.0;
} else if (ARRAY2_SIZE <= 1) {
return 1.0;
}
double fmean1 = 0.0, fmean2 = 0.0;
for (s... |
Keep all operations the same but rewrite the snippet in C. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - ... | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) {
if (ARRAY1_SIZE <= 1) {
return 1.0;
} else if (ARRAY2_SIZE <= 1) {
return 1.0;
}
double fmean1 = 0.0, fmean2 = 0.0;
for (s... |
Generate an equivalent C version of this Python code. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar... | char input[] = "top1 des1 ip1 ip2\n"
"top2 des1 ip2 ip3\n"
"ip1 extra1 ip1a ipcommon\n"
"ip2 ip2a ip2b ip2c ipcommon\n"
"des1 des1a des1b des1c\n"
"des1a des1a1 des1a2\n"
"des1c des1c1 extra1\n";
...
int find_name(item base, int len, const char *name)
{
int i;
for (i = 0; i < len; i+... |
Write the same code in C as shown below in Python. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar... | char input[] = "top1 des1 ip1 ip2\n"
"top2 des1 ip2 ip3\n"
"ip1 extra1 ip1a ipcommon\n"
"ip2 ip2a ip2b ip2c ipcommon\n"
"des1 des1a des1b des1c\n"
"des1a des1a1 des1a2\n"
"des1c des1c1 extra1\n";
...
int find_name(item base, int len, const char *name)
{
int i;
for (i = 0; i < len; i+... |
Translate this program into C but keep the logic exactly as in Python. | def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c... | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 128
typedef unsigned char character;
typedef character *string;
typedef struct node_t node;
struct node_t {
enum tag_t {
NODE_LEAF,
NODE_TREE,
NODE_SEQ,
} tag;
union {
stri... |
Write a version of this Python function in C with identical behavior. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
va... |
f();
g(1, 2, 3);
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
}
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
h(1, 2, 3, 4, "abcd", (void*)0);
struct v_args {
int arg1;
int a... |
Write the same algorithm in C as shown in this Python implementation. | def no_args():
pass
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
fixed_args(1, 2)
fixed_args(y=2, x=1)
myargs=(1,2)
fixed_args(*myargs)
def opt_args(x=1):
print(x)
opt_args()
opt_args(3.141)
def var_args(*v):
print(v)
var_args(1, 2, 3)
va... |
f();
g(1, 2, 3);
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
}
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
h(1, 2, 3, 4, "abcd", (void*)0);
struct v_args {
int arg1;
int a... |
Change the programming language of this snippet from Python to C without modifying what it does. | "Generate a short Superpermutation of n characters A... as a string using various algorithms."
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
allchars = string.ascii_uppercase... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 12
char *super = 0;
int pos, cnt[MAX];
int fact_sum(int n)
{
int s, x, f;
for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);
return s;
}
int r(int n)
{
if (!n) return 0;
char c = super[pos - n];
if (!--cnt[n]) {
cnt[n] = n;
if (!r(n-... |
Write a version of this Python function in C with identical behavior. | import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
... | #include <windows.h>
#include "resource.h"
BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {
switch( msg ) {
case WM_INITDIALOG:
srand( GetTickCount() );
SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );
break;
case WM_COMMAND:
swit... |
Can you help me rewrite this code in C instead of Python, keeping it the same logically? | from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines):
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in ... | #include <stdio.h>
#include <stdlib.h>
inline int irand(int n)
{
int r, randmax = RAND_MAX/n * n;
while ((r = rand()) >= randmax);
return r / (randmax / n);
}
inline int one_of_n(int n)
{
int i, r = 0;
for (i = 1; i < n; i++) if (!irand(i + 1)) r = i;
return r;
}
int main(void)
{
int i, r[10] = {0};
for (i ... |
Write a version of this Python function in C with identical behavior. | from itertools import groupby, permutations
def A036058(number):
return ''.join( str(len(list(g))) + k
for k,g in groupby(sorted(str(number), reverse=True)) )
def A036058_length(numberstring='0', printit=False):
iterations, last_three, queue_index = 1, ([None] * 3), 0
def A036058(numb... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec_t rec_t;
struct rec_t {
int depth;
rec_t * p[10];
};
rec_t root = {0, {0}};
#define USE_POOL_ALLOC
#ifdef USE_POOL_ALLOC
rec_t *tail = 0, *head = 0;
#define POOL_SIZE (1 << 20)
inline rec_t *new_rec()
{
if (head == tail) {
head = cal... |
Change the programming language of this snippet from Python to C without modifying what it does. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
... | #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three",... |
Write a version of this Python function in C with identical behavior. | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True... | #include <stdio.h>
inline int self_desc(unsigned long long xx)
{
register unsigned int d, x;
unsigned char cnt[10] = {0}, dig[10] = {0};
for (d = 0; xx > ~0U; xx /= 10)
cnt[ dig[d++] = xx % 10 ]++;
for (x = xx; x; x /= 10)
cnt[ dig[d++] = x % 10 ]++;
while(d-- && dig[x++] == cnt[d]);
return d == -1;
... |
Rewrite the snippet below in C so it works the same as the original Python code. | def prepend(n, seq):
return [n] + seq
def check_seq(pos, seq, n, min_len):
if pos > min_len or seq[0] > n:
return min_len, 0
if seq[0] == n:
return pos, 1
if pos < min_len:
return try_perm(0, pos, seq, n, min_len)
return min_len, 0
def try_perm(i, pos, seq, n, min_len):
... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
typedef struct {
int x, y;
} pair;
int* example = NULL;
int exampleLen = 0;
void reverse(int s[], int len) {
int i, j, t;
for (i = 0, j = len - 1; i < j; ++i, --j) {
t = s[i];
s[i... |
Produce a language-to-language conversion: from Python to C, same semantics. |
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3);
| #include <stdio.h>
void repeat(void (*f)(void), unsigned int n) {
while (n-->0)
(*f)();
}
void example() {
printf("Example\n");
}
int main(int argc, char *argv[]) {
repeat(example, 4);
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. |
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3);
| #include <stdio.h>
void repeat(void (*f)(void), unsigned int n) {
while (n-->0)
(*f)();
}
void example() {
printf("Example\n");
}
int main(int argc, char *argv[]) {
repeat(example, 4);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. |
bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __... | #include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>
int main(int argC,char* argV[])
{
double* arr,min,max;
char* str;
int i,len;
if(argC == 1)
printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
else{
arr = (double*)malloc((argC-1... |
Ensure the translated C code behaves exactly like the original Python snippet. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right =... |
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
|
Transform the following Python implementation into C, maintaining the same output and logic. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right =... |
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
|
Maintain the same structure and functionality when rewriting this code in C. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right =... |
count = 1;
n = 1;
limit = 100;
while (n < limit) {
k=3;
p=1;
n=n+2;
while ((k*k<=n) && (p)) {
p=n/k*k!=n;
k=k+2;
}
if (p) {
print(n, " is prime\n");
count = count + 1;
}
}
print("Total primes found: ", count, "\n");
|
Generate a C translation of this Python snippet without changing its computational steps. | >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return l... | #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
printf("%d\n", mul_inv(42, 2017));
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | import ctypes
def click():
ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)
ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)
click()
| #define WINVER 0x500
#include<windows.h>
int main()
{
int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
int x = maxX/2, y = maxY/2;
double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;
INPUT ip;
ZeroMemory(&ip,sizeof(ip));
ip.type = INPUT_MOUSE;
while(x > 5 || y < maxY... |
Please provide an equivalent version of this Python code in C. | from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b"<h1>Goodbye, World!</h1>"
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Bye-b... |
Convert the following code from Python to C, ensuring the logic remains intact. | from turtle import *
from math import *
iter = 3000
diskRatio = .5
factor = .5 + sqrt(1.25)
screen = getscreen()
(winWidth, winHeight) = screen.screensize()
x = 0.0
y = 0.0
maxRad = pow(iter,factor)/iter;
bgcolor("light blue")
hideturtle()
tracer(0, 0)
for i in range(iter+1):
r = pow(i,factor)/iter;... |
#include<graphics.h>
#include<math.h>
#define pi M_PI
void sunflower(int winWidth, int winHeight, double diskRatio, int iter){
double factor = .5 + sqrt(1.25),r,theta;
double x = winWidth/2.0, y = winHeight/2.0;
double maxRad = pow(iter,factor)/iter;
int i;
setbkcolor(LIGHTBLUE);
for(i=0;i<=iter;i++){
... |
Convert this Python snippet to C and keep its semantics consistent. | from collections import defaultdict
costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70... | #include <stdio.h>
#include <limits.h>
#define TRUE 1
#define FALSE 0
#define N_ROWS 4
#define N_COLS 5
typedef int bool;
int supply[N_ROWS] = { 50, 60, 50, 50 };
int demand[N_COLS] = { 30, 20, 70, 30, 60 };
int costs[N_ROWS][N_COLS] = {
{ 16, 16, 13, 22, 17 },
{ 14, 14, 13, 19, 15 },
{ 19, 19, 20, 23, ... |
Port the provided Python code into C while preserving the original functionality. | from collections import defaultdict
costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70... | #include <stdio.h>
#include <limits.h>
#define TRUE 1
#define FALSE 0
#define N_ROWS 4
#define N_COLS 5
typedef int bool;
int supply[N_ROWS] = { 50, 60, 50, 50 };
int demand[N_COLS] = { 30, 20, 70, 30, 60 };
int costs[N_ROWS][N_COLS] = {
{ 16, 16, 13, 22, 17 },
{ 14, 14, 13, 19, 15 },
{ 19, 19, 20, 23, ... |
Rewrite the snippet below in C so it works the same as the original Python code. |
from math import sqrt, cos, exp
DEG = 0.017453292519943295769236907684886127134
RE = 6371000
dd = 0.001
FIN = 10000000
def rho(a):
return exp(-a / 8500.0)
def height(a, z, d):
return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG... | #include <math.h>
#include <stdio.h>
#define DEG 0.017453292519943295769236907684886127134
#define RE 6371000.0
#define DD 0.001
#define FIN 10000000.0
static double rho(double a) {
return exp(-a / 8500.0);
}
static double height(double a, double z, double d) {
double aa = RE + a;
... |
Convert this Python snippet to C and keep its semantics consistent. | import datetime
weekDays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
thisXMas = datetime.date(2021,12,25)
thisXMasDay = thisXMas.weekday()
thisXMasDayAsString = weekDays[thisXMasDay]
print("This year's Christmas is on a {}".format(thisXMasDayAsString))
nextNewYear = datetime.date(2022,... | #define _XOPEN_SOURCE
#include <stdio.h>
#include <time.h>
int main() {
struct tm t[2];
strptime("2021-12-25", "%F", &t[0]);
strptime("2022-01-01", "%F", &t[1]);
for (int i=0; i<2; i++) {
char buf[32];
strftime(buf, 32, "%F is a %A", &t[i]);
puts(buf);
}
return 0;
}
|
Can you help me rewrite this code in C instead of Python, keeping it the same logically? |
from itertools import islice
from fractions import Fraction
from functools import reduce
try:
from itertools import izip as zip
except:
pass
def head(n):
return lambda seq: islice(seq, n)
def pipe(gen, *cmds):
return reduce(lambda gen, cmd: cmd(gen), cmds, gen)
def sinepower():
n = 0... | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
enum fps_type {
FPS_CONST = 0,
FPS_ADD,
FPS_SUB,
FPS_MUL,
FPS_DIV,
FPS_DERIV,
FPS_INT,
};
typedef struct fps_t *fps;
typedef struct fps_t {
int type;
fps s1, s2;
double a0;
} fps_t... |
Maintain the same structure and functionality when rewriting this code in C. |
def isowndigitspowersum(integer):
digits = [int(c) for c in str(integer)]
exponent = len(digits)
return sum(x ** exponent for x in digits) == integer
print("Own digits power sums for N = 3 to 9 inclusive:")
for i in range(100, 1000000000):
if isowndigitspowersum(i):
print(i)
| #include <stdio.h>
#include <math.h>
#define MAX_DIGITS 9
int digits[MAX_DIGITS];
void getDigits(int i) {
int ix = 0;
while (i > 0) {
digits[ix++] = i % 10;
i /= 10;
}
}
int main() {
int n, d, i, max, lastDigit, sum, dp;
int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};
... |
Convert this Python block to C, preserving its control flow and logic. | def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
... | #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
#define da_dim(name, type) type *name = NULL; \
int _qy_ ## name ## _p = 0; \
int ... |
Ensure the translated C code behaves exactly like the original Python snippet. | def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
... | #include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
#define da_dim(name, type) type *name = NULL; \
int _qy_ ## name ## _p = 0; \
int ... |
Maintain the same structure and functionality when rewriting this code in C. | def KlarnerRado(N):
K = [1]
for i in range(N):
j = K[i]
firstadd, secondadd = 2 * j + 1, 3 * j + 1
if firstadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < firstadd < K[pos + 1]:
K.insert(pos + 1, firstadd)
br... | #include <stdio.h>
#define ELEMENTS 10000000U
void make_klarner_rado(unsigned int *dst, unsigned int n) {
unsigned int i, i2 = 0, i3 = 0;
unsigned int m, m2 = 1, m3 = 1;
for (i = 0; i < n; ++i) {
dst[i] = m = m2 < m3 ? m2 : m3;
if (m2 == m) m2 = dst[i2++] << 1 | 1;
if (m3 == m) m3... |
Produce a functionally identical C code for the snippet given in Python. | def KlarnerRado(N):
K = [1]
for i in range(N):
j = K[i]
firstadd, secondadd = 2 * j + 1, 3 * j + 1
if firstadd < K[-1]:
for pos in range(len(K)-1, 1, -1):
if K[pos] < firstadd < K[pos + 1]:
K.insert(pos + 1, firstadd)
br... | #include <stdio.h>
#define ELEMENTS 10000000U
void make_klarner_rado(unsigned int *dst, unsigned int n) {
unsigned int i, i2 = 0, i3 = 0;
unsigned int m, m2 = 1, m3 = 1;
for (i = 0; i < n; ++i) {
dst[i] = m = m2 < m3 ? m2 : m3;
if (m2 == m) m2 = dst[i2++] << 1 | 1;
if (m3 == m) m3... |
Rewrite the snippet below in C so it works the same as the original Python code. | def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
pts = []
for i in range(n+1):
t = i / n
a = (1. - t)**3
b = 3. * t * (1. - t)**2
c = 3.0 * t**2 * (1.0 - t)
d = t**3
x = int(a * x0 + b * x1 + c * x2 + d * x3)
y = int(a * y0 + b * y1 + ... | void cubic_bezier(
image img,
unsigned int x1, unsigned int y1,
unsigned int x2, unsigned int y2,
unsigned int x3, unsigned int y3,
unsigned int x4, unsigned int y4,
color_component r,
color_component g,
color_component b );
|
Write the same algorithm in C as shown in this Python implementation. | tutor = False
def pancakesort(data):
if len(data) <= 1:
return data
if tutor: print()
for size in range(len(data), 1, -1):
maxindex = max(range(size), key=data.__getitem__)
if maxindex+1 != size:
if maxindex != 0:
if tutor: p... | int pancake_sort(int *list, unsigned int length)
{
if(length<2)
return 0;
int i,a,max_num_pos,moves;
moves=0;
for(i=length;i>1;i--)
{
max_num_pos=0;
for(a=0;a<i;a++)
{
if(list[a]>list[max_num_pos])
max_num_pos=a;
}
... |
Rewrite this program in C while keeping its functionality equivalent to the Python version. |
from random import seed,randint
from datetime import datetime
seed(str(datetime.now()))
largeNum = [randint(1,9)]
for i in range(1,1000):
largeNum.append(randint(0,9))
maxNum,minNum = 0,99999
for i in range(0,994):
num = int("".join(map(str,largeNum[i:i+5])))
if num > maxNum:
maxNum = num
... | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define DIGITS 1000
#define NUMSIZE 5
uint8_t randomDigit() {
uint8_t d;
do {d = rand() & 0xF;} while (d >= 10);
return d;
}
int numberAt(uint8_t *d, int size) {
int acc = 0;
while (size--) acc = 10*acc + *d++;
retur... |
Generate an equivalent C version of this Python code. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def digSum(n, b):
s = 0
while n:
s += (n % b)
n = n // b
return s
if __name__ == '__main__':
for n in range(11, 99):
if isPrime(digSum(n**3, 10)) an... | #include <stdio.h>
#include <stdbool.h>
int digit_sum(int n) {
int sum;
for (sum = 0; n; n /= 10) sum += n % 10;
return sum;
}
bool prime(int n) {
if (n<4) return n>=2;
for (int d=2; d*d <= n; d++)
if (n%d == 0) return false;
return true;
}
int main() {
for (int i=1; i<100; i++)
... |
Produce a functionally identical C code for the snippet given in Python. | from numpy import log
def sieve_of_Sundaram(nth, print_all=True):
assert nth > 0, "nth must be a positive integer"
k = int((2.4 * nth * log(nth)) // 2)
integers_list = [True] * k
for i in range(1, k):
j = i
while i + j + 2 * i * j < k:
integers_list[i + j + 2 * i * j]... | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int nprimes = 1000000;
int nmax = ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));
int i, j, m, k; int *a;
k = (nmax-2)/2;
a = (int *)calloc(k + 1, sizeof(int));
for(i = 0; i <= k; i++)a[i] = 2*i... |
Preserve the algorithm and functionality while converting the code from Python to C. | assert 1.008 == molar_mass('H')
assert 2.016 == molar_mass('H2')
assert 18.015 == molar_mass('H2O')
assert 34.014 == molar_mass('H2O2')
assert 34.014 == molar_mass('(HO)2')
assert 142.036 == molar_mass('Na2SO4')
assert ... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char *string;
typedef struct node_t {
string symbol;
double weight;
struct node_t *next;
} node;
node *make_node(string symbol, double weight) {
node *nptr = malloc(sizeof(node));
if (nptr) {
nptr->symbol = symbol;
... |
Convert this Python snippet to C and keep its semantics consistent. | import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
| #include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld);
|
Write a version of this Python function in C with identical behavior. |
from itertools import dropwhile, takewhile
def nnPeers(n):
def p(x):
return n == x
def go(xs):
fromFirstMatch = list(dropwhile(
lambda v: not p(v),
xs
))
ns = list(takewhile(p, fromFirstMatch))
rest = fromFirstMatch[len(ns):]
re... | #include <stdio.h>
#include <stdbool.h>
bool three_3s(const int *items, size_t len) {
int threes = 0;
while (len--)
if (*items++ == 3)
if (threes<3) threes++;
else return false;
else if (threes != 0 && threes != 3)
return false;
return true;
}
void... |
Rewrite the snippet below in C so it works the same as the original Python code. | from operator import itemgetter
DEBUG = False
def spermutations(n):
sign = 1
p = [[i, 0 if i == 0 else -1]
for i in range(n)]
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p):
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) i... | #include<stdlib.h>
#include<string.h>
#include<stdio.h>
int flag = 1;
void heapPermute(int n, int arr[],int arrLen){
int temp;
int i;
if(n==1){
printf("\n[");
for(i=0;i<arrLen;i++)
printf("%d,",arr[i]);
printf("\b] Sign : %d",flag);
flag*=-1;
}
else{
for(i=0;i<n-1;i++){
heapPermute(n-1,ar... |
Write the same algorithm in C as shown in this Python implementation. |
from itertools import count, islice
def a131382():
return (
elemIndex(x)(
productDigitSums(x)
) for x in count(1)
)
def productDigitSums(n):
return (digitSum(n * x) for x in count(0))
def main():
print(
table(10)([
str(x) for x ... | #include <stdio.h>
unsigned digit_sum(unsigned n) {
unsigned sum = 0;
do { sum += n % 10; }
while(n /= 10);
return sum;
}
unsigned a131382(unsigned n) {
unsigned m;
for (m = 1; n != digit_sum(m*n); m++);
return m;
}
int main() {
unsigned n;
for (n = 1; n <= 70; n++) {
prin... |
Rewrite the snippet below in C so it works the same as the original Python code. | def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
... | #include <stdio.h>
#include <math.h>
#include <string.h>
#define N 2200
int main(int argc, char **argv){
int a,b,c,d;
int r[N+1];
memset(r,0,sizeof(r));
for(a=1; a<=N; a++){
for(b=a; b<=N; b++){
int aabb;
if(a&1 && b&1) continue;
aabb=a*a + b*b;
for(c=b; c<=N; c++){
int aabbcc=aabb +... |
Can you help me rewrite this code in C instead of Python, keeping it the same logically? | MULTIPLICATION_TABLE = [
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
(3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
(4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
(5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
(6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
(7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
(8,... | #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
static const int d[][10] = {
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},
{2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},
{4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},
{6... |
Ensure the translated C code behaves exactly like the original Python snippet. | print("working...")
print("Steady squares under 10.000 are:")
limit = 10000
for n in range(1,limit):
nstr = str(n)
nlen = len(nstr)
square = str(pow(n,2))
rn = square[-nlen:]
if nstr == rn:
print(str(n) + " " + str(square))
print("done...")
| #include <stdio.h>
#include <stdbool.h>
bool steady(int n)
{
int mask = 1;
for (int d = n; d != 0; d /= 10)
mask *= 10;
return (n * n) % mask == n;
}
int main()
{
for (int i = 1; i < 10000; i++)
if (steady(i))
printf("%4d^2 = %8d\n", i, i * i);
return 0;
}
|
Convert this Python block to C, preserving its control flow and logic. | def reverse(n, base):
r = 0
while n > 0:
r = r*base + n%base
n = n//base
return r
def palindrome(n, base):
return n == reverse(n, base)
cnt = 0
for i in range(25000):
if all(palindrome(i, base) for base in (2,4,16)):
cnt += 1
print("{:5}".format(i), end=" \n... | #include <stdio.h>
#define MAXIMUM 25000
int reverse(int n, int base) {
int r;
for (r = 0; n; n /= base)
r = r*base + n%base;
return r;
}
int palindrome(int n, int base) {
return n == reverse(n, base);
}
int main() {
int i, c = 0;
for (i = 0; i < MAXIMUM; i++) {
if (palin... |
Convert the following code from Python to C, ensuring the logic remains intact. |
from numpy import mean
from random import sample
def gen_long_stairs(start_step, start_length, climber_steps, add_steps):
secs, behind, total = 0, start_step, start_length
while True:
behind += climber_steps
behind += sum([behind > n for n in sample(range(total), add_steps)])
total +=... | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int trial, secs_tot=0, steps_tot=0;
int sbeh, slen, wiz, secs;
time_t t;
srand((unsigned) time(&t));
printf( "Seconds steps behind steps ahead\n" );
for( trial=1;trial<=10000;trial++ ... |
Can you help me rewrite this code in C instead of Python, keeping it the same logically? | import curses
from random import randint
stdscr = curses.initscr()
for rows in range(10):
line = ''.join([chr(randint(41, 90)) for i in range(10)])
stdscr.addstr(line + '\n')
icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8")
stdscr.move(irow, icol + 10)
stdscr.addstr('Ch... | #include <windows.h>
#include <wchar.h>
int
main()
{
CONSOLE_SCREEN_BUFFER_INFO info;
COORD pos;
HANDLE conout;
long len;
wchar_t c;
conout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
0, NULL);
if (conout == INVALID_HANDLE_VALUE)
... |
Keep all operations the same but rewrite the snippet in C. | seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
| #include<stdio.h>
long long seed;
long long random(){
seed = seed * seed / 1000 % 1000000;
return seed;
}
int main(){
seed = 675248;
for(int i=1;i<=5;i++)
printf("%lld\n",random());
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
| #include<stdio.h>
long long seed;
long long random(){
seed = seed * seed / 1000 % 1000000;
return seed;
}
int main(){
seed = 675248;
for(int i=1;i<=5;i++)
printf("%lld\n",random());
return 0;
}
|
Port the provided Python code into C while preserving the original functionality. | seed = 675248
def random():
global seed
seed = int(str(seed ** 2).zfill(12)[3:9])
return seed
for _ in range(5):
print(random())
| #include<stdio.h>
long long seed;
long long random(){
seed = seed * seed / 1000 % 1000000;
return seed;
}
int main(){
seed = 675248;
for(int i=1;i<=5;i++)
printf("%lld\n",random());
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. |
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define strcomp(X, Y) strcasecmp(X, Y)
struct option
{ const char *name, *value;
int flag; };
struct option updlist[] =
{ { "NEEDSPEELING", NULL },
{ "SEEDSREMOVED", "" },
{ "NUMBEROFBANANAS", "1024" },
{ "NUMBEROFSTRAWBERRIES", "62000" },
{ NULL... |
Write a version of this Python function in C with identical behavior. |
from PIL import Image, ImageFilter
if __name__=="__main__":
im = Image.open("test.jpg")
kernelValues = [-2,-1,0,-1,1,1,0,1,2]
kernel = ImageFilter.Kernel((3,3), kernelValues)
im2 = im.filter(kernel)
im2.show()
| image filter(image img, double *K, int Ks, double, double);
|
Write the same algorithm in C as shown in this Python implementation. |
import numpy
import pprint
h = [
[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]],
[[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]
f = [
[[-9, 5, -8], [3, 5, 1]],
[[-1, -7, 2], [-5, -6, 6]],
[[8, 5, 8],[-2, -6, -4]]]
g = [
[
[54, 42, 53, -42, 85, -72],
[... | #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 ... |
Generate a C translation of this Python snippet without changing its computational steps. | from itertools import product
def gen_dict(n_faces, n_dice):
counts = [0] * ((n_faces + 1) * n_dice)
for t in product(range(1, n_faces + 1), repeat=n_dice):
counts[sum(t)] += 1
return counts, n_faces ** n_dice
def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
c1, p1 = gen_dict(n_s... | #include <stdio.h>
#include <stdint.h>
typedef uint32_t uint;
typedef uint64_t ulong;
ulong ipow(const uint x, const uint y) {
ulong result = 1;
for (uint i = 1; i <= y; i++)
result *= x;
return result;
}
uint min(const uint x, const uint y) {
return (x < y) ? x : y;
}
void throw_die(const u... |
Convert this Python block to C, preserving its control flow and logic. | from logpy import *
from logpy.core import lall
import time
def lefto(q, p, list):
return membero((q,p), zip(list, list[1:]))
def nexto(q, p, list):
return conde([lefto(q, p, list)], [lefto(p, q, list)])
houses = var()
zebraRules = lall(
(eq, (var(), var(), var(), var(), var()), houses),
(memb... | #include <stdio.h>
#include <string.h>
enum HouseStatus { Invalid, Underfull, Valid };
enum Attrib { C, M, D, A, S };
enum Colors { Red, Green, White, Yellow, Blue };
enum Mans { English, Swede, Dane, German, Norwegian };
enum Drinks { Tea, Coffee, Milk, Beer, Water };
enum Animals { Dog, Birds, Cats, Horse, Zebra ... |
Maintain the same structure and functionality when rewriting this code in C. |
from operator import attrgetter
from typing import Iterator
import mwclient
URL = 'www.rosettacode.org'
API_PATH = '/mw/'
def unimplemented_tasks(language: str,
*,
url: str,
api_path: str) -> Iterator[str]:
site = mwclient.Site(url, p... |
#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 *m... |
Convert this Python block to C, preserving its control flow and logic. |
from operator import attrgetter
from typing import Iterator
import mwclient
URL = 'www.rosettacode.org'
API_PATH = '/mw/'
def unimplemented_tasks(language: str,
*,
url: str,
api_path: str) -> Iterator[str]:
site = mwclient.Site(url, p... |
#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 *m... |
Maintain the same structure and functionality when rewriting this code in C. |
pal = [0] * 128
r = 42
g = 84
b = 126
rd = gd = bd = False
def setup():
global buffer
size(600, 600)
frameRate(25)
buffer = [None] * width * height
for x in range(width):
for y in range(width):
value = int(((128 + (128 * sin(x / 32.0)))
+ (128 + (128 *... | #include<windows.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<math.h>
#define pi M_PI
int main()
{
CONSOLE_SCREEN_BUFFER_INFO info;
int cols, rows;
time_t t;
int i,j;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
cols = info.srWindow.Right - info.srWindow.Lef... |
Produce a functionally identical C code for the snippet given in Python. |
pal = [0] * 128
r = 42
g = 84
b = 126
rd = gd = bd = False
def setup():
global buffer
size(600, 600)
frameRate(25)
buffer = [None] * width * height
for x in range(width):
for y in range(width):
value = int(((128 + (128 * sin(x / 32.0)))
+ (128 + (128 *... | #include<windows.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
#include<math.h>
#define pi M_PI
int main()
{
CONSOLE_SCREEN_BUFFER_INFO info;
int cols, rows;
time_t t;
int i,j;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
cols = info.srWindow.Right - info.srWindow.Lef... |
Write the same algorithm in C as shown in this Python implementation. |
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"
example1 = "goodbye"
| int j;
|
Maintain the same structure and functionality when rewriting this code in C. |
from functools import reduce
from operator import add
def wordleScore(target, guess):
return mapAccumL(amber)(
*first(charCounts)(
mapAccumL(green)(
[], zip(target, guess)
)
)
)[1]
def green(residue, tg):
t, g = tg
return (residue... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void wordle(const char *answer, const char *guess, int *result) {
int i, ix, n = strlen(guess);
char *ptr;
if (n != strlen(answer)) {
printf("The words must be of the same length.\n");
exit(1);
}
char answer2[n+1];
strcp... |
Convert this Python block to C, preserving its control flow and logic. | from PIL import Image
if __name__=="__main__":
im = Image.open("frog.png")
im2 = im.quantize(16)
im2.show()
| typedef struct oct_node_t oct_node_t, *oct_node;
struct oct_node_t{
uint64_t r, g, b;
int count, heap_idx;
oct_node kids[8], parent;
unsigned char n_kids, kid_idx, flags, depth;
};
inline int cmp_node(oct_node a, oct_node b)
{
if (a->n_kids < b->n_kids) return -1;
if (a->n_kids > b->n_kids) return 1;
int ac... |
Write the same algorithm in C as shown in this Python implementation. | import ast
class CallCountingVisitor(ast.NodeVisitor):
def __init__(self):
self.calls = {}
def visit_Call(self, node):
if isinstance(node.func, ast.Name):
fun_name = node.func.id
call_count = self.calls.get(fun_name, 0)
self.calls[fun_name] = call_count + 1... | #define _POSIX_SOURCE
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stddef.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct functionInfo {
char* name;
int timesCalled;
char marked;
};
void addToList(... |
Please provide an equivalent version of this Python code in C. |
u = 'abcdé'
print(ord(u[-1]))
| #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
wchar_t poker[] = L"♥♦♣♠";
wchar_t four_two[] = L"\x56db\x5341\x4e8c";
int main() {
if (!setlocale(LC_CTYPE, "")) {
fprintf(stderr, "Locale failure, check your env vars\n");
return 1;
}
#ifdef __STDC_ISO_10646__
printf(... |
Translate the given Python code snippet into C without altering its behavior. |
u = 'abcdé'
print(ord(u[-1]))
| #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
wchar_t poker[] = L"♥♦♣♠";
wchar_t four_two[] = L"\x56db\x5341\x4e8c";
int main() {
if (!setlocale(LC_CTYPE, "")) {
fprintf(stderr, "Locale failure, check your env vars\n");
return 1;
}
#ifdef __STDC_ISO_10646__
printf(... |
Ensure the translated C code behaves exactly like the original Python snippet. |
from PIL import Image
im = Image.open("boxes_1.jpg")
im.save("boxes_1v2.ppm")
| image read_image(const char *name);
|
Translate the given Python code snippet into C without altering its behavior. | from ctypes import Structure, c_int
rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg"
"_11 SCD SCS STD TC SRD RC"
"_18 SRS DTR SQD RI DRS XTC" ).split()
class RS232_9pin(Structure):
_fields_ = [(__, c_int, 1) fo... | struct RS232_data
{
unsigned carrier_detect : 1;
unsigned received_data : 1;
unsigned transmitted_data : 1;
unsigned data_terminal_ready : 1;
unsigned signal_ground : 1;
unsigned data_set_ready : 1;
unsigned request_to_send : 1;
unsigned clear_to_send :... |
Write the same algorithm in C as shown in this Python implementation. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == "__main__":
n = 0
num = 0
print('The first 20 pairs of numbers whose sum is prime:')
while True:
n += 1
suma = 2*n+1
if isPrime(suma... | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
void primeSieve(int *c, int limit, bool processEven, bool primesOnly) {
int i, ix, p, p2;
limit++;
c[0] = TRUE;
c[1] = TRUE;
if (processEven) {
for (i = 4; i < limit; i +=2) c[i] = TR... |
Produce a functionally identical C code for the snippet given in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == "__main__":
n = 0
num = 0
print('The first 20 pairs of numbers whose sum is prime:')
while True:
n += 1
suma = 2*n+1
if isPrime(suma... | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
void primeSieve(int *c, int limit, bool processEven, bool primesOnly) {
int i, ix, p, p2;
limit++;
c[0] = TRUE;
c[1] = TRUE;
if (processEven) {
for (i = 4; i < limit; i +=2) c[i] = TR... |
Translate the given Python code snippet into C without altering its behavior. | def perta(atomic) -> (int, int):
NOBLES = 2, 10, 18, 36, 54, 86, 118
INTERTWINED = 0, 0, 0, 0, 0, 57, 89
INTERTWINING_SIZE = 14
LINE_WIDTH = 18
prev_noble = 0
for row, noble in enumerate(NOBLES):
if atomic <= noble:
nb_elem = noble - prev_noble
rank = atomi... | #include <gadget/gadget.h>
LIB_GADGET_START
GD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );
MT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );
int select_box_chemical_elem( RDS(MT_CELL, Elements) );
void put_information(RDS( MT_CELL, elem), int i);
Main
GD_VIDEO table;... |
Maintain the same structure and functionality when rewriting this code in C. | import static java.lang.Math.*;
public class RayCasting {
static boolean intersects(int[] A, int[] B, double[] P) {
if (A[1] > B[1])
return intersects(B, A, P);
if (P[1] == A[1] || P[1] == B[1])
P[1] += 0.0001;
if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B... | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;
#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}
#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }
BIN_V(sub, a.x - b.x, a.y - ... |
Convert this Java block to C, preserving its control flow and logic. | import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c =... | #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x)... |
Write the same code in C as shown below in Java. | import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c =... | #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x)... |
Maintain the same structure and functionality when rewriting this code in C. | import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c =... | #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x)... |
Preserve the algorithm and functionality while converting the code from Java to C. | public class CountSubstring {
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
public static void main(String[] args){
System.out.println(countSubstring("th", "the three truths"));
System.out.println(countSubstring("aba... | #include <stdio.h>
#include <string.h>
int match(const char *s, const char *p, int overlap)
{
int c = 0, l = strlen(p);
while (*s != '\0') {
if (strncmp(s++, p, l)) continue;
if (!overlap) s += l - 1;
c++;
}
return c;
}
int main()
{
... |
Port the following code from Java to C with equivalent syntax and logic. | public class PrimeDigits {
private static boolean primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false;
}
n /= 10;
sum += r;
}
return... | #include <stdbool.h>
#include <stdio.h>
bool primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
switch (r) {
case 2:
case 3:
case 5:
case 7:
break;
default:
return false;
}
n /= 10;
sum +... |
Write the same algorithm in C as shown in this Java implementation. | public class PrimeDigits {
private static boolean primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false;
}
n /= 10;
sum += r;
}
return... | #include <stdbool.h>
#include <stdio.h>
bool primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
switch (r) {
case 2:
case 3:
case 5:
case 7:
break;
default:
return false;
}
n /= 10;
sum +... |
Convert this Java snippet to C and keep its semantics consistent. | public class Compare
{
public static void compare (String A, String B)
{
if (A.equals(B))
System.debug(A + ' and ' + B + ' are lexically equal.');
else
System.debug(A + ' and ' + B + ' are not lexically equal.');
if (A.equalsIgnoreCase(B))
Sy... |
if (strcmp(a,b)) action_on_equality();
|
Translate this program into C but keep the logic exactly as in Java. | import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
... | #include <stdio.h>
#include <time.h>
#define note_file "NOTES.TXT"
int main(int argc, char**argv)
{
FILE *note = 0;
time_t tm;
int i;
char *p;
if (argc < 2) {
if ((note = fopen(note_file, "r")))
while ((i = fgetc(note)) != EOF)
putchar(i);
} else if ((note = fopen(note_file, "a"))) {
tm = time(0);
... |
Write the same code in C as shown below in Java. | import static java.lang.Math.*;
public class Test {
final static int N = 32;
final static int N2 = (N * (N - 1) / 2);
final static double STEP = 0.05;
static double[] xval = new double[N];
static double[] t_sin = new double[N];
static double[] t_cos = new double[N];
static double[] t_tan =... | #include <stdio.h>
#include <string.h>
#include <math.h>
#define N 32
#define N2 (N * (N - 1) / 2)
#define STEP .05
double xval[N], t_sin[N], t_cos[N], t_tan[N];
double r_sin[N2], r_cos[N2], r_tan[N2];
double rho(double *x, double *y, double *r, int i, int n)
{
if (n < 0) return 0;
if (!n) return y[i];
int ... |
Keep all operations the same but rewrite the snippet in C. | import java.util.*;
public class FWord {
private String fWord0 = "";
private String fWord1 = "";
private String nextFWord () {
final String result;
if ( "".equals ( fWord1 ) ) result = "1";
else if ( "".equals ( fWord0 ) ) result = "0";
else ... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void print_headings()
{
printf("%2s", "N");
printf(" %10s", "Length");
printf(" %-20s", "Entropy");
printf(" %-40s", "Word");
printf("\n");
}
double calculate_entropy(int ones, int zeros)
{
double result = 0;
int total = ones + zero... |
Translate this program into C but keep the logic exactly as in Java. | import java.util.*;
public class FWord {
private String fWord0 = "";
private String fWord1 = "";
private String nextFWord () {
final String result;
if ( "".equals ( fWord1 ) ) result = "1";
else if ( "".equals ( fWord0 ) ) result = "0";
else ... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void print_headings()
{
printf("%2s", "N");
printf(" %10s", "Length");
printf(" %-20s", "Entropy");
printf(" %-40s", "Word");
printf("\n");
}
double calculate_entropy(int ones, int zeros)
{
double result = 0;
int total = ones + zero... |
Transform the following Java implementation into C, maintaining the same output and logic. | import java.text.DecimalFormat;
public class AnglesNormalizationAndConversion {
public static void main(String[] args) {
DecimalFormat formatAngle = new DecimalFormat("######0.000000");
DecimalFormat formatConv = new DecimalFormat("###0.0000");
System.out.printf(" ... | #define PI 3.141592653589793
#define TWO_PI 6.283185307179586
double normalize2deg(double a) {
while (a < 0) a += 360;
while (a >= 360) a -= 360;
return a;
}
double normalize2grad(double a) {
while (a < 0) a += 400;
while (a >= 400) a -= 400;
return a;
}
double normalize2mil(double a) {
while (a < 0) a +... |
Rewrite this program in C while keeping its functionality equivalent to the Java version. | public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/");
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j];... | #include <stdio.h>
int common_len(const char *const *names, int n, char sep)
{
int i, pos;
for (pos = 0; ; pos++) {
for (i = 0; i < n; i++) {
if (names[i][pos] != '\0' &&
names[i][pos] == names[0][pos])
continue;
while (pos > 0 && names[0][--pos] != sep);
return pos;
}
}
return 0;
}
in... |
Change the following Java code into C without altering its purpose. | public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/");
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j];... | #include <stdio.h>
int common_len(const char *const *names, int n, char sep)
{
int i, pos;
for (pos = 0; ; pos++) {
for (i = 0; i < n; i++) {
if (names[i][pos] != '\0' &&
names[i][pos] == names[0][pos])
continue;
while (pos > 0 && names[0][--pos] != sep);
return pos;
}
}
return 0;
}
in... |
Produce a functionally identical C code for the snippet given in Java. | import static java.lang.Math.abs;
import java.util.*;
import java.util.function.IntSupplier;
public class Test {
static void distCheck(IntSupplier f, int nRepeats, double delta) {
Map<Integer, Integer> counts = new HashMap<>();
for (int i = 0; i < nRepeats; i++)
counts.compute(f.getAs... | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
inline int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
inline int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
int check(int (*gen)(), int... |
Translate the given Java code snippet into C without altering its behavior. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= ... | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(... |
Please provide an equivalent version of this Java code in C. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= ... | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(... |
Generate an equivalent C version of this Java code. | import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= ... | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct stirling_cache_tag {
int max;
int* values;
} stirling_cache;
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return sc->values[n*(... |
Ensure the translated C code behaves exactly like the original Java snippet. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<I... | #include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equ... |
Convert the following code from Java to C, ensuring the logic remains intact. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<I... | #include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equ... |
Can you help me rewrite this code in C instead of Java, keeping it the same logically? |
Object foo = new Object();
int[] fooArray = new int[size];
int x = 0;
| #include <stdlib.h>
#define SIZEOF_MEMB (sizeof(int))
#define NMEMB 100
int main()
{
int *ints = malloc(SIZEOF_MEMB*NMEMB);
ints = realloc(ints, sizeof(int)*(NMEMB+1));
int *int2 = calloc(NMEMB, SIZEOF_MEMB);
free(ints); free(int2);
return 0;
}
|
Produce a functionally identical C code for the snippet given in Java. | public class Count{
public static void main(String[] args){
for(long i = 1; ;i++) System.out.println(i);
}
}
| #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.