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), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
#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.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
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), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
#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.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
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/2) dth = pi / ntx for jx in xrange(nimx): for iy in xrange(mimy): col = pim[jx, iy] if col == 255: continue for jtx in xrange(ntx): th = dth * jtx r = jx*cos(th) + iy*sin(th) iry = mry/2 + int(r/dr+0.5) phim[jtx, iry] -= 1 return him def test(): "Test Hough transform with pentagon." im = Image.open("pentagon.png").convert("L") him = hough(im) him.save("ho5.bmp") if __name__ == "__main__": test()
#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[3]); int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]); int threads = 0; if(argc > 5) threads = atoi(argv[5]); char titleBuffer[200]; SLTimer t; CImg<int> image(fileName.c_str()); int imageDimensions[] = {image.height(), image.width(), 0}; Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions); Sequence< Sequence<int> > result; sl_init(threads); t.start(); sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result); t.stop(); CImg<int> resultImage(result[1].size(), result.size()); for(int y = 0; y < result.size(); y++) for(int x = 0; x < result[y+1].size(); x++) resultImage(x,result.size() - 1 - y) = result[y+1][x+1]; sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0", image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime()); resultImage.display(titleBuffer); sl_done(); return 0; }
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 hh = 0.5*h gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) return gamax/gamma_spounge(a) c = None def gamma_spounge( z): global c a = 12 if c is None: k1_factrl = 1.0 c = [] c.append(math.sqrt(2.0*math.pi)) for k in range(1,a): c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) k1_factrl *= -k accm = c[0] for k in range(1,a): accm += c[k] / (z+k) accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) return accm/z; def chi2UniformDistance( dataSet ): expected = sum(dataSet)*1.0/len(dataSet) cntrd = (d-expected for d in dataSet) return sum(x*x for x in cntrd)/expected def chi2Probability(dof, distance): return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) def chi2IsUniform(dataSet, significance): dof = len(dataSet)-1 dist = chi2UniformDistance(dataSet) return chi2Probability( dof, dist ) > significance dset1 = [ 199809, 200665, 199607, 200270, 199649 ] dset2 = [ 522573, 244456, 139979, 71531, 21461 ] for ds in (dset1, dset2): print "Data set:", ds dof = len(ds)-1 distance =chi2UniformDistance(ds) print "dof: %d distance: %.4f" % (dof, distance), prob = chi2Probability( dof, distance) print "probability: %.4f"%prob, print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
#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 (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
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 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
#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 (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
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 - 1)) + v2**2 / (n2**2 * (n2 - 1))) p = 2 * sp.stats.t.cdf(-abs(t), df) return t, df, p welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9])) (-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
#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 (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
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_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
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++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
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_set): 'Recursive topological extractor' _sofar += [tops] _sofar_set.union(tops) depends = reduce(set.union, (data.get(top, set()) for top in tops)) if depends: _topx(data, depends, _sofar, _sofar_set) ordered, accum = [], set() for s in _sofar[::-1]: ordered += [sorted(s - accum)] accum |= s return ordered def printorder(order): 'Prettyprint topological ordering' if order: print("First: " + ', '.join(str(s) for s in order[0])) for o in order[1:]: print(" Then: " + ', '.join(str(s) for s in o)) def toplevels(data): for k, v in data.items(): v.discard(k) dependents = reduce(set.union, data.values()) return set(data.keys()) - dependents if __name__ == '__main__': data = dict( top1 = set('ip1 des1 ip2'.split()), top2 = set('ip2 des1 ip3'.split()), des1 = set('des1a des1b des1c'.split()), des1a = set('des1a1 des1a2'.split()), des1c = set('des1c1 extra1'.split()), ip2 = set('ip2a ip2b ip2c ipcommon'.split()), ip1 = set('ip1a ipcommon extra1'.split()), ) tops = toplevels(data) print("The top levels of the dependency graph are: " + ' '.join(tops)) for t in sorted(tops): print("\nThe compile order for top level: %s is..." % t) printorder(topx(data, set([t]))) if len(tops) > 1: print("\nThe compile order for top levels: %s is..." % ' and '.join(str(s) for s in sorted(tops)) ) printorder(topx(data, tops))
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++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
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 == '\\' and len(s) > 1: s, c = s[1:], c + s[1] out, s = [a+c for a in out], s[1:] return out,s def getgroup(s, depth): out, comma = [], False while s: g,s = getitem(s, depth) if not s: break out += g if s[0] == '}': if comma: return out, s[1:] return ['{' + a + '}' for a in out], s[1:] if s[0] == ',': comma,s = True, s[1:] return None for s in .split('\n'): print "\n\t".join([s] + getitem(s)[0]) + "\n"
#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 { string str; node *root; } data; node *next; }; node *allocate_node(enum tag_t tag) { node *n = malloc(sizeof(node)); if (n == NULL) { fprintf(stderr, "Failed to allocate node for tag: %d\n", tag); exit(1); } n->tag = tag; n->next = NULL; return n; } node *make_leaf(string str) { node *n = allocate_node(NODE_LEAF); n->data.str = str; return n; } node *make_tree() { node *n = allocate_node(NODE_TREE); n->data.root = NULL; return n; } node *make_seq() { node *n = allocate_node(NODE_SEQ); n->data.root = NULL; return n; } void deallocate_node(node *n) { if (n == NULL) { return; } deallocate_node(n->next); n->next = NULL; if (n->tag == NODE_LEAF) { free(n->data.str); n->data.str = NULL; } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) { deallocate_node(n->data.root); n->data.root = NULL; } else { fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag); exit(1); } free(n); } void append(node *root, node *elem) { if (root == NULL) { fprintf(stderr, "Cannot append to uninitialized node."); exit(1); } if (elem == NULL) { return; } if (root->tag == NODE_SEQ || root->tag == NODE_TREE) { if (root->data.root == NULL) { root->data.root = elem; } else { node *it = root->data.root; while (it->next != NULL) { it = it->next; } it->next = elem; } } else { fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag); exit(1); } } size_t count(node *n) { if (n == NULL) { return 0; } if (n->tag == NODE_LEAF) { return 1; } if (n->tag == NODE_TREE) { size_t sum = 0; node *it = n->data.root; while (it != NULL) { sum += count(it); it = it->next; } return sum; } if (n->tag == NODE_SEQ) { size_t prod = 1; node *it = n->data.root; while (it != NULL) { prod *= count(it); it = it->next; } return prod; } fprintf(stderr, "Cannot count node with tag: %d\n", n->tag); exit(1); } void expand(node *n, size_t pos) { if (n == NULL) { return; } if (n->tag == NODE_LEAF) { printf(n->data.str); } else if (n->tag == NODE_TREE) { node *it = n->data.root; while (true) { size_t cnt = count(it); if (pos < cnt) { expand(it, pos); break; } pos -= cnt; it = it->next; } } else if (n->tag == NODE_SEQ) { size_t prod = pos; node *it = n->data.root; while (it != NULL) { size_t cnt = count(it); size_t rem = prod % cnt; expand(it, rem); it = it->next; } } else { fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag); exit(1); } } string allocate_string(string src) { size_t len = strlen(src); string out = calloc(len + 1, sizeof(character)); if (out == NULL) { fprintf(stderr, "Failed to allocate a copy of the string."); exit(1); } strcpy(out, src); return out; } node *parse_seq(string input, size_t *pos); node *parse_tree(string input, size_t *pos) { node *root = make_tree(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; size_t depth = 0; bool asSeq = false; bool allow = false; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = '\\'; buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { buffer[bufpos++] = c; buffer[bufpos] = 0; asSeq = true; depth++; } else if (c == '}') { if (depth-- > 0) { buffer[bufpos++] = c; buffer[bufpos] = 0; } else { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); } else { append(root, make_leaf(allocate_string(buffer))); } break; } } else if (c == ',') { if (depth == 0) { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); bufpos = 0; buffer[bufpos] = 0; asSeq = false; } else { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } return root; } node *parse_seq(string input, size_t *pos) { node *root = make_seq(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { node *tree = parse_tree(input, pos); if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } append(root, tree); } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } return root; } void test(string input) { size_t pos = 0; node *n = parse_seq(input, &pos); size_t cnt = count(n); size_t i; printf("Pattern: %s\n", input); for (i = 0; i < cnt; i++) { expand(n, i); printf("\n"); } printf("\n"); deallocate_node(n); } int main() { test("~/{Downloads,Pictures}/*.{jpg,gif,png}"); test("It{{em,alic}iz,erat}e{d,}, please."); test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!"); return 0; }
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) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
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 arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
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) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
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 arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
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[:n] allperms = [''.join(p) for p in permutations(allchars)] sp, tofind = allperms[0], set(allperms[1:]) while tofind: for skip in range(1, n): for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])): trial_perm = (sp + trial_add)[-n:] if trial_perm in tofind: sp += trial_add tofind.discard(trial_perm) trial_add = None break if trial_add is None: break assert all(perm in sp for perm in allperms) return sp def s_perm1(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop() if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm2(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop(0) if nxt not in sp: sp += nxt if perms: nxt = perms.pop(-1) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def _s_perm3(n, cmp): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: lastn = sp[-n:] nxt = cmp(perms, key=lambda pm: sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn))) perms.remove(nxt) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm3_max(n): return _s_perm3(n, max) def s_perm3_min(n): return _s_perm3(n, min) longest = [factorial(n) * n for n in range(MAXN + 1)] weight, runtime = {}, {} print(__doc__) for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]: print('\n print(algo.__doc__) weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0) for n in range(1, MAXN + 1): gc.collect() gc.disable() t = datetime.datetime.now() sp = algo(n) t = datetime.datetime.now() - t gc.enable() runtime[algo.__name__] += t lensp = len(sp) wt = (lensp / longest[n]) ** 2 print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f' % (n, lensp, longest[n], wt)) weight[algo.__name__] *= wt weight[algo.__name__] **= 1 / n weight[algo.__name__] = 1 / weight[algo.__name__] print('%*s Overall Weight: %5.2f in %.1f seconds.' % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds())) print('\n print('\n'.join('%12s (%.3f)' % kv for kv in sorted(weight.items(), key=lambda keyvalue: -keyvalue[1]))) print('\n print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
#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-1)) return 0; } super[pos++] = c; return 1; } void superperm(int n) { int i, len; pos = n; len = fact_sum(n); super = realloc(super, len + 1); super[len] = '\0'; for (i = 0; i <= n; i++) cnt[i] = i; for (i = 1; i <= n; i++) super[i - 1] = i + '0'; while (r(n)); } int main(void) { int n; for (n = 0; n < MAX; n++) { printf("superperm(%2d) ", n); superperm(n); printf("len = %d", (int)strlen(super)); putchar('\n'); } return 0; }
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)) def update(e): if not e.char.isdigit(): tkMessageBox.showerror('Error', 'Invalid input !') return "break" e = Entry(text=s) e.grid(column=0, row=0, **options) e.bind('<Key>', update) b1 = Button(text="Increase", command=increase, **options ) b1.grid(column=1, row=0, **options) b2 = Button(text="Random", command=rand, **options) b2.grid(column=2, row=0, **options) mainloop()
#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: switch( LOWORD(wPar) ) { case IDC_INCREMENT: { UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE ); SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE ); } break; case IDC_RANDOM: { int reply = MessageBox( hwnd, "Do you really want to\nget a random number?", "Random input confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE ); } break; case IDC_QUIT: SendMessage( hwnd, WM_CLOSE, 0, 0 ); break; default: ; } break; case WM_CLOSE: { int reply = MessageBox( hwnd, "Do you really want to quit?", "Quit confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) EndDialog( hwnd, 0 ); } break; default: ; } return 0; } int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) { return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc ); }
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 range(trials): bins[one_of_n(range(n))] += 1 return bins print(one_of_n_test())
#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 = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
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(number): return ''.join( str(len(list(g))) + k for k,g in groupby(number) ) while True: if printit: print(" %2i %s" % (iterations, numberstring)) numberstring = ''.join(sorted(numberstring, reverse=True)) if numberstring in last_three: break assert iterations < 1000000 last_three[queue_index], numberstring = numberstring, A036058(numberstring) iterations += 1 queue_index +=1 queue_index %=3 return iterations def max_A036058_length( start_range=range(11) ): already_done = set() max_len = (-1, []) for n in start_range: sn = str(n) sns = tuple(sorted(sn, reverse=True)) if sns not in already_done: already_done.add(sns) size = A036058_length(sns) if size > max_len[0]: max_len = (size, [n]) elif size == max_len[0]: max_len[1].append(n) return max_len lenmax, starts = max_A036058_length( range(1000000) ) allstarts = [] for n in starts: allstarts += [int(''.join(x)) for x in set(k for k in permutations(str(n), 4) if k[0] != '0')] allstarts = [x for x in sorted(allstarts) if x < 1000000] print ( % (lenmax, allstarts) ) print ( ) for n in starts: print() A036058_length(str(n), printit=True)
#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 = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } #else #define new_rec() calloc(sizeof(rec_t), 1) #endif rec_t *find_rec(char *s) { int i; rec_t *r = &root; while (*s) { i = *s++ - '0'; if (!r->p[i]) r->p[i] = new_rec(); r = r->p[i]; } return r; } char number[100][4]; void init() { int i; for (i = 0; i < 100; i++) sprintf(number[i], "%d", i); } void count(char *buf) { int i, c[10] = {0}; char *s; for (s = buf; *s; c[*s++ - '0']++); for (i = 9; i >= 0; i--) { if (!c[i]) continue; s = number[c[i]]; *buf++ = s[0]; if ((*buf = s[1])) buf++; *buf++ = i + '0'; } *buf = '\0'; } int depth(char *in, int d) { rec_t *r = find_rec(in); if (r->depth > 0) return r->depth; d++; if (!r->depth) r->depth = -d; else r->depth += d; count(in); d = depth(in, d); if (r->depth <= 0) r->depth = d + 1; return r->depth; } int main(void) { char a[100]; int i, d, best_len = 0, n_best = 0; int best_ints[32]; rec_t *r; init(); for (i = 0; i < 1000000; i++) { sprintf(a, "%d", i); d = depth(a, 0); if (d < best_len) continue; if (d > best_len) { n_best = 0; best_len = d; } if (d == best_len) best_ints[n_best++] = i; } printf("longest length: %d\n", best_len); for (i = 0; i < n_best; i++) { printf("%d\n", best_ints[i]); sprintf(a, "%d", best_ints[i]); for (d = 0; d <= best_len; d++) { r = find_rec(a); printf("%3d: %s\n", r->depth, a); count(a); } putchar('\n'); } return 0; }
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) delim = " " if len(num[-1]) > len(hyphen[-1]): num = hyphen delim = "-" if num[-1] in irregularOrdinals: num[-1] = delim + irregularOrdinals[num[-1]] elif num[-1].endswith("y"): num[-1] = delim + num[-1][:-1] + "ieth" else: num[-1] = delim + num[-1] + "th" return "".join(num) if __name__ == "__main__": tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split() for num in tests: print("{} => {}".format(num, num2ordinal(num))) TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num)
#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", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); 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]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf("%llu: %s\n", n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
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), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, 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; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
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): if i > pos: return min_len, 0 res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len) res2 = try_perm(i + 1, pos, seq, n, res1[0]) if res2[0] < res1[0]: return res2 if res2[0] == res1[0]: return res2[0], res1[1] + res2[1] raise Exception("try_perm exception") def init_try_perm(x): return try_perm(0, 0, [1], x, 12) def find_brauer(num): res = init_try_perm(num) print print "N = ", num print "Minimum length of chains: L(n) = ", res[0] print "Number of minimum length Brauer chains: ", res[1] nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379] for i in nums: find_brauer(i)
#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] = s[j]; s[j] = t; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen); pair checkSeq(int pos, int seq[], int n, int len, int minLen) { pair p; if (pos > minLen || seq[0] > n) { p.x = minLen; p.y = 0; return p; } else if (seq[0] == n) { example = malloc(len * sizeof(int)); memcpy(example, seq, len * sizeof(int)); exampleLen = len; p.x = pos; p.y = 1; return p; } else if (pos < minLen) { return tryPerm(0, pos, seq, n, len, minLen); } else { p.x = minLen; p.y = 0; return p; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) { int *seq2; pair p, res1, res2; size_t size = sizeof(int); if (i > pos) { p.x = minLen; p.y = 0; return p; } seq2 = malloc((len + 1) * size); memcpy(seq2 + 1, seq, len * size); seq2[0] = seq[0] + seq[i]; res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen); res2 = tryPerm(i + 1, pos, seq, n, len, res1.x); free(seq2); if (res2.x < res1.x) return res2; else if (res2.x == res1.x) { p.x = res2.x; p.y = res1.y + res2.y; return p; } else { printf("Error in tryPerm\n"); p.x = 0; p.y = 0; return p; } } pair initTryPerm(int x, int minLen) { int seq[1] = {1}; return tryPerm(0, 0, seq, x, 1, minLen); } void printArray(int a[], int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]\n"); } bool isBrauer(int a[], int len) { int i, j; bool ok; for (i = 2; i < len; ++i) { ok = FALSE; for (j = i - 1; j >= 0; j--) { if (a[i-1] + a[j] == a[i]) { ok = TRUE; break; } } if (!ok) return FALSE; } return TRUE; } bool isAdditionChain(int a[], int len) { int i, j, k; bool ok, exit; for (i = 2; i < len; ++i) { if (a[i] > a[i - 1] * 2) return FALSE; ok = FALSE; exit = FALSE; for (j = i - 1; j >= 0; --j) { for (k = j; k >= 0; --k) { if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; } } if (exit) break; } if (!ok) return FALSE; } if (example == NULL && !isBrauer(a, len)) { example = malloc(len * sizeof(int)); memcpy(example, a, len * sizeof(int)); exampleLen = len; } return TRUE; } void nextChains(int index, int len, int seq[], int *pcount) { for (;;) { int i; if (index < len - 1) { nextChains(index + 1, len, seq, pcount); } if (seq[index] + len - 1 - index >= seq[len - 1]) return; seq[index]++; for (i = index + 1; i < len - 1; ++i) { seq[i] = seq[i-1] + 1; } if (isAdditionChain(seq, len)) (*pcount)++; } } int findNonBrauer(int num, int len, int brauer) { int i, count = 0; int *seq = malloc(len * sizeof(int)); seq[0] = 1; seq[len - 1] = num; for (i = 1; i < len - 1; ++i) { seq[i] = seq[i - 1] + 1; } if (isAdditionChain(seq, len)) count = 1; nextChains(2, len, seq, &count); free(seq); return count - brauer; } void findBrauer(int num, int minLen, int nbLimit) { pair p = initTryPerm(num, minLen); int actualMin = p.x, brauer = p.y, nonBrauer; printf("\nN = %d\n", num); printf("Minimum length of chains : L(%d) = %d\n", num, actualMin); printf("Number of minimum length Brauer chains : %d\n", brauer); if (brauer > 0) { printf("Brauer example : "); reverse(example, exampleLen); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } if (num <= nbLimit) { nonBrauer = findNonBrauer(num, actualMin + 1, brauer); printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer); if (nonBrauer > 0) { printf("Non-Brauer example : "); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } } else { printf("Non-Brauer analysis suppressed\n"); } } int main() { int i; int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; printf("Searching for Brauer chains up to a minimum length of 12:\n"); for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79); 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; }
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 __name__ == '__main__': import re for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;" "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;" "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'): print("\nNumbers:", line) numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] mn, mx, sp = sparkline(numbers) print(' min: %5f; max: %5f' % (mn, mx)) print(" " + sp)
#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)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
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 = load_ast() return make_node(node_type, left, 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 = load_ast() return make_node(node_type, left, 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 = load_ast() return make_node(node_type, left, 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 lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m >>> modinv(42, 2017) 1969 >>>
#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-5){ ip.mi.mouseData = 0; ip.mi.dx = x * factorX; ip.mi.dy = y * factorY; ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; SendInput(1,&ip,sizeof(ip)); Sleep(1); if(x>3) x-=1; if(y<maxY-3) y+=1; } ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP; SendInput(1,&ip,sizeof(ip)); return 0; }
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-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
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; if r/maxRad < diskRatio: pencolor("black") else: pencolor("yellow") theta = 2*pi*factor*i; up() setposition(x + r*sin(theta), y + r*cos(theta)) down() circle(10.0 * i/(1.0*iter)) update() done()
#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++){ r = pow(i,factor)/iter; r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW); theta = 2*pi*factor*i; circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter)); } } int main() { initwindow(1000,1000,"Sunflower..."); sunflower(1000,1000,0.5,3000); getch(); closegraph(); return 0; }
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, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print "\t", n, print cost = 0 for g in sorted(costs): print g, "\t", for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print "\t", print print "\n\nTotal Cost = ", cost
#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, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
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, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print "\t", n, print cost = 0 for g in sorted(costs): print g, "\t", for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print "\t", print print "\n\nTotal Cost = ", cost
#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, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
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)) - RE def column_density(a, z): dsum, d = 0.0, 0.0 while d < FIN: delta = max(dd, (dd)*d) dsum += rho(height(a, z, d + 0.5 * delta)) * delta d += delta return dsum def airmass(a, z): return column_density(a, z) / column_density(a, 0) print('Angle 0 m 13700 m\n', '-' * 36) for z in range(0, 91, 5): print(f"{z: 3d} {airmass(0, z): 12.7f} {airmass(13700, z): 12.7f}")
#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; double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG)); return hh - RE; } static double column_density(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = DD * d; if (delta < DD) delta = DD; sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } static double airmass(double a, double z) { return column_density(a, z) / column_density(a, 0.0); } int main() { puts("Angle 0 m 13700 m"); puts("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } }
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,1,1) nextNewYearDay = nextNewYear.weekday() nextNewYearDayAsString = weekDays[nextNewYearDay] print("Next new year is on a {}".format(nextNewYearDayAsString))
#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 fac = 1 sign = +1 zero = 0 yield zero while True: n +=1 fac *= n yield Fraction(1, fac*sign) sign = -sign n +=1 fac *= n yield zero def cosinepower(): n = 0 fac = 1 sign = +1 yield Fraction(1,fac) zero = 0 while True: n +=1 fac *= n yield zero sign = -sign n +=1 fac *= n yield Fraction(1, fac*sign) def pluspower(*powergenerators): for elements in zip(*powergenerators): yield sum(elements) def minuspower(*powergenerators): for elements in zip(*powergenerators): yield elements[0] - sum(elements[1:]) def mulpower(fgen,ggen): 'From: http://en.wikipedia.org/wiki/Power_series a,b = [],[] for f,g in zip(fgen, ggen): a.append(f) b.append(g) yield sum(f*g for f,g in zip(a, reversed(b))) def constpower(n): yield n while True: yield 0 def diffpower(gen): 'differentiatiate power series' next(gen) for n, an in enumerate(gen, start=1): yield an*n def intgpower(k=0): 'integrate power series with constant k' def _intgpower(gen): yield k for n, an in enumerate(gen, start=1): yield an * Fraction(1,n) return _intgpower print("cosine") c = list(pipe(cosinepower(), head(10))) print(c) print("sine") s = list(pipe(sinepower(), head(10))) print(s) integc = list(pipe(cosinepower(),intgpower(0), head(10))) integs1 = list(minuspower(pipe(constpower(1), head(10)), pipe(sinepower(),intgpower(0), head(10)))) assert s == integc, "The integral of cos should be sin" assert c == integs1, "1 minus the integral of sin should be cos"
#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; fps fps_new() { fps x = malloc(sizeof(fps_t)); x->a0 = 0; x->s1 = x->s2 = 0; x->type = 0; return x; } void fps_redefine(fps x, int op, fps y, fps z) { x->type = op; x->s1 = y; x->s2 = z; } fps _binary(fps x, fps y, int op) { fps s = fps_new(); s->s1 = x; s->s2 = y; s->type = op; return s; } fps _unary(fps x, int op) { fps s = fps_new(); s->s1 = x; s->type = op; return s; } double term(fps x, int n) { double ret = 0; int i; switch (x->type) { case FPS_CONST: return n > 0 ? 0 : x->a0; case FPS_ADD: ret = term(x->s1, n) + term(x->s2, n); break; case FPS_SUB: ret = term(x->s1, n) - term(x->s2, n); break; case FPS_MUL: for (i = 0; i <= n; i++) ret += term(x->s1, i) * term(x->s2, n - i); break; case FPS_DIV: if (! term(x->s2, 0)) return NAN; ret = term(x->s1, n); for (i = 1; i <= n; i++) ret -= term(x->s2, i) * term(x, n - i) / term(x->s2, 0); break; case FPS_DERIV: ret = n * term(x->s1, n + 1); break; case FPS_INT: if (!n) return x->a0; ret = term(x->s1, n - 1) / n; break; default: fprintf(stderr, "Unknown operator %d\n", x->type); exit(1); } return ret; } #define _add(x, y) _binary(x, y, FPS_ADD) #define _sub(x, y) _binary(x, y, FPS_SUB) #define _mul(x, y) _binary(x, y, FPS_MUL) #define _div(x, y) _binary(x, y, FPS_DIV) #define _integ(x) _unary(x, FPS_INT) #define _deriv(x) _unary(x, FPS_DERIV) fps fps_const(double a0) { fps x = fps_new(); x->type = FPS_CONST; x->a0 = a0; return x; } int main() { int i; fps one = fps_const(1); fps fcos = fps_new(); fps fsin = _integ(fcos); fps ftan = _div(fsin, fcos); fps_redefine(fcos, FPS_SUB, one, _integ(fsin)); fps fexp = fps_const(1); fps_redefine(fexp, FPS_INT, fexp, 0); printf("Sin:"); for (i = 0; i < 10; i++) printf(" %g", term(fsin, i)); printf("\nCos:"); for (i = 0; i < 10; i++) printf(" %g", term(fcos, i)); printf("\nTan:"); for (i = 0; i < 10; i++) printf(" %g", term(ftan, i)); printf("\nExp:"); for (i = 0; i < 10; i++) printf(" %g", term(fexp, i)); return 0; }
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}; printf("Own digits power sums for N = 3 to 9 inclusive:\n"); for (n = 3; n < 10; ++n) { for (d = 2; d < 10; ++d) powers[d] *= d; i = (int)pow(10, n-1); max = i * 10; lastDigit = 0; while (i < max) { if (!lastDigit) { getDigits(i); sum = 0; for (d = 0; d < n; ++d) { dp = digits[d]; sum += powers[dp]; } } else if (lastDigit == 1) { sum++; } else { sum += powers[lastDigit] - powers[lastDigit-1]; } if (sum == i) { printf("%d\n", i); if (lastDigit == 0) printf("%d\n", i + 1); i += 10 - lastDigit; lastDigit = 0; } else if (sum > i) { i += 10 - lastDigit; lastDigit = 0; } else if (lastDigit < 9) { i++; lastDigit++; } else { i++; lastDigit = 0; } } } return 0; }
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: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break
#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 _qy_ ## name ## _max = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) typedef unsigned char uchar; typedef uchar code; typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } Code_t; typedef struct Code_map { char *text; Code_t op; } Code_map; Code_map code_map[] = { {"fetch", FETCH}, {"store", STORE}, {"push", PUSH }, {"add", ADD }, {"sub", SUB }, {"mul", MUL }, {"div", DIV }, {"mod", MOD }, {"lt", LT }, {"gt", GT }, {"le", LE }, {"ge", GE }, {"eq", EQ }, {"ne", NE }, {"and", AND }, {"or", OR }, {"neg", NEG }, {"not", NOT }, {"jmp", JMP }, {"jz", JZ }, {"prtc", PRTC }, {"prts", PRTS }, {"prti", PRTI }, {"halt", HALT }, }; FILE *source_fp; da_dim(object, code); void error(const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("error: %s\n", buf); exit(1); } void run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) { int32_t *sp = &data[g_size + 1]; const code *pc = obj; again: switch (*pc++) { case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again; case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again; case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again; case ADD: sp[-2] += sp[-1]; --sp; goto again; case SUB: sp[-2] -= sp[-1]; --sp; goto again; case MUL: sp[-2] *= sp[-1]; --sp; goto again; case DIV: sp[-2] /= sp[-1]; --sp; goto again; case MOD: sp[-2] %= sp[-1]; --sp; goto again; case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again; case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again; case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again; case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again; case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again; case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again; case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again; case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again; case NEG: sp[-1] = -sp[-1]; goto again; case NOT: sp[-1] = !sp[-1]; goto again; case JMP: pc += *(int32_t *)pc; goto again; case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again; case PRTC: printf("%c", sp[-1]); --sp; goto again; case PRTS: printf("%s", string_pool[sp[-1]]); --sp; goto again; case PRTI: printf("%d", sp[-1]); --sp; goto again; case HALT: break; default: error("Unknown opcode %d\n", *(pc - 1)); } } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } char *translate(char *st) { char *p, *q; if (st[0] == '"') ++st; p = q = st; while ((*p++ = *q++) != '\0') { if (q[-1] == '\\') { if (q[0] == 'n') { p[-1] = '\n'; ++q; } else if (q[0] == '\\') { ++q; } } if (q[0] == '"' && q[1] == '\0') ++q; } return st; } int findit(const char text[], int offset) { for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) { if (strcmp(code_map[i].text, text) == 0) return code_map[i].op; } error("Unknown instruction %s at %d\n", text, offset); return -1; } void emit_byte(int c) { da_append(object, (uchar)c); } void emit_int(int32_t n) { union { int32_t n; unsigned char c[sizeof(int32_t)]; } x; x.n = n; for (size_t i = 0; i < sizeof(x.n); ++i) { emit_byte(x.c[i]); } } char **load_code(int *ds) { int line_len, n_strings; char **string_pool; char *text = read_line(&line_len); text = rtrim(text, &line_len); strtok(text, " "); *ds = atoi(strtok(NULL, " ")); strtok(NULL, " "); n_strings = atoi(strtok(NULL, " ")); string_pool = malloc(n_strings * sizeof(char *)); for (int i = 0; i < n_strings; ++i) { text = read_line(&line_len); text = rtrim(text, &line_len); text = translate(text); string_pool[i] = strdup(text); } for (;;) { int len; text = read_line(&line_len); if (text == NULL) break; text = rtrim(text, &line_len); int offset = atoi(strtok(text, " ")); char *instr = strtok(NULL, " "); int opcode = findit(instr, offset); emit_byte(opcode); char *operand = strtok(NULL, " "); switch (opcode) { case JMP: case JZ: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; case PUSH: emit_int(atoi(operand)); break; case FETCH: case STORE: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; } } return string_pool; } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); int data_size; char **string_pool = load_code(&data_size); int data[1000 + data_size]; run_vm(object, data, data_size, string_pool); }
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: stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop(); pc += word_size elif op == PUSH: stack.append(bytes_to_int(code[pc:pc+word_size])[0]); pc += word_size elif op == ADD: stack[-2] += stack[-1]; stack.pop() elif op == SUB: stack[-2] -= stack[-1]; stack.pop() elif op == MUL: stack[-2] *= stack[-1]; stack.pop() elif op == DIV: stack[-2] /= stack[-1]; stack.pop() elif op == MOD: stack[-2] %= stack[-1]; stack.pop() elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop() elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop() elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop() elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop() elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop() elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop() elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop() elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop() elif op == NEG: stack[-1] = -stack[-1] elif op == NOT: stack[-1] = not stack[-1] elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0] elif op == PRTC: print stack[-1] as a character; stack.pop() elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop() elif op == PRTI: print stack[-1] as an integer; stack.pop() elif op == HALT: break
#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 _qy_ ## name ## _max = 0 #define da_redim(name) do {if (_qy_ ## name ## _p >= _qy_ ## name ## _max) \ name = realloc(name, (_qy_ ## name ## _max += 32) * sizeof(name[0]));} while (0) #define da_rewind(name) _qy_ ## name ## _p = 0 #define da_append(name, x) do {da_redim(name); name[_qy_ ## name ## _p++] = x;} while (0) typedef unsigned char uchar; typedef uchar code; typedef enum { FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } Code_t; typedef struct Code_map { char *text; Code_t op; } Code_map; Code_map code_map[] = { {"fetch", FETCH}, {"store", STORE}, {"push", PUSH }, {"add", ADD }, {"sub", SUB }, {"mul", MUL }, {"div", DIV }, {"mod", MOD }, {"lt", LT }, {"gt", GT }, {"le", LE }, {"ge", GE }, {"eq", EQ }, {"ne", NE }, {"and", AND }, {"or", OR }, {"neg", NEG }, {"not", NOT }, {"jmp", JMP }, {"jz", JZ }, {"prtc", PRTC }, {"prts", PRTS }, {"prti", PRTI }, {"halt", HALT }, }; FILE *source_fp; da_dim(object, code); void error(const char *fmt, ... ) { va_list ap; char buf[1000]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); printf("error: %s\n", buf); exit(1); } void run_vm(const code obj[], int32_t data[], int g_size, char **string_pool) { int32_t *sp = &data[g_size + 1]; const code *pc = obj; again: switch (*pc++) { case FETCH: *sp++ = data[*(int32_t *)pc]; pc += sizeof(int32_t); goto again; case STORE: data[*(int32_t *)pc] = *--sp; pc += sizeof(int32_t); goto again; case PUSH: *sp++ = *(int32_t *)pc; pc += sizeof(int32_t); goto again; case ADD: sp[-2] += sp[-1]; --sp; goto again; case SUB: sp[-2] -= sp[-1]; --sp; goto again; case MUL: sp[-2] *= sp[-1]; --sp; goto again; case DIV: sp[-2] /= sp[-1]; --sp; goto again; case MOD: sp[-2] %= sp[-1]; --sp; goto again; case LT: sp[-2] = sp[-2] < sp[-1]; --sp; goto again; case GT: sp[-2] = sp[-2] > sp[-1]; --sp; goto again; case LE: sp[-2] = sp[-2] <= sp[-1]; --sp; goto again; case GE: sp[-2] = sp[-2] >= sp[-1]; --sp; goto again; case EQ: sp[-2] = sp[-2] == sp[-1]; --sp; goto again; case NE: sp[-2] = sp[-2] != sp[-1]; --sp; goto again; case AND: sp[-2] = sp[-2] && sp[-1]; --sp; goto again; case OR: sp[-2] = sp[-2] || sp[-1]; --sp; goto again; case NEG: sp[-1] = -sp[-1]; goto again; case NOT: sp[-1] = !sp[-1]; goto again; case JMP: pc += *(int32_t *)pc; goto again; case JZ: pc += (*--sp == 0) ? *(int32_t *)pc : (int32_t)sizeof(int32_t); goto again; case PRTC: printf("%c", sp[-1]); --sp; goto again; case PRTS: printf("%s", string_pool[sp[-1]]); --sp; goto again; case PRTI: printf("%d", sp[-1]); --sp; goto again; case HALT: break; default: error("Unknown opcode %d\n", *(pc - 1)); } } char *read_line(int *len) { static char *text = NULL; static int textmax = 0; for (*len = 0; ; (*len)++) { int ch = fgetc(source_fp); if (ch == EOF || ch == '\n') { if (*len == 0) return NULL; break; } if (*len + 1 >= textmax) { textmax = (textmax == 0 ? 128 : textmax * 2); text = realloc(text, textmax); } text[*len] = ch; } text[*len] = '\0'; return text; } char *rtrim(char *text, int *len) { for (; *len > 0 && isspace(text[*len - 1]); --(*len)) ; text[*len] = '\0'; return text; } char *translate(char *st) { char *p, *q; if (st[0] == '"') ++st; p = q = st; while ((*p++ = *q++) != '\0') { if (q[-1] == '\\') { if (q[0] == 'n') { p[-1] = '\n'; ++q; } else if (q[0] == '\\') { ++q; } } if (q[0] == '"' && q[1] == '\0') ++q; } return st; } int findit(const char text[], int offset) { for (size_t i = 0; i < sizeof(code_map) / sizeof(code_map[0]); i++) { if (strcmp(code_map[i].text, text) == 0) return code_map[i].op; } error("Unknown instruction %s at %d\n", text, offset); return -1; } void emit_byte(int c) { da_append(object, (uchar)c); } void emit_int(int32_t n) { union { int32_t n; unsigned char c[sizeof(int32_t)]; } x; x.n = n; for (size_t i = 0; i < sizeof(x.n); ++i) { emit_byte(x.c[i]); } } char **load_code(int *ds) { int line_len, n_strings; char **string_pool; char *text = read_line(&line_len); text = rtrim(text, &line_len); strtok(text, " "); *ds = atoi(strtok(NULL, " ")); strtok(NULL, " "); n_strings = atoi(strtok(NULL, " ")); string_pool = malloc(n_strings * sizeof(char *)); for (int i = 0; i < n_strings; ++i) { text = read_line(&line_len); text = rtrim(text, &line_len); text = translate(text); string_pool[i] = strdup(text); } for (;;) { int len; text = read_line(&line_len); if (text == NULL) break; text = rtrim(text, &line_len); int offset = atoi(strtok(text, " ")); char *instr = strtok(NULL, " "); int opcode = findit(instr, offset); emit_byte(opcode); char *operand = strtok(NULL, " "); switch (opcode) { case JMP: case JZ: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; case PUSH: emit_int(atoi(operand)); break; case FETCH: case STORE: operand++; len = strlen(operand); operand[len - 1] = '\0'; emit_int(atoi(operand)); break; } } return string_pool; } void init_io(FILE **fp, FILE *std, const char mode[], const char fn[]) { if (fn[0] == '\0') *fp = std; else if ((*fp = fopen(fn, mode)) == NULL) error(0, 0, "Can't open %s\n", fn); } int main(int argc, char *argv[]) { init_io(&source_fp, stdin, "r", argc > 1 ? argv[1] : ""); int data_size; char **string_pool = load_code(&data_size); int data[1000 + data_size]; run_vm(object, data, data_size, string_pool); }
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) break elif firstadd > K[-1]: K.append(firstadd) if secondadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < secondadd < K[pos + 1]: K.insert(pos + 1, secondadd) break elif secondadd > K[-1]: K.append(secondadd) return K kr1m = KlarnerRado(100_000) print('First 100 Klarner-Rado sequence numbers:') for idx, v in enumerate(kr1m[:100]): print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '') for n in [1000, 10_000, 100_000]: print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
#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 = dst[i3++] * 3 + 1; } } int main(void) { static unsigned int klarner_rado[ELEMENTS]; unsigned int i; make_klarner_rado(klarner_rado, ELEMENTS); for (i = 0; i < 99; ++i) printf("%u ", klarner_rado[i]); for (i = 100; i <= ELEMENTS; i *= 10) printf("%u\n", klarner_rado[i - 1]); return 0; }
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) break elif firstadd > K[-1]: K.append(firstadd) if secondadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < secondadd < K[pos + 1]: K.insert(pos + 1, secondadd) break elif secondadd > K[-1]: K.append(secondadd) return K kr1m = KlarnerRado(100_000) print('First 100 Klarner-Rado sequence numbers:') for idx, v in enumerate(kr1m[:100]): print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '') for n in [1000, 10_000, 100_000]: print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
#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 = dst[i3++] * 3 + 1; } } int main(void) { static unsigned int klarner_rado[ELEMENTS]; unsigned int i; make_klarner_rado(klarner_rado, ELEMENTS); for (i = 0; i < 99; ++i) printf("%u ", klarner_rado[i]); for (i = 100; i <= ELEMENTS; i *= 10) printf("%u\n", klarner_rado[i - 1]); return 0; }
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 + c * y2 + d * y3) pts.append( (x, y) ) for i in range(n): self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]) Bitmap.cubicbezier = cubicbezier bitmap = Bitmap(17,17) bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11) bitmap.chardisplay()
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: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), maxindex+1 )) data[:maxindex+1] = reversed(data[:maxindex+1]) if tutor: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), size )) data[:size] = reversed(data[:size]) if tutor: print()
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; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
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 elif num < minNum: minNum = num print("Largest 5-adjacent number found ", maxNum) print("Smallest 5-adjacent number found ", minNum)
#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++; return acc; } int main() { uint8_t digits[DIGITS]; int i, largest = 0; srand(time(NULL)); for (i=0; i<DIGITS; i++) digits[i] = randomDigit(); for (i=0; i<DIGITS-NUMSIZE; i++) { int here = numberAt(&digits[i], NUMSIZE); if (here > largest) largest = here; } printf("%d\n", largest); return 0; }
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)) and isPrime(digSum(n**2, 10)): print(n, end = " ")
#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++) if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i))) printf("%d ", i); printf("\n"); return 0; }
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] = False j += 1 pcount = 0 for i in range(1, k + 1): if integers_list[i]: pcount += 1 if print_all: print(f"{2 * i + 1:4}", end=' ') if pcount % 10 == 0: print() if pcount == nth: print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n") break sieve_of_Sundaram(100, True) sieve_of_Sundaram(1000000, False)
#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+1; for (i = 1; (i+1)*i*2 <= k; i++) for (j = i; j <= (k-i)/(2*i+1); j++) { m = i + j + 2*i*j; if(a[m]) a[m] = 0; } for (i = 1, j = 0; i <= k; i++) if (a[i]) { if(j%10 == 0 && j <= 100)printf("\n"); j++; if(j <= 100)printf("%3d ", a[i]); else if(j == nprimes){ printf("\n%d th prime is %d\n",j,a[i]); break; } } }
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 84.162 == molar_mass('C6H12') assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 == molar_mass('C6H4O2(OH)4') assert 386.664 == molar_mass('C27H46O') assert 315 == molar_mass('Uue')
#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; nptr->weight = weight; nptr->next = NULL; return nptr; } return NULL; } void free_node(node *ptr) { if (ptr) { free_node(ptr->next); ptr->next = NULL; free(ptr); } } node *insert(string symbol, double weight, node *head) { node *nptr = make_node(symbol, weight); nptr->next = head; return nptr; } node *dic; void init() { dic = make_node("H", 1.008); dic = insert("He", 4.002602, dic); dic = insert("Li", 6.94, dic); dic = insert("Be", 9.0121831, dic); dic = insert("B", 10.81, dic); dic = insert("C", 12.011, dic); dic = insert("N", 14.007, dic); dic = insert("O", 15.999, dic); dic = insert("F", 18.998403163, dic); dic = insert("Ne", 20.1797, dic); dic = insert("Na", 22.98976928, dic); dic = insert("Mg", 24.305, dic); dic = insert("Al", 26.9815385, dic); dic = insert("Si", 28.085, dic); dic = insert("P", 30.973761998, dic); dic = insert("S", 32.06, dic); dic = insert("Cl", 35.45, dic); dic = insert("Ar", 39.948, dic); dic = insert("K", 39.0983, dic); dic = insert("Ca", 40.078, dic); dic = insert("Sc", 44.955908, dic); dic = insert("Ti", 47.867, dic); dic = insert("V", 50.9415, dic); dic = insert("Cr", 51.9961, dic); dic = insert("Mn", 54.938044, dic); dic = insert("Fe", 55.845, dic); dic = insert("Co", 58.933194, dic); dic = insert("Ni", 58.6934, dic); dic = insert("Cu", 63.546, dic); dic = insert("Zn", 65.38, dic); dic = insert("Ga", 69.723, dic); dic = insert("Ge", 72.630, dic); dic = insert("As", 74.921595, dic); dic = insert("Se", 78.971, dic); dic = insert("Br", 79.904, dic); dic = insert("Kr", 83.798, dic); dic = insert("Rb", 85.4678, dic); dic = insert("Sr", 87.62, dic); dic = insert("Y", 88.90584, dic); dic = insert("Zr", 91.224, dic); dic = insert("Nb", 92.90637, dic); dic = insert("Mo", 95.95, dic); dic = insert("Ru", 101.07, dic); dic = insert("Rh", 102.90550, dic); dic = insert("Pd", 106.42, dic); dic = insert("Ag", 107.8682, dic); dic = insert("Cd", 112.414, dic); dic = insert("In", 114.818, dic); dic = insert("Sn", 118.710, dic); dic = insert("Sb", 121.760, dic); dic = insert("Te", 127.60, dic); dic = insert("I", 126.90447, dic); dic = insert("Xe", 131.293, dic); dic = insert("Cs", 132.90545196, dic); dic = insert("Ba", 137.327, dic); dic = insert("La", 138.90547, dic); dic = insert("Ce", 140.116, dic); dic = insert("Pr", 140.90766, dic); dic = insert("Nd", 144.242, dic); dic = insert("Pm", 145, dic); dic = insert("Sm", 150.36, dic); dic = insert("Eu", 151.964, dic); dic = insert("Gd", 157.25, dic); dic = insert("Tb", 158.92535, dic); dic = insert("Dy", 162.500, dic); dic = insert("Ho", 164.93033, dic); dic = insert("Er", 167.259, dic); dic = insert("Tm", 168.93422, dic); dic = insert("Yb", 173.054, dic); dic = insert("Lu", 174.9668, dic); dic = insert("Hf", 178.49, dic); dic = insert("Ta", 180.94788, dic); dic = insert("W", 183.84, dic); dic = insert("Re", 186.207, dic); dic = insert("Os", 190.23, dic); dic = insert("Ir", 192.217, dic); dic = insert("Pt", 195.084, dic); dic = insert("Au", 196.966569, dic); dic = insert("Hg", 200.592, dic); dic = insert("Tl", 204.38, dic); dic = insert("Pb", 207.2, dic); dic = insert("Bi", 208.98040, dic); dic = insert("Po", 209, dic); dic = insert("At", 210, dic); dic = insert("Rn", 222, dic); dic = insert("Fr", 223, dic); dic = insert("Ra", 226, dic); dic = insert("Ac", 227, dic); dic = insert("Th", 232.0377, dic); dic = insert("Pa", 231.03588, dic); dic = insert("U", 238.02891, dic); dic = insert("Np", 237, dic); dic = insert("Pu", 244, dic); dic = insert("Am", 243, dic); dic = insert("Cm", 247, dic); dic = insert("Bk", 247, dic); dic = insert("Cf", 251, dic); dic = insert("Es", 252, dic); dic = insert("Fm", 257, dic); dic = insert("Uue", 315, dic); dic = insert("Ubn", 299, dic); } double lookup(string symbol) { for (node *ptr = dic; ptr; ptr = ptr->next) { if (strcmp(symbol, ptr->symbol) == 0) { return ptr->weight; } } printf("symbol not found: %s\n", symbol); return 0.0; } double total(double mass, int count) { if (count > 0) { return mass * count; } return mass; } double total_s(string sym, int count) { double mass = lookup(sym); return total(mass, count); } double evaluate_c(string expr, size_t *pos, double mass) { int count = 0; if (expr[*pos] < '0' || '9' < expr[*pos]) { printf("expected to find a count, saw the character: %c\n", expr[*pos]); } for (; expr[*pos]; (*pos)++) { char c = expr[*pos]; if ('0' <= c && c <= '9') { count = count * 10 + c - '0'; } else { break; } } return total(mass, count); } double evaluate_p(string expr, size_t limit, size_t *pos) { char sym[4]; int sym_pos = 0; int count = 0; double sum = 0.0; for (; *pos < limit && expr[*pos]; (*pos)++) { char c = expr[*pos]; if ('A' <= c && c <= 'Z') { if (sym_pos > 0) { sum += total_s(sym, count); sym_pos = 0; count = 0; } sym[sym_pos++] = c; sym[sym_pos] = 0; } else if ('a' <= c && c <= 'z') { sym[sym_pos++] = c; sym[sym_pos] = 0; } else if ('0' <= c && c <= '9') { count = count * 10 + c - '0'; } else if (c == '(') { if (sym_pos > 0) { sum += total_s(sym, count); sym_pos = 0; count = 0; } (*pos)++; double mass = evaluate_p(expr, limit, pos); sum += evaluate_c(expr, pos, mass); (*pos)--; } else if (c == ')') { if (sym_pos > 0) { sum += total_s(sym, count); sym_pos = 0; count = 0; } (*pos)++; return sum; } else { printf("Unexpected character encountered: %c\n", c); } } if (sym_pos > 0) { sum += total_s(sym, count); } return sum; } double evaluate(string expr) { size_t limit = strlen(expr); size_t pos = 0; return evaluate_p(expr, limit, &pos); } void test(string expr) { double mass = evaluate(expr); printf("%17s -> %7.3f\n", expr, mass); } int main() { init(); test("H"); test("H2"); test("H2O"); test("H2O2"); test("(HO)2"); test("Na2SO4"); test("C6H12"); test("COOH(C(CH3)2)3CH3"); test("C6H4O2(OH)4"); test("C27H46O"); test("Uue"); free_node(dic); dic = NULL; return 0; }
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):] return p(len(ns)) and ( not any(p(x) for x in rest) ) return go def main(): print( '\n'.join([ f'{xs} -> {nnPeers(3)(xs)}' for xs in [ [9, 3, 3, 3, 2, 1, 7, 8, 5], [5, 2, 9, 3, 3, 7, 8, 4, 1], [1, 4, 3, 6, 7, 3, 8, 3, 2], [1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6, 8, 7, 2, 3, 3, 3, 1] ] ]) ) if __name__ == '__main__': main()
#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 print_list(const int *items, size_t len) { while (len--) printf("%d ", *items++); } int main() { int lists[][9] = { {9,3,3,3,2,1,7,8,5}, {5,2,9,3,3,6,8,4,1}, {1,4,3,6,7,3,8,3,2}, {1,2,3,4,5,6,7,8,9}, {4,6,8,7,2,3,3,3,1} }; size_t list_length = sizeof(lists[0]) / sizeof(int); size_t n_lists = sizeof(lists) / sizeof(lists[0]); for (size_t i=0; i<n_lists; i++) { print_list(lists[i], list_length); printf("-> %s\n", three_3s(lists[i], list_length) ? "true" : "false"); } return 0; }
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) if pp[1]), key=itemgetter(1)) sign *= -1 if d1 == -1: i2 = i1 - 1 p[i1], p[i2] = p[i2], p[i1] if i2 == 0 or p[i2 - 1][0] > n1: p[i2][1] = 0 elif d1 == 1: i2 = i1 + 1 p[i1], p[i2] = p[i2], p[i1] if i2 == n - 1 or p[i2 + 1][0] > n1: p[i2][1] = 0 if DEBUG: print ' yield tuple(pp[0] for pp in p), sign for i3, pp in enumerate(p): n3, d3 = pp if n3 > n1: pp[1] = 1 if i3 < i2 else -1 if DEBUG: print ' if __name__ == '__main__': from itertools import permutations for n in (3, 4): print '\nPermutations and sign of %i items' % n sp = set() for i in spermutations(n): sp.add(i[0]) print('Perm: %r Sign: %2i' % i) p = set(permutations(range(n))) assert sp == p, 'Two methods of generating permutations do not agree'
#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,arr,arrLen); if(n%2==0){ temp = arr[i]; arr[i] = arr[n-1]; arr[n-1] = temp; } else{ temp = arr[0]; arr[0] = arr[n-1]; arr[n-1] = temp; } } heapPermute(n-1,arr,arrLen); } } int main(int argC,char* argV[0]) { int *arr, i=0, count = 1; char* token; if(argC==1) printf("Usage : %s <comma separated list of integers>",argV[0]); else{ while(argV[1][i]!=00){ if(argV[1][i++]==',') count++; } arr = (int*)malloc(count*sizeof(int)); i = 0; token = strtok(argV[1],","); while(token!=NULL){ arr[i++] = atoi(token); token = strtok(NULL,","); } heapPermute(i,arr,count); } return 0; }
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 in islice( a131382(), 40 ) ]) ) 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 digitSum(n): return sum(int(x) for x in list(str(n))) def elemIndex(x): def go(xs): try: return next( i for i, v in enumerate(xs) if x == v ) except StopIteration: return None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
#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++) { printf("%9u", a131382(n)); if (n % 10 == 0) printf("\n"); } return 0; }
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]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i] if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
#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 + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
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, 7, 6, 5, 9, 3, 2, 1, 0, 4), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0), ] INV = (0, 4, 3, 2, 1, 5, 6, 7, 8, 9) PERMUTATION_TABLE = [ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 5, 7, 6, 2, 8, 3, 0, 9, 4), (5, 8, 0, 3, 7, 9, 6, 1, 4, 2), (8, 9, 1, 6, 0, 4, 3, 5, 2, 7), (9, 4, 5, 3, 1, 2, 6, 8, 7, 0), (4, 2, 8, 6, 5, 7, 3, 9, 0, 1), (2, 7, 9, 3, 8, 0, 6, 4, 1, 5), (7, 0, 4, 6, 9, 1, 3, 2, 5, 8), ] def verhoeffchecksum(n, validate=True, terse=True, verbose=False): if verbose: print(f"\n{'Validation' if validate else 'Check digit'}",\ f"calculations for {n}:\n\n i nᵢ p[i,nᵢ] c\n------------------") c, dig = 0, list(str(n if validate else 10 * n)) for i, ni in enumerate(dig[::-1]): p = PERMUTATION_TABLE[i % 8][int(ni)] c = MULTIPLICATION_TABLE[c][p] if verbose: print(f"{i:2} {ni} {p} {c}") if verbose and not validate: print(f"\ninv({c}) = {INV[c]}") if not terse: print(f"\nThe validation for '{n}' is {'correct' if c == 0 else 'incorrect'}."\ if validate else f"\nThe check digit for '{n}' is {INV[c]}.") return c == 0 if validate else INV[c] if __name__ == '__main__': for n, va, t, ve in [ (236, False, False, True), (2363, True, False, True), (2369, True, False, True), (12345, False, False, True), (123451, True, False, True), (123459, True, False, True), (123456789012, False, False, False), (1234567890120, True, False, False), (1234567890129, True, False, False)]: verhoeffchecksum(n, va, t, ve)
#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, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; static const int inv[] = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; static const int p[][10] = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; int verhoeff(const char* s, bool validate, bool verbose) { if (verbose) { const char* t = validate ? "Validation" : "Check digit"; printf("%s calculations for '%s':\n\n", t, s); puts(u8" i n\xE1\xB5\xA2 p[i,n\xE1\xB5\xA2] c"); puts("------------------"); } int len = strlen(s); if (validate) --len; int c = 0; for (int i = len; i >= 0; --i) { int ni = (i == len && !validate) ? 0 : s[i] - '0'; assert(ni >= 0 && ni < 10); int pi = p[(len - i) % 8][ni]; c = d[c][pi]; if (verbose) printf("%2d %d %d %d\n", len - i, ni, pi, c); } if (verbose && !validate) printf("\ninv[%d] = %d\n", c, inv[c]); return validate ? c == 0 : inv[c]; } int main() { const char* ss[3] = {"236", "12345", "123456789012"}; for (int i = 0; i < 3; ++i) { const char* s = ss[i]; bool verbose = i < 2; int c = verhoeff(s, false, verbose); printf("\nThe check digit for '%s' is '%d'.\n", s, c); int len = strlen(s); char sc[len + 2]; strncpy(sc, s, len + 2); for (int j = 0; j < 2; ++j) { sc[len] = (j == 0) ? c + '0' : '9'; int v = verhoeff(sc, true, verbose); printf("\nThe validation for '%s' is %s.\n", sc, v ? "correct" : "incorrect"); } } return 0; }
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"[cnt % 12 == 0]) print()
#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 (palindrome(i, 2) && palindrome(i, 4) && palindrome(i, 16)) { printf("%5d%c", i, ++c % 12 ? ' ' : '\n'); } } printf("\n"); return 0; }
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 += add_steps secs += 1 yield (secs, behind, total) ls = gen_long_stairs(1, 100, 1, 5) print("Seconds Behind Ahead\n----------------------") while True: secs, pos, len = next(ls) if 600 <= secs < 610: print(secs, " ", pos, " ", len - pos) elif secs == 610: break print("\nTen thousand trials to top:") times, heights = [], [] for trial in range(10_000): trialstairs = gen_long_stairs(1, 100, 1, 5) while True: sec, step, height = next(trialstairs) if step >= height: times.append(sec) heights.append(height) break print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
#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++ ) { sbeh = 0; slen = 100; secs = 0; while(sbeh<slen) { sbeh+=1; for(wiz=1;wiz<=5;wiz++) { if(rand()%slen < sbeh) sbeh+=1; slen+=1; } secs+=1; if(trial==1&&599<secs&&secs<610) printf("%d %d %d\n", secs, sbeh, slen-sbeh ); } secs_tot+=secs; steps_tot+=slen; } printf( "Average secs taken: %f\n", secs_tot/10000.0 ); printf( "Average final length of staircase: %f\n", steps_tot/10000.0 ); return 0; }
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('Character at column 3, row 6 = ' + ch + '\n') stdscr.getch() curses.endwin()
#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) return 1; if (GetConsoleScreenBufferInfo(conout, &info) == 0) return 1; pos.X = info.srWindow.Left + 3; pos.Y = info.srWindow.Top + 6; if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 || len <= 0) return 1; wprintf(L"Character at (3, 6) had been '%lc'\n", c); return 0; }
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.disabled_prefix = disabled_prefix def __str__(self): disabled = ('', '%s ' % self.disabled_prefix)[self.disabled] value = (' %s' % self.value, '')[self.value is None] return ''.join((disabled, self.name, value)) def get(self): enabled = not bool(self.disabled) if self.value is None: value = enabled else: value = enabled and self.value return value class Config(object): reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$' def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX): self.disabled_prefix = disabled_prefix self.contents = [] self.options = {} self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix) if fname: self.parse_file(fname) def __str__(self): return '\n'.join(map(str, self.contents)) def parse_file(self, fname): with open(fname) as f: self.parse_lines(f) return self def parse_lines(self, lines): for line in lines: self.parse_line(line) return self def parse_line(self, line): s = ''.join(c for c in line.strip() if c in string.printable) moOPTION = self.creOPTION.match(s) if moOPTION: name = moOPTION.group('name').upper() if not name in self.options: self.add_option(name, moOPTION.group('value'), moOPTION.group('disabled')) else: if not s.startswith(self.disabled_prefix): self.contents.append(line.rstrip()) return self def add_option(self, name, value=None, disabled=False): name = name.upper() opt = Option(name, value, disabled) self.options[name] = opt self.contents.append(opt) return opt def set_option(self, name, value=None, disabled=False): name = name.upper() opt = self.options.get(name) if opt: opt.value = value opt.disabled = disabled else: opt = self.add_option(name, value, disabled) return opt def enable_option(self, name, value=None): return self.set_option(name, value, False) def disable_option(self, name, value=None): return self.set_option(name, value, True) def get_option(self, name): opt = self.options.get(name.upper()) value = opt.get() if opt else None return value if __name__ == '__main__': import sys cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None) cfg.disable_option('needspeeling') cfg.enable_option('seedsremoved') cfg.enable_option('numberofbananas', 1024) cfg.enable_option('numberofstrawberries', 62000) print cfg
#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, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
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], [45, -170, 94, -36, 48, 73], [-39, 65, -112, -16, -78, -72], [6, -11, -6, 62, 49, 8]], [ [-57, 49, -23, 52, -135, 66], [-23, 127, -58, -5, -118, 64], [87, -16, 121, 23, -41, -12], [-19, 29, 35, -148, -11, 45]], [ [-55, -147, -146, -31, 55, 60], [-88, -45, -28, 46, -26, -144], [-12, -107, -34, 150, 249, 66], [11, -15, -34, 27, -78, -50]], [ [56, 67, 108, 4, 2, -48], [58, 67, 89, 32, 32, -8], [-42, -31, -103, -30, -23, -8], [6, 4, -26, -10, 26, 12]]] def trim_zero_empty(x): if len(x) > 0: if type(x[0]) != numpy.ndarray: return list(numpy.trim_zeros(x)) else: new_x = [] for l in x: tl = trim_zero_empty(l) if len(tl) > 0: new_x.append(tl) return new_x else: return x def deconv(a, b): ffta = numpy.fft.fftn(a) ashape = numpy.shape(a) fftb = numpy.fft.fftn(b,ashape) fftquotient = ffta / fftb c = numpy.fft.ifftn(fftquotient) trimmedc = numpy.around(numpy.real(c),decimals=6) cleanc = trim_zero_empty(trimmedc) return cleanc print("deconv(g,h)=") pprint.pprint(deconv(g,h)) print(" ") print("deconv(g,f)=") pprint.pprint(deconv(g,f))
#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 row_len) { 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 < ns; i++) { if (cabs(creal(h[i])) < 1e-10) h[i] = 0; } for (int i = 0; i > lf - lg - row_len; i--) out[-i] = h[(i + ns) % ns]/32; free(g2); free(f2); } double* unpack2(void *m, int rows, int len, int to_len) { double *buf = calloc(sizeof(double), rows * to_len); for (int i = 0; i < rows; i++) for (int j = 0; j < len; j++) buf[i * to_len + j] = ((double(*)[len])m)[i][j]; return buf; } void pack2(double * buf, int rows, int from_len, int to_len, void *out) { for (int i = 0; i < rows; i++) for (int j = 0; j < to_len; j++) ((double(*)[to_len])out)[i][j] = buf[i * from_len + j] / 4; } void deconv2(void *g, int row_g, int col_g, void *f, int row_f, int col_f, void *out) { double *g2 = unpack2(g, row_g, col_g, col_g); double *f2 = unpack2(f, row_f, col_f, col_g); double ff[(row_g - row_f + 1) * col_g]; deconv(g2, row_g * col_g, f2, row_f * col_g, ff, col_g); pack2(ff, row_g - row_f + 1, col_g, col_g - col_f + 1, out); free(g2); free(f2); } double* unpack3(void *m, int x, int y, int z, int to_y, int to_z) { double *buf = calloc(sizeof(double), x * to_y * to_z); for (int i = 0; i < x; i++) for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) buf[(i * to_y + j) * to_z + k] = ((double(*)[y][z])m)[i][j][k]; } return buf; } void pack3(double * buf, int x, int y, int z, int to_y, int to_z, void *out) { for (int i = 0; i < x; i++) for (int j = 0; j < to_y; j++) for (int k = 0; k < to_z; k++) ((double(*)[to_y][to_z])out)[i][j][k] = buf[(i * y + j) * z + k] / 4; } void deconv3(void *g, int gx, int gy, int gz, void *f, int fx, int fy, int fz, void *out) { double *g2 = unpack3(g, gx, gy, gz, gy, gz); double *f2 = unpack3(f, fx, fy, fz, gy, gz); double ff[(gx - fx + 1) * gy * gz]; deconv(g2, gx * gy * gz, f2, fx * gy * gz, ff, gy * gz); pack3(ff, gx - fx + 1, gy, gz, gy - fy + 1, gz - fz + 1, out); free(g2); free(f2); } int main() { PI = atan2(1,1) * 4; double h[2][3][4] = { {{-6, -8, -5, 9}, {-7, 9, -6, -8}, { 2, -7, 9, 8}}, {{ 7, 4, 4, -6}, { 9, 9, 4, -4}, {-3, 7, -2, -3}} }; int hx = 2, hy = 3, hz = 4; double f[3][2][3] = { {{-9, 5, -8}, { 3, 5, 1}}, {{-1, -7, 2}, {-5, -6, 6}}, {{ 8, 5, 8}, {-2, -6, -4}} }; int fx = 3, fy = 2, fz = 3; double g[4][4][6] = { { { 54, 42, 53, -42, 85, -72}, { 45,-170, 94, -36, 48, 73}, {-39, 65,-112, -16, -78, -72}, { 6, -11, -6, 62, 49, 8} }, { {-57, 49, -23, 52, -135, 66},{-23, 127, -58, -5, -118, 64}, { 87, -16, 121, 23, -41, -12},{-19, 29, 35,-148, -11, 45} }, { {-55, -147, -146, -31, 55, 60},{-88, -45, -28, 46, -26,-144}, {-12, -107, -34, 150, 249, 66},{ 11, -15, -34, 27, -78, -50} }, { { 56, 67, 108, 4, 2,-48},{ 58, 67, 89, 32, 32, -8}, {-42, -31,-103, -30,-23, -8},{ 6, 4, -26, -10, 26, 12} } }; int gx = 4, gy = 4, gz = 6; double h2[gx - fx + 1][gy - fy + 1][gz - fz + 1]; deconv3(g, gx, gy, gz, f, fx, fy, fz, h2); printf("deconv3(g, f):\n"); for (int i = 0; i < gx - fx + 1; i++) { for (int j = 0; j < gy - fy + 1; j++) { for (int k = 0; k < gz - fz + 1; k++) printf("%g ", h2[i][j][k]); printf("\n"); } if (i < gx - fx) printf("\n"); } double f2[gx - hx + 1][gy - hy + 1][gz - hz + 1]; deconv3(g, gx, gy, gz, h, hx, hy, hz, f2); printf("\ndeconv3(g, h):\n"); for (int i = 0; i < gx - hx + 1; i++) { for (int j = 0; j < gy - hy + 1; j++) { for (int k = 0; k < gz - hz + 1; k++) printf("%g ", f2[i][j][k]); printf("\n"); } if (i < gx - hx) printf("\n"); } }
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_sides1, n_dice1) c2, p2 = gen_dict(n_sides2, n_dice2) p12 = float(p1 * p2) return sum(p[1] * q[1] / p12 for p, q in product(enumerate(c1), enumerate(c2)) if p[0] > q[0]) print beating_probability(4, 9, 6, 6) print beating_probability(10, 5, 7, 6)
#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 uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; } for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); } double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1); const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2); const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2)); double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; } int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
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), (membero, ('Englishman', var(), var(), var(), 'red'), houses), (membero, ('Swede', var(), var(), 'dog', var()), houses), (membero, ('Dane', var(), 'tea', var(), var()), houses), (lefto, (var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), (membero, (var(), var(), 'coffee', var(), 'green'), houses), (membero, (var(), 'Pall Mall', var(), 'birds', var()), houses), (membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses), (eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), (eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), (nexto, (var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), (membero, (var(), 'Blue Master', 'beer', var(), var()), houses), (membero, ('German', 'Prince', var(), var(), var()), houses), (nexto, ('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), (membero, (var(), var(), var(), 'zebra', var()), houses) ) t0 = time.time() solutions = run(0, houses, zebraRules) t1 = time.time() dur = t1-t0 count = len(solutions) zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0] print "%i solutions in %.2f seconds" % (count, dur) print "The %s is the owner of the zebra" % zebraOwner print "Here are all the houses:" for line in solutions[0]: print str(line)
#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 }; enum Smokes { PallMall, Dunhill, Blend, BlueMaster, Prince }; void printHouses(int ha[5][5]) { const char *color[] = { "Red", "Green", "White", "Yellow", "Blue" }; const char *man[] = { "English", "Swede", "Dane", "German", "Norwegian" }; const char *drink[] = { "Tea", "Coffee", "Milk", "Beer", "Water" }; const char *animal[] = { "Dog", "Birds", "Cats", "Horse", "Zebra" }; const char *smoke[] = { "PallMall", "Dunhill", "Blend", "BlueMaster", "Prince" }; printf("%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s\n", "House", "Color", "Man", "Drink", "Animal", "Smoke"); for (int i = 0; i < 5; i++) { printf("%-10d", i); if (ha[i][C] >= 0) printf("%-10.10s", color[ha[i][C]]); else printf("%-10.10s", "-"); if (ha[i][M] >= 0) printf("%-10.10s", man[ha[i][M]]); else printf("%-10.10s", "-"); if (ha[i][D] >= 0) printf("%-10.10s", drink[ha[i][D]]); else printf("%-10.10s", "-"); if (ha[i][A] >= 0) printf("%-10.10s", animal[ha[i][A]]); else printf("%-10.10s", "-"); if (ha[i][S] >= 0) printf("%-10.10s\n", smoke[ha[i][S]]); else printf("-\n"); } } int checkHouses(int ha[5][5]) { int c_add = 0, c_or = 0; int m_add = 0, m_or = 0; int d_add = 0, d_or = 0; int a_add = 0, a_or = 0; int s_add = 0, s_or = 0; if (ha[2][D] >= 0 && ha[2][D] != Milk) return Invalid; if (ha[0][M] >= 0 && ha[0][M] != Norwegian) return Invalid; for (int i = 0; i < 5; i++) { if (ha[i][C] >= 0) { c_add += (1 << ha[i][C]); c_or |= (1 << ha[i][C]); } if (ha[i][M] >= 0) { m_add += (1 << ha[i][M]); m_or |= (1 << ha[i][M]); } if (ha[i][D] >= 0) { d_add += (1 << ha[i][D]); d_or |= (1 << ha[i][D]); } if (ha[i][A] >= 0) { a_add += (1 << ha[i][A]); a_or |= (1 << ha[i][A]); } if (ha[i][S] >= 0) { s_add += (1 << ha[i][S]); s_or |= (1 << ha[i][S]); } if ((ha[i][M] >= 0 && ha[i][C] >= 0) && ((ha[i][M] == English && ha[i][C] != Red) || (ha[i][M] != English && ha[i][C] == Red))) return Invalid; if ((ha[i][M] >= 0 && ha[i][A] >= 0) && ((ha[i][M] == Swede && ha[i][A] != Dog) || (ha[i][M] != Swede && ha[i][A] == Dog))) return Invalid; if ((ha[i][M] >= 0 && ha[i][D] >= 0) && ((ha[i][M] == Dane && ha[i][D] != Tea) || (ha[i][M] != Dane && ha[i][D] == Tea))) return Invalid; if ((i > 0 && ha[i][C] >= 0 ) && ((ha[i - 1][C] == Green && ha[i][C] != White) || (ha[i - 1][C] != Green && ha[i][C] == White))) return Invalid; if ((ha[i][C] >= 0 && ha[i][D] >= 0) && ((ha[i][C] == Green && ha[i][D] != Coffee) || (ha[i][C] != Green && ha[i][D] == Coffee))) return Invalid; if ((ha[i][S] >= 0 && ha[i][A] >= 0) && ((ha[i][S] == PallMall && ha[i][A] != Birds) || (ha[i][S] != PallMall && ha[i][A] == Birds))) return Invalid; if ((ha[i][S] >= 0 && ha[i][C] >= 0) && ((ha[i][S] == Dunhill && ha[i][C] != Yellow) || (ha[i][S] != Dunhill && ha[i][C] == Yellow))) return Invalid; if (ha[i][S] == Blend) { if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats) return Invalid; else if (i == 4 && ha[i - 1][A] != Cats) return Invalid; else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Cats && ha[i - 1][A] != Cats) return Invalid; } if (ha[i][S] == Dunhill) { if (i == 0 && ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse) return Invalid; else if (i == 4 && ha[i - 1][A] != Horse) return Invalid; else if (ha[i + 1][A] >= 0 && ha[i + 1][A] != Horse && ha[i - 1][A] != Horse) return Invalid; } if ((ha[i][S] >= 0 && ha[i][D] >= 0) && ((ha[i][S] == BlueMaster && ha[i][D] != Beer) || (ha[i][S] != BlueMaster && ha[i][D] == Beer))) return Invalid; if ((ha[i][M] >= 0 && ha[i][S] >= 0) && ((ha[i][M] == German && ha[i][S] != Prince) || (ha[i][M] != German && ha[i][S] == Prince))) return Invalid; if (ha[i][M] == Norwegian && ((i < 4 && ha[i + 1][C] >= 0 && ha[i + 1][C] != Blue) || (i > 0 && ha[i - 1][C] != Blue))) return Invalid; if (ha[i][S] == Blend) { if (i == 0 && ha[i + 1][D] >= 0 && ha[i + 1][D] != Water) return Invalid; else if (i == 4 && ha[i - 1][D] != Water) return Invalid; else if (ha[i + 1][D] >= 0 && ha[i + 1][D] != Water && ha[i - 1][D] != Water) return Invalid; } } if ((c_add != c_or) || (m_add != m_or) || (d_add != d_or) || (a_add != a_or) || (s_add != s_or)) { return Invalid; } if ((c_add != 0b11111) || (m_add != 0b11111) || (d_add != 0b11111) || (a_add != 0b11111) || (s_add != 0b11111)) { return Underfull; } return Valid; } int bruteFill(int ha[5][5], int hno, int attr) { int stat = checkHouses(ha); if ((stat == Valid) || (stat == Invalid)) return stat; int hb[5][5]; memcpy(hb, ha, sizeof(int) * 5 * 5); for (int i = 0; i < 5; i++) { hb[hno][attr] = i; stat = checkHouses(hb); if (stat != Invalid) { int nexthno, nextattr; if (attr < 4) { nextattr = attr + 1; nexthno = hno; } else { nextattr = 0; nexthno = hno + 1; } stat = bruteFill(hb, nexthno, nextattr); if (stat != Invalid) { memcpy(ha, hb, sizeof(int) * 5 * 5); return stat; } } } return Invalid; } int main() { int ha[5][5] = {{-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1}}; bruteFill(ha, 0, 0); printHouses(ha); return 0; }
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, path=api_path) all_tasks = site.categories['Programming Tasks'] language_tasks = site.categories[language] name = attrgetter('name') all_tasks_names = map(name, all_tasks) language_tasks_names = set(map(name, language_tasks)) for task in all_tasks_names: if task not in language_tasks_names: yield task if __name__ == '__main__': tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH) print(*tasks, sep='\n')
#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_find_unimplemented_tasks.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; }
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, path=api_path) all_tasks = site.categories['Programming Tasks'] language_tasks = site.categories[language] name = attrgetter('name') all_tasks_names = map(name, all_tasks) language_tasks_names = set(map(name, language_tasks)) for task in all_tasks_names: if task not in language_tasks_names: yield task if __name__ == '__main__': tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH) print(*tasks, sep='\n')
#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_find_unimplemented_tasks.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; }
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 * cos(y / 32.0))) + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4) buffer[x + y * width] = value def draw(): global r, g, b, rd, gd, bd if r > 128: rd = True if not rd: r += 1 else: r-=1 if r < 0: rd = False if g > 128: gd = True if not gd: g += 1 else: g- = 1 if r < 0: gd = False if b > 128: bd = True if not bd: b += 1 else: b- = 1 if b < 0: bd = False for i in range(128): s_1 = sin(i * PI / 25) s_2 = sin(i * PI / 50 + PI / 4) pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128) loadPixels() for i, b in enumerate(buffer): pixels[i] = pal[(b + frameCount) % 127] updatePixels()
#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.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system("@clear||cls"); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf("%c",219); } getchar(); return 0; }
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 * cos(y / 32.0))) + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4) buffer[x + y * width] = value def draw(): global r, g, b, rd, gd, bd if r > 128: rd = True if not rd: r += 1 else: r-=1 if r < 0: rd = False if g > 128: gd = True if not gd: g += 1 else: g- = 1 if r < 0: gd = False if b > 128: bd = True if not bd: b += 1 else: b- = 1 if b < 0: bd = False for i in range(128): s_1 = sin(i * PI / 25) s_2 = sin(i * PI / 50 + PI / 4) pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128) loadPixels() for i, b in enumerate(buffer): pixels[i] = pal[(b + frameCount) % 127] updatePixels()
#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.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system("@clear||cls"); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf("%c",219); } getchar(); return 0; }
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, (g, 2)) if t == g else ( [t] + residue, (g, 0) ) def amber(tally, cn): c, n = cn return (tally, 2) if 2 == n else ( adjust( lambda x: x - 1, c, tally ), 1 ) if 0 < tally.get(c, 0) else (tally, 0) def main(): print(' -> '.join(['Target', 'Guess', 'Scores'])) print() print( '\n'.join([ wordleReport(*tg) for tg in [ ("ALLOW", "LOLLY"), ("CHANT", "LATTE"), ("ROBIN", "ALERT"), ("ROBIN", "SONIC"), ("ROBIN", "ROBIN"), ("BULLY", "LOLLY"), ("ADAPT", "SÅLÅD"), ("Ukraine", "Ukraíne"), ("BBAAB", "BBBBBAA"), ("BBAABBB", "AABBBAA") ] ]) ) def wordleReport(target, guess): scoreName = {2: 'green', 1: 'amber', 0: 'gray'} if 5 != len(target): return f'{target}: Expected 5 character target.' elif 5 != len(guess): return f'{guess}: Expected 5 character guess.' else: scores = wordleScore(target, guess) return ' -> '.join([ target, guess, repr(scores), ' '.join([ scoreName[n] for n in scores ]) ]) def adjust(f, k, dct): return dict( dct, **{k: f(dct[k]) if k in dct else None} ) def charCounts(s): return reduce( lambda a, c: insertWith(add)(c)(1)(a), list(s), {} ) def first(f): return lambda xy: (f(xy[0]), xy[1]) def insertWith(f): return lambda k: lambda x: lambda dct: dict( dct, **{k: f(dct[k], x) if k in dct else x} ) def mapAccumL(f): def nxt(a, x): return second(lambda v: a[1] + [v])( f(a[0], x) ) return lambda acc, xs: reduce( nxt, xs, (acc, []) ) def second(f): return lambda xy: (xy[0], f(xy[1])) if __name__ == '__main__': main()
#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]; strcpy(answer2, answer); for (i = 0; i < n; ++i) { if (guess[i] == answer2[i]) { answer2[i] = '\v'; result[i] = 2; } } for (i = 0; i < n; ++i) { if ((ptr = strchr(answer2, guess[i])) != NULL) { ix = ptr - answer2; answer2[ix] = '\v'; result[i] = 1; } } } int main() { int i, j; const char *answer, *guess; int res[5]; const char *res2[5]; const char *colors[3] = {"grey", "yellow", "green"}; const char *pairs[5][2] = { {"ALLOW", "LOLLY"}, {"BULLY", "LOLLY"}, {"ROBIN", "ALERT"}, {"ROBIN", "SONIC"}, {"ROBIN", "ROBIN"} }; for (i = 0; i < 5; ++i) { answer = pairs[i][0]; guess = pairs[i][1]; for (j = 0; j < 5; ++j) res[j] = 0; wordle(answer, guess, res); for (j = 0; j < 5; ++j) res2[j] = colors[res[j]]; printf("%s v %s => { ", answer, guess); for (j = 0; j < 5; ++j) printf("%d ", res[j]); printf("} => { "); for (j = 0; j < 5; ++j) printf("%s ", res2[j]); printf("}\n"); } return 0; }
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 = a->count * (1 + a->kid_idx) >> a->depth; int bc = b->count * (1 + b->kid_idx) >> b->depth; return ac < bc ? -1 : ac > bc; } oct_node node_insert(oct_node root, unsigned char *pix) { # define OCT_DEPTH 8 unsigned char i, bit, depth = 0; for (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) { i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit); if (!root->kids[i]) root->kids[i] = node_new(i, depth, root); root = root->kids[i]; } root->r += pix[0]; root->g += pix[1]; root->b += pix[2]; root->count++; return root; } oct_node node_fold(oct_node p) { if (p->n_kids) abort(); oct_node q = p->parent; q->count += p->count; q->r += p->r; q->g += p->g; q->b += p->b; q->n_kids --; q->kids[p->kid_idx] = 0; return q; } void color_replace(oct_node root, unsigned char *pix) { unsigned char i, bit; for (bit = 1 << 7; bit; bit >>= 1) { i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit); if (!root->kids[i]) break; root = root->kids[i]; } pix[0] = root->r; pix[1] = root->g; pix[2] = root->b; } void color_quant(image im, int n_colors) { int i; unsigned char *pix = im->pix; node_heap heap = { 0, 0, 0 }; oct_node root = node_new(0, 0, 0), got; for (i = 0; i < im->w * im->h; i++, pix += 3) heap_add(&heap, node_insert(root, pix)); while (heap.n > n_colors + 1) heap_add(&heap, node_fold(pop_heap(&heap))); double c; for (i = 1; i < heap.n; i++) { got = heap.buf[i]; c = got->count; got->r = got->r / c + .5; got->g = got->g / c + .5; got->b = got->b / c + .5; printf("%2d | %3llu %3llu %3llu (%d pixels)\n", i, got->r, got->g, got->b, got->count); } for (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3) color_replace(root, pix); node_free(); free(heap.buf); }
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 self.generic_visit(node) filename = input('Enter a filename to parse: ') with open(filename, encoding='utf-8') as f: contents = f.read() root = ast.parse(contents, filename=filename) visitor = CallCountingVisitor() visitor.visit(root) top10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10] for name, count in top10: print(name,'called',count,'times')
#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(struct functionInfo** list, struct functionInfo toAdd, \ size_t* numElements, size_t* allocatedSize) { static const char* keywords[32] = {"auto", "break", "case", "char", "const", \ "continue", "default", "do", "double", \ "else", "enum", "extern", "float", "for", \ "goto", "if", "int", "long", "register", \ "return", "short", "signed", "sizeof", \ "static", "struct", "switch", "typedef", \ "union", "unsigned", "void", "volatile", \ "while" }; int i; for (i = 0; i < 32; i++) { if (!strcmp(toAdd.name, keywords[i])) { return; } } if (!*list) { *allocatedSize = 10; *list = calloc(*allocatedSize, sizeof(struct functionInfo)); if (!*list) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ *allocatedSize, sizeof(struct functionInfo)); abort(); } (*list)[0].name = malloc(strlen(toAdd.name)+1); if (!(*list)[0].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[0].name, toAdd.name); (*list)[0].timesCalled = 1; (*list)[0].marked = 0; *numElements = 1; } else { char found = 0; unsigned int i; for (i = 0; i < *numElements; i++) { if (!strcmp((*list)[i].name, toAdd.name)) { found = 1; (*list)[i].timesCalled++; break; } } if (!found) { struct functionInfo* newList = calloc((*allocatedSize)+10, \ sizeof(struct functionInfo)); if (!newList) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ (*allocatedSize)+10, sizeof(struct functionInfo)); abort(); } memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo)); free(*list); *allocatedSize += 10; *list = newList; (*list)[*numElements].name = malloc(strlen(toAdd.name)+1); if (!(*list)[*numElements].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[*numElements].name, toAdd.name); (*list)[*numElements].timesCalled = 1; (*list)[*numElements].marked = 0; (*numElements)++; } } } void printList(struct functionInfo** list, size_t numElements) { char maxSet = 0; unsigned int i; size_t maxIndex = 0; for (i = 0; i<10; i++) { maxSet = 0; size_t j; for (j = 0; j<numElements; j++) { if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) { if (!(*list)[j].marked) { maxSet = 1; maxIndex = j; } } } (*list)[maxIndex].marked = 1; printf("%s() called %d times.\n", (*list)[maxIndex].name, \ (*list)[maxIndex].timesCalled); } } void freeList(struct functionInfo** list, size_t numElements) { size_t i; for (i = 0; i<numElements; i++) { free((*list)[i].name); } free(*list); } char* extractFunctionName(char* readHead) { char* identifier = readHead; if (isalpha(*identifier) || *identifier == '_') { while (isalnum(*identifier) || *identifier == '_') { identifier++; } } char* toParen = identifier; if (toParen == readHead) return NULL; while (isspace(*toParen)) { toParen++; } if (*toParen != '(') return NULL; ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \ - ((ptrdiff_t)readHead)+1; char* const name = malloc(size); if (!name) { printf("Failed to allocate %lu bytes.\n", size); abort(); } name[size-1] = '\0'; memcpy(name, readHead, size-1); if (strcmp(name, "")) { return name; } free(name); return NULL; } int main(int argc, char** argv) { int i; for (i = 1; i<argc; i++) { errno = 0; FILE* file = fopen(argv[i], "r"); if (errno || !file) { printf("fopen() failed with error code \"%s\"\n", \ strerror(errno)); abort(); } char comment = 0; #define DOUBLEQUOTE 1 #define SINGLEQUOTE 2 int string = 0; struct functionInfo* functions = NULL; struct functionInfo toAdd; size_t numElements = 0; size_t allocatedSize = 0; struct stat metaData; errno = 0; if (fstat(fileno(file), &metaData) < 0) { printf("fstat() returned error \"%s\"\n", strerror(errno)); abort(); } char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \ MAP_PRIVATE, fileno(file), 0); if (errno) { printf("mmap() failed with error \"%s\"\n", strerror(errno)); abort(); } if (!mmappedSource) { printf("mmap() returned NULL.\n"); abort(); } char* readHead = mmappedSource; while (readHead < mmappedSource + metaData.st_size) { while (*readHead) { if (!string) { if (*readHead == '/' && !strncmp(readHead, "", 2)) { comment = 0; } } if (!comment) { if (*readHead == '"') { if (!string) { string = DOUBLEQUOTE; } else if (string == DOUBLEQUOTE) { if (strncmp((readHead-1), "\\\"", 2)) { string = 0; } } } if (*readHead == '\'') { if (!string) { string = SINGLEQUOTE; } else if (string == SINGLEQUOTE) { if (strncmp((readHead-1), "\\\'", 2)) { string = 0; } } } } if (!comment && !string) { char* name = extractFunctionName(readHead); if (name) { toAdd.name = name; addToList(&functions, toAdd, &numElements, &allocatedSize); readHead += strlen(name); } free(name); } readHead++; } } errno = 0; munmap(mmappedSource, metaData.st_size); if (errno) { printf("munmap() returned error \"%s\"\n", strerror(errno)); abort(); } errno = 0; fclose(file); if (errno) { printf("fclose() returned error \"%s\"\n", strerror(errno)); abort(); } printList(&functions, numElements); freeList(&functions, numElements); } return 0; }
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("%lc\n", 0x2708); printf("%ls\n", poker); printf("%ls\n", four_two); #else printf("airplane\n"); printf("club diamond club spade\n"); printf("for ty two\n"); #endif return 0; }
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("%lc\n", 0x2708); printf("%ls\n", poker); printf("%ls\n", four_two); #else printf("airplane\n"); printf("club diamond club spade\n"); printf("for ty two\n"); #endif return 0; }
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) for __ in rs232_9pin] class RS232_25pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
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 : 1; unsigned ring_indicator : 1; };
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): num += 1 if num < 21: print('{:2}'.format(n), "+", '{:2}'.format(n+1), "=", '{:2}'.format(suma)) else: break
#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] = TRUE; } p = 3; while (TRUE) { p2 = p * p; if (p2 >= limit) break; for (i = p2; i < limit; i += 2*p) c[i] = TRUE; while (TRUE) { p += 2; if (!c[p]) break; } } if (primesOnly) { c[0] = 2; for (i = 3, ix = 1; i < limit; i += 2) { if (!c[i]) c[ix++] = i; } } } int main() { int i, p, hp, n = 10000000; int limit = (int)(log(n) * (double)n * 1.2); int *primes = (int *)calloc(limit, sizeof(int)); primeSieve(primes, limit-1, FALSE, TRUE); printf("The first 20 pairs of natural numbers whose sum is prime are:\n"); for (i = 1; i <= 20; ++i) { p = primes[i]; hp = p / 2; printf("%2d + %2d = %2d\n", hp, hp+1, p); } printf("\nThe 10 millionth such pair is:\n"); p = primes[n]; hp = p / 2; printf("%2d + %2d = %2d\n", hp, hp+1, p); free(primes); return 0; }
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): num += 1 if num < 21: print('{:2}'.format(n), "+", '{:2}'.format(n+1), "=", '{:2}'.format(suma)) else: break
#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] = TRUE; } p = 3; while (TRUE) { p2 = p * p; if (p2 >= limit) break; for (i = p2; i < limit; i += 2*p) c[i] = TRUE; while (TRUE) { p += 2; if (!c[p]) break; } } if (primesOnly) { c[0] = 2; for (i = 3, ix = 1; i < limit; i += 2) { if (!c[i]) c[ix++] = i; } } } int main() { int i, p, hp, n = 10000000; int limit = (int)(log(n) * (double)n * 1.2); int *primes = (int *)calloc(limit, sizeof(int)); primeSieve(primes, limit-1, FALSE, TRUE); printf("The first 20 pairs of natural numbers whose sum is prime are:\n"); for (i = 1; i <= 20; ++i) { p = primes[i]; hp = p / 2; printf("%2d + %2d = %2d\n", hp, hp+1, p); } printf("\nThe 10 millionth such pair is:\n"); p = primes[n]; hp = p / 2; printf("%2d + %2d = %2d\n", hp, hp+1, p); free(primes); return 0; }
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 = atomic - prev_noble if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE: row += 2 col = rank + 1 else: nb_empty = LINE_WIDTH - nb_elem inside_left_element_rank = 2 if noble > 2 else 1 col = rank + (nb_empty if rank > inside_left_element_rank else 0) break prev_noble = noble return row+1, col TESTS = { 1: (1, 1), 2: (1, 18), 29: (4,11), 42: (5, 6), 58: (8, 5), 59: (8, 6), 57: (8, 4), 71: (8, 18), 72: (6, 4), 89: (9, 4), 90: (9, 5), 103: (9, 18), } for input, out in TESTS.items(): found = perta(input) print('TEST:{:3d} -> '.format(input) + str(found) + (f' ; ERROR: expected {out}' if found != out else ''))
#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; Resize_terminal(42,135); Init_video( &table ); Gpm_Connect conn; if ( ! Init_mouse(&conn)){ Msg_red("No se puede conectar al servidor del ratón\n"); Stop(1); } Enable_raw_mode(); Hide_cursor; New multitype Elements; Elements = load_chem_elements( pSDS(Elements) ); Throw( load_fail ); New objects Btn_exit; Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, " Terminar ", 6,44, 15, 0); table = put_chemical_cell( table, SDS(Elements) ); Refresh(table); Put object Btn_exit; int c; Waiting_some_clic(c) { if( select_box_chemical_elem(SDS(Elements)) ){ Waiting_some_clic(c) break; } if (Object_mouse( Btn_exit)) break; Refresh(table); Put object Btn_exit; } Free object Btn_exit; Free multitype Elements; Exception( load_fail ){ Msg_red("No es un archivo matriciable"); } Free video table; Disable_raw_mode(); Close_mouse(); Show_cursor; At SIZE_TERM_ROWS,0; Prnl; End void put_information(RDS(MT_CELL, elem), int i) { At 2,19; Box_solid(11,64,67,17); Color(15,17); At 4,22; Print "Elemento (%s) = %s", (char*)$s-elem[i,5],(char*)$s-elem[i,6]; if (Cell_type(elem,i,7) == double_TYPE ){ At 5,22; Print "Peso atómico = %f", $d-elem[i,7]; }else{ At 5,22; Print "Peso atómico = (%ld)", $l-elem[i,7]; } At 6,22; Print "Posición = (%ld, %ld)",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1; At 8,22; Print "1ª energía de"; if (Cell_type(elem,i,12) == double_TYPE ){ At 9,22; Print "ionización (kJ/mol) = %.*f",2,$d-elem[i,12]; }else{ At 9,22; Print "ionización (kJ/mol) = ---"; } if (Cell_type(elem,i,13) == double_TYPE ){ At 10,22; Print "Electronegatividad = %.*f",2,$d-elem[i,13]; }else{ At 10,22; Print "Electronegatividad = ---"; } At 4,56; Print "Conf. electrónica:"; At 5,56; Print " %s", (char*)$s-elem[i,14]; At 7,56; Print "Estados de oxidación:"; if ( Cell_type(elem,i,15) == string_TYPE ){ At 8,56; Print " %s", (char*)$s-elem[i,15]; }else{ At 8,56; Print " %ld", $l-elem[i,15]; } At 10,56; Print "Número Atómico: %ld",$l-elem[i,4]; Reset_color; } int select_box_chemical_elem( RDS(MT_CELL, elem) ) { int i; Iterator up i [0:1:Rows(elem)]{ if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){ Gotoxy( $l-elem[i,8], $l-elem[i,9] ); Color_fore( 15 ); Color_back( 0 ); Box( 4,5, DOUB_ALL ); Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print "%ld",$l-elem[i,4]; Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print "%s",(char*)$s-elem[i,5]; Flush_out; Reset_color; put_information(SDS(elem),i); return 1; } } return 0; } GD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data) { int i; Iterator up i [0:1:Rows(elem)]{ long rx = 2+($l-elem[i,0]*4); long cx = 3+($l-elem[i,1]*7); long offr = rx+3; long offc = cx+6; Gotoxy(table, rx, cx); Color_fore(table, $l-elem[i,2]); Color_back(table,$l-elem[i,3]); Box(table, 4,5, SING_ALL ); char Atnum[50], Elem[50]; sprintf(Atnum,"\x1b[3m%ld\x1b[23m",$l-elem[i,4]); sprintf(Elem, "\x1b[1m%s\x1b[22m",(char*)$s-elem[i,5]); Outvid(table,rx+1, cx+2, Atnum); Outvid(table,rx+2, cx+2, Elem); Reset_text(table); $l-elem[i,8] = rx; $l-elem[i,9] = cx; $l-elem[i,10] = offr; $l-elem[i,11] = offc; } Iterator up i [ 1: 1: 19 ]{ Gotoxy(table, 31, 5+(i-1)*7); char num[5]; sprintf( num, "%d",i ); Outvid(table, num ); } Iterator up i [ 1: 1: 8 ]{ Gotoxy(table, 3+(i-1)*4, 130); char num[5]; sprintf( num, "%d",i ); Outvid(table, num ); } Outvid( table, 35,116, "8"); Outvid( table, 39,116, "9"); Color_fore(table, 15); Color_back(table, 0); Outvid(table,35,2,"Lantánidos ->"); Outvid(table,39,2,"Actínidos ->"); Reset_text(table); return table; } MT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data ) { F_STAT dataFile = Stat_file("chem_table.txt"); if( dataFile.is_matrix ){ Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1]; E = Load_matrix_mt( SDS(E), "chem_table.txt", dataFile, DET_LONG); }else{ Is_ok=0; } return E; }
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[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
#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 - b.y); BIN_V(add, a.x + b.x, a.y + b.y); BIN_S(dot, a.x * b.x + a.y * b.y); BIN_S(cross, a.x * b.y - a.y * b.x); vec vmadd(vec a, double s, vec b) { vec c; c.x = a.x + s * b.x; c.y = a.y + s * b.y; return c; } int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect) { vec dx = vsub(x1, x0), dy = vsub(y1, y0); double d = vcross(dy, dx), a; if (!d) return 0; a = (vcross(x0, dx) - vcross(y0, dx)) / d; if (sect) *sect = vmadd(y0, a, dy); if (a < -tol || a > 1 + tol) return -1; if (a < tol || a > 1 - tol) return 0; a = (vcross(x0, dy) - vcross(y0, dy)) / d; if (a < 0 || a > 1) return -1; return 1; } double dist(vec x, vec y0, vec y1, double tol) { vec dy = vsub(y1, y0); vec x1, s; int r; x1.x = x.x + dy.y; x1.y = x.y - dy.x; r = intersect(x, x1, y0, y1, tol, &s); if (r == -1) return HUGE_VAL; s = vsub(s, x); return sqrt(vdot(s, s)); } #define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++) int inside(vec v, polygon p, double tol) { int i, k, crosses, intersectResult; vec *pv; double min_x, max_x, min_y, max_y; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; min_x = dist(v, p->v[i], p->v[k], tol); if (min_x < tol) return 0; } min_x = max_x = p->v[0].x; min_y = max_y = p->v[1].y; for_v(i, pv, p) { if (pv->x > max_x) max_x = pv->x; if (pv->x < min_x) min_x = pv->x; if (pv->y > max_y) max_y = pv->y; if (pv->y < min_y) min_y = pv->y; } if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y) return -1; max_x -= min_x; max_x *= 2; max_y -= min_y; max_y *= 2; max_x += max_y; vec e; while (1) { crosses = 0; e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x; e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0); if (!intersectResult) break; if (intersectResult == 1) crosses++; } if (i == p->n) break; } return (crosses & 1) ? 1 : -1; } int main() { vec vsq[] = { {0,0}, {10,0}, {10,10}, {0,10}, {2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}}; polygon_t sq = { 4, vsq }, sq_hole = { 8, vsq }; vec c = { 10, 5 }; vec d = { 5, 5 }; printf("%d\n", inside(c, &sq, 1e-10)); printf("%d\n", inside(c, &sq_hole, 1e-10)); printf("%d\n", inside(d, &sq, 1e-10)); printf("%d\n", inside(d, &sq_hole, 1e-10)); return 0; }
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 = a + b = %s%n", c); Pt d = c.neg(); System.out.printf("d = -c = %s%n", d); System.out.printf("c + d = %s%n", c.plus(d)); System.out.printf("a + b + d = %s%n", a.plus(b).plus(d)); System.out.printf("a * 12345 = %s%n", a.mult(12345)); } } class Pt { final static int bCoeff = 7; double x, y; Pt(double x, double y) { this.x = x; this.y = y; } static Pt zero() { return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); } boolean isZero() { return this.x > 1e20 || this.x < -1e20; } static Pt fromY(double y) { return new Pt(cbrt(pow(y, 2) - bCoeff), y); } Pt dbl() { if (isZero()) return this; double L = (3 * this.x * this.x) / (2 * this.y); double x2 = pow(L, 2) - 2 * this.x; return new Pt(x2, L * (this.x - x2) - this.y); } Pt neg() { return new Pt(this.x, -this.y); } Pt plus(Pt q) { if (this.x == q.x && this.y == q.y) return dbl(); if (isZero()) return q; if (q.isZero()) return this; double L = (q.y - this.y) / (q.x - this.x); double xx = pow(L, 2) - this.x - q.x; return new Pt(xx, L * (this.x - xx) - this.y); } Pt mult(int n) { Pt r = Pt.zero(); Pt p = this; for (int i = 1; i <= n; i <<= 1) { if ((i & n) != 0) r = r.plus(p); p = p.dbl(); } return r; } @Override public String toString() { if (isZero()) return "Zero"; return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y); } }
#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) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
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 = a + b = %s%n", c); Pt d = c.neg(); System.out.printf("d = -c = %s%n", d); System.out.printf("c + d = %s%n", c.plus(d)); System.out.printf("a + b + d = %s%n", a.plus(b).plus(d)); System.out.printf("a * 12345 = %s%n", a.mult(12345)); } } class Pt { final static int bCoeff = 7; double x, y; Pt(double x, double y) { this.x = x; this.y = y; } static Pt zero() { return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); } boolean isZero() { return this.x > 1e20 || this.x < -1e20; } static Pt fromY(double y) { return new Pt(cbrt(pow(y, 2) - bCoeff), y); } Pt dbl() { if (isZero()) return this; double L = (3 * this.x * this.x) / (2 * this.y); double x2 = pow(L, 2) - 2 * this.x; return new Pt(x2, L * (this.x - x2) - this.y); } Pt neg() { return new Pt(this.x, -this.y); } Pt plus(Pt q) { if (this.x == q.x && this.y == q.y) return dbl(); if (isZero()) return q; if (q.isZero()) return this; double L = (q.y - this.y) / (q.x - this.x); double xx = pow(L, 2) - this.x - q.x; return new Pt(xx, L * (this.x - xx) - this.y); } Pt mult(int n) { Pt r = Pt.zero(); Pt p = this; for (int i = 1; i <= n; i <<= 1) { if ((i & n) != 0) r = r.plus(p); p = p.dbl(); } return r; } @Override public String toString() { if (isZero()) return "Zero"; return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y); } }
#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) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
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 = a + b = %s%n", c); Pt d = c.neg(); System.out.printf("d = -c = %s%n", d); System.out.printf("c + d = %s%n", c.plus(d)); System.out.printf("a + b + d = %s%n", a.plus(b).plus(d)); System.out.printf("a * 12345 = %s%n", a.mult(12345)); } } class Pt { final static int bCoeff = 7; double x, y; Pt(double x, double y) { this.x = x; this.y = y; } static Pt zero() { return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); } boolean isZero() { return this.x > 1e20 || this.x < -1e20; } static Pt fromY(double y) { return new Pt(cbrt(pow(y, 2) - bCoeff), y); } Pt dbl() { if (isZero()) return this; double L = (3 * this.x * this.x) / (2 * this.y); double x2 = pow(L, 2) - 2 * this.x; return new Pt(x2, L * (this.x - x2) - this.y); } Pt neg() { return new Pt(this.x, -this.y); } Pt plus(Pt q) { if (this.x == q.x && this.y == q.y) return dbl(); if (isZero()) return q; if (q.isZero()) return this; double L = (q.y - this.y) / (q.x - this.x); double xx = pow(L, 2) - this.x - q.x; return new Pt(xx, L * (this.x - xx) - this.y); } Pt mult(int n) { Pt r = Pt.zero(); Pt p = this; for (int i = 1; i <= n; i <<= 1) { if ((i & n) != 0) r = r.plus(p); p = p.dbl(); } return r; } @Override public String toString() { if (isZero()) return "Zero"; return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y); } }
#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) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
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("abab", "ababababab")); System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); } }
#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() { printf("%d\n", match("the three truths", "th", 0)); printf("overlap:%d\n", match("abababababa", "aba", 1)); printf("not: %d\n", match("abababababa", "aba", 0)); return 0; }
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 sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
#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 += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
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 sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
#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 += r; } return sum == 13; } int main() { int i, c; c = 0; for (i = 1; i < 1000000; i++) { if (primeDigitsSum13(i)) { printf("%6d ", i); if (c++ == 10) { c = 0; printf("\n"); } } } printf("\n"); return 0; }
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)) System.debug(A + ' and ' + B + ' are case-insensitive lexically equal.'); else System.debug(A + ' and ' + B + ' are not case-insensitive lexically equal.'); if (A.compareTo(B) < 0) System.debug(A + ' is lexically before ' + B); else if (A.compareTo(B) > 0) System.debug(A + ' is lexically after ' + B); if (A.compareTo(B) >= 0) System.debug(A + ' is not lexically before ' + B); if (A.compareTo(B) <= 0) System.debug(A + ' is not lexically after ' + B); System.debug('The lexical relationship is: ' + A.compareTo(B)); } }
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()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
#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); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 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 = new double[N]; static double[] r_sin = new double[N2]; static double[] r_cos = new double[N2]; static double[] r_tan = new double[N2]; static double rho(double[] x, double[] y, double[] r, int i, int n) { if (n < 0) return 0; if (n == 0) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } static double thiele(double[] x, double[] y, double[] r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } public static void main(String[] args) { for (int i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (int i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN; System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0)); System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0)); System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0)); } }
#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 idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } #define i_sin(x) thiele(t_sin, xval, r_sin, x, 0) #define i_cos(x) thiele(t_cos, xval, r_cos, x, 0) #define i_tan(x) thiele(t_tan, xval, r_tan, x, 0) int main() { int i; for (i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = 0/0.; printf("%16.14f\n", 6 * i_sin(.5)); printf("%16.14f\n", 3 * i_cos(.5)); printf("%16.14f\n", 4 * i_tan(1.)); return 0; }
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 result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
#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 + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
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 result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
#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 + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
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(" degrees gradiens mils radians%n"); for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) { for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) { double d = 0, g = 0, m = 0, r = 0; switch (units) { case "degrees": d = d2d(angle); g = d2g(d); m = d2m(d); r = d2r(d); break; case "gradiens": g = g2g(angle); d = g2d(g); m = g2m(g); r = g2r(g); break; case "mils": m = m2m(angle); d = m2d(m); g = m2g(m); r = m2r(m); break; case "radians": r = r2r(angle); d = r2d(r); g = r2g(r); m = r2m(r); break; } System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r)); } } } private static final double DEGREE = 360D; private static final double GRADIAN = 400D; private static final double MIL = 6400D; private static final double RADIAN = (2 * Math.PI); private static double d2d(double a) { return a % DEGREE; } private static double d2g(double a) { return a * (GRADIAN / DEGREE); } private static double d2m(double a) { return a * (MIL / DEGREE); } private static double d2r(double a) { return a * (RADIAN / 360); } private static double g2d(double a) { return a * (DEGREE / GRADIAN); } private static double g2g(double a) { return a % GRADIAN; } private static double g2m(double a) { return a * (MIL / GRADIAN); } private static double g2r(double a) { return a * (RADIAN / GRADIAN); } private static double m2d(double a) { return a * (DEGREE / MIL); } private static double m2g(double a) { return a * (GRADIAN / MIL); } private static double m2m(double a) { return a % MIL; } private static double m2r(double a) { return a * (RADIAN / MIL); } private static double r2d(double a) { return a * (DEGREE / RADIAN); } private static double r2g(double a) { return a * (GRADIAN / RADIAN); } private static double r2m(double a) { return a * (MIL / RADIAN); } private static double r2r(double a) { return a % RADIAN; } }
#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 += 6400; while (a >= 6400) a -= 6400; return a; } double normalize2rad(double a) { while (a < 0) a += TWO_PI; while (a >= TWO_PI) a -= TWO_PI; return a; } double deg2grad(double a) {return a * 10 / 9;} double deg2mil(double a) {return a * 160 / 9;} double deg2rad(double a) {return a * PI / 180;} double grad2deg(double a) {return a * 9 / 10;} double grad2mil(double a) {return a * 16;} double grad2rad(double a) {return a * PI / 200;} double mil2deg(double a) {return a * 9 / 160;} double mil2grad(double a) {return a / 16;} double mil2rad(double a) {return a * PI / 3200;} double rad2deg(double a) {return a * 180 / PI;} double rad2grad(double a) {return a * 200 / PI;} double rad2mil(double a) {return a * 3200 / PI;}
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]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
#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; } int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]); return 0; }
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]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
#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; } int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]); return 0; }
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.getAsInt(), (k, v) -> v == null ? 1 : v + 1); double target = nRepeats / (double) counts.size(); int deltaCount = (int) (delta / 100.0 * target); counts.forEach((k, v) -> { if (abs(target - v) >= deltaCount) System.out.printf("distribution potentially skewed " + "for '%s': '%d'%n", k, v); }); counts.keySet().stream().sorted().forEach(k -> System.out.printf("%d %d%n", k, counts.get(k))); } public static void main(String[] a) { distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1); } }
#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 n, int cnt, double delta) { int i = cnt, *bins = calloc(sizeof(int), n); double ratio; while (i--) bins[gen() - 1]++; for (i = 0; i < n; i++) { ratio = bins[i] * n / (double)cnt - 1; if (ratio > -delta && ratio < delta) continue; printf("bin %d out of range: %d (%g%% vs %g%%), ", i + 1, bins[i], ratio * 100, delta * 100); break; } free(bins); return i == n; } int main() { int cnt = 1; while ((cnt *= 10) <= 1000000) { printf("Count = %d: ", cnt); printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n"); } return 0; }
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 <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
#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*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
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 <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
#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*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
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 <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
#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*(n-1)/2 + k - 1]; } bool stirling_cache_create(stirling_cache* sc, int max) { int* values = calloc(max * (max + 1)/2, sizeof(int)); if (values == NULL) return false; sc->max = max; sc->values = values; for (int n = 1; n <= max; ++n) { for (int k = 1; k < n; ++k) { int s1 = stirling_number2(sc, n - 1, k - 1); int s2 = stirling_number2(sc, n - 1, k); values[n*(n-1)/2 + k - 1] = s1 + s2 * k; } } return true; } void stirling_cache_destroy(stirling_cache* sc) { free(sc->values); sc->values = NULL; } void print_stirling_numbers(stirling_cache* sc, int max) { printf("Stirling numbers of the second kind:\nn/k"); for (int k = 0; k <= max; ++k) printf(k == 0 ? "%2d" : "%8d", k); printf("\n"); for (int n = 0; n <= max; ++n) { printf("%2d ", n); for (int k = 0; k <= n; ++k) printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k)); printf("\n"); } } int main() { stirling_cache sc = { 0 }; const int max = 12; if (!stirling_cache_create(&sc, max)) { fprintf(stderr, "Out of memory\n"); return 1; } print_stirling_numbers(&sc, max); stirling_cache_destroy(&sc); return 0; }
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<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
#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_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
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<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
#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_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
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; }