Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite the snippet below in C so it works the same as the original Java code.
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; }
Generate an equivalent C version of this Java code.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
Change the following Java code into C without altering its purpose.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.io.*; public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.currentX = length; s.currentY = length; s.lineLength = length; s.begin(656); s.execute(rewrite(4)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private PeanoCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = "L"; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'L') sb.append("LFRFL-F-RFLFR+F+LFRFL"); else if (ch == 'R') sb.append("RFLFR+F+LFRFL-F-RFLFR"); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final int ANGLE = 90; }
#include <graphics.h> #include <math.h> void Peano(int x, int y, int lg, int i1, int i2) { if (lg == 1) { lineto(3*x,3*y); return; } lg = lg/3; Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); Peano(x+lg, y+lg, lg, i1, 1-i2); Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); } int main(void) { initwindow(1000,1000,"Peano, Peano"); Peano(0, 0, 1000, 0, 0); getch(); cleardevice(); return 0; }
Change the following Java code into C without altering its purpose.
import java.util.Random; public class SevenSidedDice { private static final Random rnd = new Random(); public static void main(String[] args) { SevenSidedDice now=new SevenSidedDice(); System.out.println("Random number from 1 to 7: "+now.seven()); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1+rnd.nextInt(5); } }
int rand5() { int r, rand_max = RAND_MAX - (RAND_MAX % 5); while ((r = rand()) >= rand_max); return r / (rand_max / 5) + 1; } int rand5_7() { int r; while ((r = rand5() * 5 + rand5()) >= 27); return r / 3 - 1; } int main() { printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n"); printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n"); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import static java.lang.Math.abs; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public class NoConnection { static int[][] links = { {2, 3, 4}, {3, 4, 5}, {2, 4}, {5}, {2, 3, 4}, {3, 4, 5}, }; static int[] pegs = new int[8]; public static void main(String[] args) { List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList()); do { Collections.shuffle(vals); for (int i = 0; i < pegs.length; i++) pegs[i] = vals.get(i); } while (!solved()); printResult(); } static boolean solved() { for (int i = 0; i < links.length; i++) for (int peg : links[i]) if (abs(pegs[i] - peg) == 1) return false; return true; } static void printResult() { System.out.printf(" %s %s%n", pegs[0], pegs[1]); System.out.printf("%s %s %s %s%n", pegs[2], pegs[3], pegs[4], pegs[5]); System.out.printf(" %s %s%n", pegs[6], pegs[7]); } }
#include <stdbool.h> #include <stdio.h> #include <math.h> int connections[15][2] = { {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, }; int pegs[8]; int num = 0; bool valid() { int i; for (i = 0; i < 15; i++) { if (abs(pegs[connections[i][0]] - pegs[connections[i][1]]) == 1) { return false; } } return true; } void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } void printSolution() { printf("----- %d -----\n", num++); printf(" %d %d\n", pegs[0], pegs[1]); printf("%d %d %d %d\n", pegs[2], pegs[3], pegs[4], pegs[5]); printf(" %d %d\n", pegs[6], pegs[7]); printf("\n"); } void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { int i; for (i = le; i <= ri; i++) { swap(pegs + le, pegs + i); solution(le + 1, ri); swap(pegs + le, pegs + i); } } } int main() { int i; for (i = 0; i < 8; i++) { pegs[i] = i + 1; } solution(0, 8 - 1); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
#include <stdio.h> #include <string.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 bool is_prime(ull n) { ull d; if (n < 2) return FALSE; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; d = 5; while (d * d <= n) { if (!(n % d)) return FALSE; d += 2; if (!(n % d)) return FALSE; d += 4; } return TRUE; } void ord(char *res, int n) { char suffix[3]; int m = n % 100; if (m >= 4 && m <= 20) { sprintf(res,"%dth", n); return; } switch(m % 10) { case 1: strcpy(suffix, "st"); break; case 2: strcpy(suffix, "nd"); break; case 3: strcpy(suffix, "rd"); break; default: strcpy(suffix, "th"); break; } sprintf(res, "%d%s", n, suffix); } bool is_magnanimous(ull n) { ull p, q, r; if (n < 10) return TRUE; for (p = 10; ; p *= 10) { q = n / p; r = n % p; if (!is_prime(q + r)) return FALSE; if (q < 10) break; } return TRUE; } void list_mags(int from, int thru, int digs, int per_line) { ull i = 0; int c = 0; char res1[13], res2[13]; if (from < 2) { printf("\nFirst %d magnanimous numbers:\n", thru); } else { ord(res1, from); ord(res2, thru); printf("\n%s through %s magnanimous numbers:\n", res1, res2); } for ( ; c < thru; ++i) { if (is_magnanimous(i)) { if (++c >= from) { printf("%*llu ", digs, i); if (!(c % per_line)) printf("\n"); } } } } int main() { list_mags(1, 45, 3, 15); list_mags(241, 250, 1, 10); list_mags(391, 400, 1, 10); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
#include <stdio.h> #include <string.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 bool is_prime(ull n) { ull d; if (n < 2) return FALSE; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; d = 5; while (d * d <= n) { if (!(n % d)) return FALSE; d += 2; if (!(n % d)) return FALSE; d += 4; } return TRUE; } void ord(char *res, int n) { char suffix[3]; int m = n % 100; if (m >= 4 && m <= 20) { sprintf(res,"%dth", n); return; } switch(m % 10) { case 1: strcpy(suffix, "st"); break; case 2: strcpy(suffix, "nd"); break; case 3: strcpy(suffix, "rd"); break; default: strcpy(suffix, "th"); break; } sprintf(res, "%d%s", n, suffix); } bool is_magnanimous(ull n) { ull p, q, r; if (n < 10) return TRUE; for (p = 10; ; p *= 10) { q = n / p; r = n % p; if (!is_prime(q + r)) return FALSE; if (q < 10) break; } return TRUE; } void list_mags(int from, int thru, int digs, int per_line) { ull i = 0; int c = 0; char res1[13], res2[13]; if (from < 2) { printf("\nFirst %d magnanimous numbers:\n", thru); } else { ord(res1, from); ord(res2, thru); printf("\n%s through %s magnanimous numbers:\n", res1, res2); } for ( ; c < thru; ++i) { if (is_magnanimous(i)) { if (++c >= from) { printf("%*llu ", digs, i); if (!(c % per_line)) printf("\n"); } } } } int main() { list_mags(1, 45, 3, 15); list_mags(241, 250, 1, 10); list_mags(391, 400, 1, 10); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.*; public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0; public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); } public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); } public int count() { return count_; } private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } } private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); } private static int nextOddNumber(int n) { return 1 + 2 * (n/2); } public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define CHUNK_BYTES (32 << 8) #define CHUNK_SIZE (CHUNK_BYTES << 6) int field[CHUNK_BYTES]; #define GET(x) (field[(x)>>6] & 1<<((x)>>1&31)) #define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31)) typedef unsigned uint; typedef struct { uint *e; uint cap, len; } uarray; uarray primes, offset; void push(uarray *a, uint n) { if (a->len >= a->cap) { if (!(a->cap *= 2)) a->cap = 16; a->e = realloc(a->e, sizeof(uint) * a->cap); } a->e[a->len++] = n; } uint low; void init(void) { uint p, q; unsigned char f[1<<16]; memset(f, 0, sizeof(f)); push(&primes, 2); push(&offset, 0); for (p = 3; p < 1<<16; p += 2) { if (f[p]) continue; for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1; push(&primes, p); push(&offset, q); } low = 1<<16; } void sieve(void) { uint i, p, q, hi, ptop; if (!low) init(); memset(field, 0, sizeof(field)); hi = low + CHUNK_SIZE; ptop = sqrt(hi) * 2 + 1; for (i = 1; (p = primes.e[i]*2) < ptop; i++) { for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p) SET(q); offset.e[i] = q + low; } for (p = 1; p < CHUNK_SIZE; p += 2) if (!GET(p)) push(&primes, low + p); low = hi; } int main(void) { uint i, p, c; while (primes.len < 20) sieve(); printf("First 20:"); for (i = 0; i < 20; i++) printf(" %u", primes.e[i]); putchar('\n'); while (primes.e[primes.len-1] < 150) sieve(); printf("Between 100 and 150:"); for (i = 0; i < primes.len; i++) { if ((p = primes.e[i]) >= 100 && p < 150) printf(" %u", primes.e[i]); } putchar('\n'); while (primes.e[primes.len-1] < 8000) sieve(); for (i = c = 0; i < primes.len; i++) if ((p = primes.e[i]) >= 7700 && p < 8000) c++; printf("%u primes between 7700 and 8000\n", c); for (c = 10; c <= 100000000; c *= 10) { while (primes.len < c) sieve(); printf("%uth prime: %u\n", c, primes.e[c-1]); } return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Random; public class RPS { public enum Item{ ROCK, PAPER, SCISSORS, ; public List<Item> losesToList; public boolean losesTo(Item other) { return losesToList.contains(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK); ROCK.losesToList = Arrays.asList(PAPER); PAPER.losesToList = Arrays.asList(SCISSORS); } } public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{ for(Item item:Item.values()) put(item, 1); }}; private int totalThrows = Item.values().length; public static void main(String[] args){ RPS rps = new RPS(); rps.run(); } public void run() { Scanner in = new Scanner(System.in); System.out.print("Make your choice: "); while(in.hasNextLine()){ Item aiChoice = getAIChoice(); String input = in.nextLine(); Item choice; try{ choice = Item.valueOf(input.toUpperCase()); }catch (IllegalArgumentException ex){ System.out.println("Invalid choice"); continue; } counts.put(choice, counts.get(choice) + 1); totalThrows++; System.out.println("Computer chose: " + aiChoice); if(aiChoice == choice){ System.out.println("Tie!"); }else if(aiChoice.losesTo(choice)){ System.out.println("You chose...wisely. You win!"); }else{ System.out.println("You chose...poorly. You lose!"); } System.out.print("Make your choice: "); } } private static final Random rng = new Random(); private Item getAIChoice() { int rand = rng.nextInt(totalThrows); for(Map.Entry<Item, Integer> entry:counts.entrySet()){ Item item = entry.getKey(); int count = entry.getValue(); if(rand < count){ List<Item> losesTo = item.losesToList; return losesTo.get(rng.nextInt(losesTo.size())); } rand -= count; } return null; } }
#include <stdio.h> #include <stdlib.h> #define LEN 3 int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0); int i; for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; } int main() { int user_action, my_action; int user_rec[] = {0, 0, 0}; const char *names[] = { "Rock", "Paper", "Scissors" }; char str[2]; const char *winner[] = { "We tied.", "Meself winned.", "You win." }; double p[LEN] = { 1./3, 1./3, 1./3 }; while (1) { my_action = rand_idx(p,LEN); printf("\nYour choice [1-3]:\n" " 1. Rock\n 2. Paper\n 3. Scissors\n> "); if (!scanf("%d", &user_action)) { scanf("%1s", str); if (*str == 'q') { printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]); return 0; } continue; } user_action --; if (user_action > 2 || user_action < 0) { printf("invalid choice; again\n"); continue; } printf("You chose %s; I chose %s. %s\n", names[user_action], names[my_action], winner[(my_action - user_action + 3) % 3]); user_rec[user_action]++; } }
Please provide an equivalent version of this Java code in C.
import java.util.Scanner; public class twoDimArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nbr1 = in.nextInt(); int nbr2 = in.nextInt(); double[][] array = new double[nbr1][nbr2]; array[0][0] = 42.0; System.out.println("The number at place [0 0] is " + array[0][0]); } }
#include <stdio.h> int main(int argc, char **argv) { int user1 = 0, user2 = 0; printf("Enter two integers. Space delimited, please: "); scanf("%d %d",&user1, &user2); int array[user1][user2]; array[user1/2][user2/2] = user1 + user2; printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
import java.util.Scanner; public class twoDimArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nbr1 = in.nextInt(); int nbr2 = in.nextInt(); double[][] array = new double[nbr1][nbr2]; array[0][0] = 42.0; System.out.println("The number at place [0 0] is " + array[0][0]); } }
#include <stdio.h> int main(int argc, char **argv) { int user1 = 0, user2 = 0; printf("Enter two integers. Space delimited, please: "); scanf("%d %d",&user1, &user2); int array[user1][user2]; array[user1/2][user2/2] = user1 + user2; printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]); return 0; }
Translate this program into C but keep the logic exactly as in Java.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Keep all operations the same but rewrite the snippet in C.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Convert this Java block to C, preserving its control flow and logic.
public class Vig{ static String encodedMessage = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; final static double freq[] = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; public static void main(String[] args) { int lenghtOfEncodedMessage = encodedMessage.length(); char[] encoded = new char [lenghtOfEncodedMessage] ; char[] key = new char [lenghtOfEncodedMessage] ; encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0); int txt[] = new int[lenghtOfEncodedMessage]; int len = 0, j; double fit, best_fit = 1e100; for (j = 0; j < lenghtOfEncodedMessage; j++) if (Character.isUpperCase(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); System.out.printf("%f, key length: %2d ", fit, j); System.out.print(key); if (fit < best_fit) { best_fit = fit; System.out.print(" <--- best so far"); } System.out.print("\n"); } } static String decrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length(); } return res; } static int best_match(final double []a, final double []b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } static double freq_every_nth(final int []msg, int len, int interval, char[] key) { double sum, d, ret; double [] accu = new double [26]; double [] out = new double [26]; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; rot = best_match(out, freq); try{ key[j] = (char)(rot + 'A'); } catch (Exception e) { System.out.print(e.getMessage()); } for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; const double freq[] = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; int best_match(const double *a, const double *b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } double freq_every_nth(const int *msg, int len, int interval, char *key) { double sum, d, ret; double out[26], accu[26] = {0}; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; key[j] = rot = best_match(out, freq); key[j] += 'A'; for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } int main() { int txt[strlen(encoded)]; int len = 0, j; char key[100]; double fit, best_fit = 1e100; for (j = 0; encoded[j] != '\0'; j++) if (isupper(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); printf("%f, key length: %2d, %s", fit, j, key); if (fit < best_fit) { best_fit = fit; printf(" <--- best so far"); } printf("\n"); } return 0; }
Generate an equivalent C version of this Java code.
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
#include <stdio.h> #include <stdlib.h> #include <gmp.h> mpz_t tmp1, tmp2, t5, t239, pows; void actan(mpz_t res, unsigned long base, mpz_t pows) { int i, neg = 1; mpz_tdiv_q_ui(res, pows, base); mpz_set(tmp1, res); for (i = 3; ; i += 2) { mpz_tdiv_q_ui(tmp1, tmp1, base * base); mpz_tdiv_q_ui(tmp2, tmp1, i); if (mpz_cmp_ui(tmp2, 0) == 0) break; if (neg) mpz_sub(res, res, tmp2); else mpz_add(res, res, tmp2); neg = !neg; } } char * get_digits(int n, size_t* len) { mpz_ui_pow_ui(pows, 10, n + 20); actan(t5, 5, pows); mpz_mul_ui(t5, t5, 16); actan(t239, 239, pows); mpz_mul_ui(t239, t239, 4); mpz_sub(t5, t5, t239); mpz_ui_pow_ui(pows, 10, 20); mpz_tdiv_q(t5, t5, pows); *len = mpz_sizeinbase(t5, 10); return mpz_get_str(0, 0, t5); } int main(int c, char **v) { unsigned long accu = 16384, done = 0; size_t got; char *s; mpz_init(tmp1); mpz_init(tmp2); mpz_init(t5); mpz_init(t239); mpz_init(pows); while (1) { s = get_digits(accu, &got); got -= 2; while (s[got] == '0' || s[got] == '9') got--; printf("%.*s", (int)(got - done), s + done); free(s); done = got; accu *= 2; } return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); for (flip = 0, i = 1; i < N; i++) flip += q[i] > q[i + 1]; printf("flips: %d\n", flip); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); for (flip = 0, i = 1; i < N; i++) flip += q[i] > q[i + 1]; printf("flips: %d\n", flip); return 0; }
Convert this Java block to C, preserving its control flow and logic.
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); for (flip = 0, i = 1; i < N; i++) flip += q[i] > q[i + 1]; printf("flips: %d\n", flip); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
#include <stdio.h> #include <stdlib.h> typedef struct func_t *func; typedef struct func_t { func (*fn) (func, func); func _; int num; } func_t; func new(func(*f)(func, func), func _) { func x = malloc(sizeof(func_t)); x->fn = f; x->_ = _; x->num = 0; return x; } func call(func f, func n) { return f->fn(f, n); } func Y(func(*f)(func, func)) { func g = new(f, 0); g->_ = g; return g; } func num(int n) { func x = new(0, 0); x->num = n; return x; } func fac(func self, func n) { int nn = n->num; return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num) : num(1); } func fib(func self, func n) { int nn = n->num; return nn > 1 ? num( call(self->_, num(nn - 1))->num + call(self->_, num(nn - 2))->num ) : num(1); } void show(func n) { printf(" %d", n->num); } int main() { int i; func f = Y(fac); printf("fac: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); f = Y(fib); printf("fib: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
#include<stdio.h> typedef struct{ int integer; float decimal; char letter; char string[100]; double bigDecimal; }Composite; Composite example() { Composite C = {1, 2.3, 'a', "Hello World", 45.678}; return C; } int main() { Composite C = example(); printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
#include <stdlib.h> #include <stdio.h> int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } } printf("The first ten terms of the Van Eck sequence are:\n"); for (int i = 0; i < 10; i ++) printf("%d ", a[i]); printf("\n\nTerms 991 to 1000 of the sequence are:\n"); for (int i = 990; i < 1000; i ++) printf("%d ", a[i]); putchar('\n'); return 0; }
Keep all operations the same but rewrite the snippet in C.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
#include <stdlib.h> #include <stdio.h> int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } } printf("The first ten terms of the Van Eck sequence are:\n"); for (int i = 0; i < 10; i ++) printf("%d ", a[i]); printf("\n\nTerms 991 to 1000 of the sequence are:\n"); for (int i = 990; i < 1000; i ++) printf("%d ", a[i]); putchar('\n'); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "ftptest@example.com"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
#include <ftplib.h> int main(void) { netbuf *nbuf; FtpInit(); FtpConnect("kernel.org", &nbuf); FtpLogin("anonymous", "", nbuf); FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf); FtpChdir("pub/linux/kernel", nbuf); FtpDir((void*)0, ".", nbuf); FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf); FtpQuit(nbuf); return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
for(int i = 1;i <= 10; i++){ System.out.print(i); if(i % 5 == 0){ System.out.println(); continue; } System.out.print(", "); }
for(int i = 1;i <= 10; i++){ printf("%d", i); if(i % 5 == 0){ printf("\n"); continue; } printf(", "); }
Write a version of this Java function in C with identical behavior.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
#include<conio.h> #define COLOURS 8 int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); clrscr(); for(colour=0;colour<COLOURS;colour++) { getch(); gotoxy(1+colour*MAXCOL/COLOURS,1); textbackground(colour); for(j=0;j<MAXROW;j++){ for(i=0;i<MAXCOL/COLOURS;i++){ cprintf(" "); } gotoxy(1+colour*MAXCOL/COLOURS,1+j); } } getch(); textbackground(BLACK); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
#include<conio.h> #define COLOURS 8 int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); clrscr(); for(colour=0;colour<COLOURS;colour++) { getch(); gotoxy(1+colour*MAXCOL/COLOURS,1); textbackground(colour); for(j=0;j<MAXROW;j++){ for(i=0;i<MAXCOL/COLOURS;i++){ cprintf(" "); } gotoxy(1+colour*MAXCOL/COLOURS,1+j); } } getch(); textbackground(BLACK); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import static java.util.Arrays.stream; import java.util.Locale; import static java.util.stream.IntStream.range; public class Test { static double dotProduct(double[] a, double[] b) { return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum(); } static double[][] matrixMul(double[][] A, double[][] B) { double[][] result = new double[A.length][B[0].length]; double[] aux = new double[B.length]; for (int j = 0; j < B[0].length; j++) { for (int k = 0; k < B.length; k++) aux[k] = B[k][j]; for (int i = 0; i < A.length; i++) result[i][j] = dotProduct(A[i], aux); } return result; } static double[][] pivotize(double[][] m) { int n = m.length; double[][] id = range(0, n).mapToObj(j -> range(0, n) .mapToDouble(i -> i == j ? 1 : 0).toArray()) .toArray(double[][]::new); for (int i = 0; i < n; i++) { double maxm = m[i][i]; int row = i; for (int j = i; j < n; j++) if (m[j][i] > maxm) { maxm = m[j][i]; row = j; } if (i != row) { double[] tmp = id[i]; id[i] = id[row]; id[row] = tmp; } } return id; } static double[][][] lu(double[][] A) { int n = A.length; double[][] L = new double[n][n]; double[][] U = new double[n][n]; double[][] P = pivotize(A); double[][] A2 = matrixMul(P, A); for (int j = 0; j < n; j++) { L[j][j] = 1; for (int i = 0; i < j + 1; i++) { double s1 = 0; for (int k = 0; k < i; k++) s1 += U[k][j] * L[i][k]; U[i][j] = A2[i][j] - s1; } for (int i = j; i < n; i++) { double s2 = 0; for (int k = 0; k < j; k++) s2 += U[k][j] * L[i][k]; L[i][j] = (A2[i][j] - s2) / U[j][j]; } } return new double[][][]{L, U, P}; } static void print(double[][] m) { stream(m).forEach(a -> { stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n)); System.out.println(); }); System.out.println(); } public static void main(String[] args) { double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}}; double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1}, {2.0, 5, 7, 1}}; for (double[][] m : lu(a)) print(m); System.out.println(); for (double[][] m : lu(b)) print(m); } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #define foreach(a, b, c) for (int a = b; a < c; a++) #define for_i foreach(i, 0, n) #define for_j foreach(j, 0, n) #define for_k foreach(k, 0, n) #define for_ij for_i for_j #define for_ijk for_ij for_k #define _dim int n #define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; } #define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; } typedef double **mat; #define _zero(a) mat_zero(a, n) void mat_zero(mat x, int n) { for_ij x[i][j] = 0; } #define _new(a) a = mat_new(n) mat mat_new(_dim) { mat x = malloc(sizeof(double*) * n); x[0] = malloc(sizeof(double) * n * n); for_i x[i] = x[0] + n * i; _zero(x); return x; } #define _copy(a) mat_copy(a, n) mat mat_copy(void *s, _dim) { mat x = mat_new(n); for_ij x[i][j] = ((double (*)[n])s)[i][j]; return x; } #define _del(x) mat_del(x) void mat_del(mat x) { free(x[0]); free(x); } #define _QUOT(x) #x #define QUOTE(x) _QUOT(x) #define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n) void mat_show(mat x, char *fmt, _dim) { if (!fmt) fmt = "%8.4g"; for_i { printf(i ? " " : " [ "); for_j { printf(fmt, x[i][j]); printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n"); } } } #define _mul(a, b) mat_mul(a, b, n) mat mat_mul(mat a, mat b, _dim) { mat c = _new(c); for_ijk c[i][j] += a[i][k] * b[k][j]; return c; } #define _pivot(a, b) mat_pivot(a, b, n) void mat_pivot(mat a, mat p, _dim) { for_ij { p[i][j] = (i == j); } for_i { int max_j = i; foreach(j, i, n) if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j; if (max_j != i) for_k { _swap(p[i][k], p[max_j][k]); } } } #define _LU(a, l, u, p) mat_LU(a, l, u, p, n) void mat_LU(mat A, mat L, mat U, mat P, _dim) { _zero(L); _zero(U); _pivot(A, P); mat Aprime = _mul(P, A); for_i { L[i][i] = 1; } for_ij { double s; if (j <= i) { _sum_k(0, j, L[j][k] * U[k][i], s) U[j][i] = Aprime[j][i] - s; } if (j >= i) { _sum_k(0, i, L[j][k] * U[k][i], s); L[j][i] = (Aprime[j][i] - s) / U[i][i]; } } _del(Aprime); } double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }}; double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}; int main() { int n = 3; mat A, L, P, U; _new(L); _new(P); _new(U); A = _copy(A3); _LU(A, L, U, P); _show(A); _show(L); _show(U); _show(P); _del(A); _del(L); _del(U); _del(P); printf("\n"); n = 4; _new(L); _new(P); _new(U); A = _copy(A4); _LU(A, L, U, P); _show(A); _show(L); _show(U); _show(P); _del(A); _del(L); _del(U); _del(P); return 0; }
Translate the given Java code snippet into C without altering its behavior.
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
#include <stdio.h> #include <stdlib.h> struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf("%s", info[it].text); found_word = 1; } } if (0 == found_word) printf("%d", i); printf("\n"); } } int main(void) { struct replace_info info[3] = { {5, "Buzz"}, {7, "Baxx"}, {3, "Fizz"} }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
#include <stdio.h> #include <stdlib.h> struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf("%s", info[it].text); found_word = 1; } } if (0 == found_word) printf("%d", i); printf("\n"); } } int main(void) { struct replace_info info[3] = { {5, "Buzz"}, {7, "Baxx"}, {3, "Fizz"} }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
Generate an equivalent C version of this Java code.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Keep all operations the same but rewrite the snippet in C.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Port the provided Java code into C while preserving the original functionality.
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void play() { digits = getSolvableDigits(); Scanner in = new Scanner(System.in); while (true) { System.out.print("Make 24 using these digits: "); System.out.println(digits); System.out.println("(Enter 'q' to quit, 's' for a solution)"); System.out.print("> "); String line = in.nextLine(); if (line.equalsIgnoreCase("q")) { System.out.println("\nThanks for playing"); return; } if (line.equalsIgnoreCase("s")) { System.out.println(solution); digits = getSolvableDigits(); continue; } char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray(); try { validate(entry); if (evaluate(infixToPostfix(entry))) { System.out.println("\nCorrect! Want to try another? "); digits = getSolvableDigits(); } else { System.out.println("\nNot correct."); } } catch (Exception e) { System.out.printf("%n%s Try again.%n", e.getMessage()); } } } void validate(char[] input) throws Exception { int total1 = 0, parens = 0, opsCount = 0; for (char c : input) { if (Character.isDigit(c)) total1 += 1 << (c - '0') * 4; else if (c == '(') parens++; else if (c == ')') parens--; else if (ops.indexOf(c) != -1) opsCount++; if (parens < 0) throw new Exception("Parentheses mismatch."); } if (parens != 0) throw new Exception("Parentheses mismatch."); if (opsCount != 3) throw new Exception("Wrong number of operators."); int total2 = 0; for (int d : digits) total2 += 1 << d * 4; if (total1 != total2) throw new Exception("Not the same digits."); } boolean evaluate(char[] line) throws Exception { Stack<Float> s = new Stack<>(); try { for (char c : line) { if ('0' <= c && c <= '9') s.push((float) c - '0'); else s.push(applyOperator(s.pop(), s.pop(), c)); } } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return (Math.abs(24 - s.peek()) < 0.001F); } float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } List<Integer> randomDigits() { Random r = new Random(); List<Integer> result = new ArrayList<>(4); for (int i = 0; i < 4; i++) result.add(r.nextInt(9) + 1); return result; } List<Integer> getSolvableDigits() { List<Integer> result; do { result = randomDigits(); } while (!isSolvable(result)); return result; } boolean isSolvable(List<Integer> digits) { Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2); permute(digits, dPerms, 0); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>(total); permuteOperators(oPerms, 4, total); StringBuilder sb = new StringBuilder(4 + 3); for (String pattern : patterns) { char[] patternChars = pattern.toCharArray(); for (List<Integer> dig : dPerms) { for (List<Integer> opr : oPerms) { int i = 0, j = 0; for (char c : patternChars) { if (c == 'n') sb.append(dig.get(i++)); else sb.append(ops.charAt(opr.get(j++))); } String candidate = sb.toString(); try { if (evaluate(candidate.toCharArray())) { solution = postfixToInfix(candidate); return true; } } catch (Exception ignored) { } sb.setLength(0); } } } return false; } String postfixToInfix(String postfix) { class Expression { String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format("%s %s %s", e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } } Stack<Expression> expr = new Stack<>(); for (char c : postfix.toCharArray()) { int idx = ops.indexOf(c); if (idx != -1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec) l.ex = '(' + l.ex + ')'; if (r.prec <= opPrec) r.ex = '(' + r.ex + ')'; expr.push(new Expression(l.ex, r.ex, "" + c)); } else { expr.push(new Expression("" + c)); } } return expr.peek().ex; } char[] infixToPostfix(char[] infix) throws Exception { StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); try { for (char c : infix) { int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 >= prec1) sb.append(ops.charAt(s.pop())); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())); s.pop(); } else { sb.append(c); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())); } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return sb.toString().toCharArray(); } void permute(List<Integer> lst, Set<List<Integer>> res, int k) { for (int i = k; i < lst.size(); i++) { Collections.swap(lst, i, k); permute(lst, res, k + 1); Collections.swap(lst, k, i); } if (k == lst.size()) res.add(new ArrayList<>(lst)); } void permuteOperators(List<List<Integer>> res, int n, int total) { for (int i = 0, npow = n * n; i < total; i++) res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); } }
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void play() { digits = getSolvableDigits(); Scanner in = new Scanner(System.in); while (true) { System.out.print("Make 24 using these digits: "); System.out.println(digits); System.out.println("(Enter 'q' to quit, 's' for a solution)"); System.out.print("> "); String line = in.nextLine(); if (line.equalsIgnoreCase("q")) { System.out.println("\nThanks for playing"); return; } if (line.equalsIgnoreCase("s")) { System.out.println(solution); digits = getSolvableDigits(); continue; } char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray(); try { validate(entry); if (evaluate(infixToPostfix(entry))) { System.out.println("\nCorrect! Want to try another? "); digits = getSolvableDigits(); } else { System.out.println("\nNot correct."); } } catch (Exception e) { System.out.printf("%n%s Try again.%n", e.getMessage()); } } } void validate(char[] input) throws Exception { int total1 = 0, parens = 0, opsCount = 0; for (char c : input) { if (Character.isDigit(c)) total1 += 1 << (c - '0') * 4; else if (c == '(') parens++; else if (c == ')') parens--; else if (ops.indexOf(c) != -1) opsCount++; if (parens < 0) throw new Exception("Parentheses mismatch."); } if (parens != 0) throw new Exception("Parentheses mismatch."); if (opsCount != 3) throw new Exception("Wrong number of operators."); int total2 = 0; for (int d : digits) total2 += 1 << d * 4; if (total1 != total2) throw new Exception("Not the same digits."); } boolean evaluate(char[] line) throws Exception { Stack<Float> s = new Stack<>(); try { for (char c : line) { if ('0' <= c && c <= '9') s.push((float) c - '0'); else s.push(applyOperator(s.pop(), s.pop(), c)); } } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return (Math.abs(24 - s.peek()) < 0.001F); } float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } List<Integer> randomDigits() { Random r = new Random(); List<Integer> result = new ArrayList<>(4); for (int i = 0; i < 4; i++) result.add(r.nextInt(9) + 1); return result; } List<Integer> getSolvableDigits() { List<Integer> result; do { result = randomDigits(); } while (!isSolvable(result)); return result; } boolean isSolvable(List<Integer> digits) { Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2); permute(digits, dPerms, 0); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>(total); permuteOperators(oPerms, 4, total); StringBuilder sb = new StringBuilder(4 + 3); for (String pattern : patterns) { char[] patternChars = pattern.toCharArray(); for (List<Integer> dig : dPerms) { for (List<Integer> opr : oPerms) { int i = 0, j = 0; for (char c : patternChars) { if (c == 'n') sb.append(dig.get(i++)); else sb.append(ops.charAt(opr.get(j++))); } String candidate = sb.toString(); try { if (evaluate(candidate.toCharArray())) { solution = postfixToInfix(candidate); return true; } } catch (Exception ignored) { } sb.setLength(0); } } } return false; } String postfixToInfix(String postfix) { class Expression { String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format("%s %s %s", e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } } Stack<Expression> expr = new Stack<>(); for (char c : postfix.toCharArray()) { int idx = ops.indexOf(c); if (idx != -1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec) l.ex = '(' + l.ex + ')'; if (r.prec <= opPrec) r.ex = '(' + r.ex + ')'; expr.push(new Expression(l.ex, r.ex, "" + c)); } else { expr.push(new Expression("" + c)); } } return expr.peek().ex; } char[] infixToPostfix(char[] infix) throws Exception { StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); try { for (char c : infix) { int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 >= prec1) sb.append(ops.charAt(s.pop())); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())); s.pop(); } else { sb.append(c); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())); } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return sb.toString().toCharArray(); } void permute(List<Integer> lst, Set<List<Integer>> res, int k) { for (int i = k; i < lst.size(); i++) { Collections.swap(lst, i, k); permute(lst, res, k + 1); Collections.swap(lst, k, i); } if (k == lst.size()) res.add(new ArrayList<>(lst)); } void permuteOperators(List<List<Integer>> res, int n, int total) { for (int i = 0, npow = n * n; i < total; i++) res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); } }
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Port the provided Java code into C while preserving the original functionality.
import java.util.Scanner; import java.util.Random; public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks(in.nextInt()); } private static void runTasks(int nTasks){ for(int i = 0; i < nTasks; i++){ System.out.println("Starting task number " + (i+1) + "."); runThreads(); Worker.checkpoint(); } } private static void runThreads(){ for(int i = 0; i < Worker.nWorkers; i ++){ new Thread(new Worker(i+1)).start(); } } public static class Worker implements Runnable{ public Worker(int threadID){ this.threadID = threadID; } public void run(){ work(); } private synchronized void work(){ try { int workTime = rgen.nextInt(900) + 100; System.out.println("Worker " + threadID + " will work for " + workTime + " msec."); Thread.sleep(workTime); nFinished++; System.out.println("Worker " + threadID + " is ready"); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } public static synchronized void checkpoint(){ while(nFinished != nWorkers){ try { Thread.sleep(10); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } nFinished = 0; } private int threadID; private static Random rgen = new Random(); private static int nFinished = 0; public static int nWorkers = 0; } }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> int main() { int jobs = 41, tid; omp_set_num_threads(5); #pragma omp parallel shared(jobs) private(tid) { tid = omp_get_thread_num(); while (jobs > 0) { #pragma omp barrier if (!jobs) break; printf("%d: taking job %d\n", tid, jobs--); usleep(100000 + rand() / (double) RAND_MAX * 3000000); printf("%d: done job\n", tid); } printf("[%d] leaving\n", tid); #pragma omp barrier } return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curByte = (int)(n & 0x7F); if (i != (numBytes - 1)) curByte |= 0x80; output[i] = (byte)curByte; n >>>= 7; } return output; } public static long decode(byte[] b) { long n = 0; for (int i = 0; i < b.length; i++) { int curByte = b[i] & 0xFF; n = (n << 7) | (curByte & 0x7F); if ((curByte & 0x80) == 0) break; } return n; } public static String byteArrayToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { if (i > 0) sb.append(", "); String s = Integer.toHexString(b[i] & 0xFF); if (s.length() < 2) s = "0" + s; sb.append(s); } return sb.toString(); } public static void main(String[] args) { long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; for (long n : testNumbers) { byte[] encoded = encode(n); long decoded = decode(encoded); System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); } } }
#include <stdio.h> #include <stdint.h> void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; } uint64_t from_seq(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++ & 128); return r; } int main() { uint8_t s[10]; uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; int i, j; for (j = 0; j < sizeof(x)/8; j++) { to_seq(x[j], s); printf("seq from %llx: [ ", x[j]); i = 0; do { printf("%02x ", s[i]); } while ((s[i++] & 128)); printf("] back: %llx\n", from_seq(s)); } return 0; }
Keep all operations the same but rewrite the snippet in C.
import java.io.*; import java.security.*; import java.util.*; public class SHA256MerkleTree { public static void main(String[] args) { if (args.length != 1) { System.err.println("missing file argument"); System.exit(1); } try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) { byte[] digest = sha256MerkleTree(in, 1024); if (digest != null) System.out.println(digestToString(digest)); } catch (Exception e) { e.printStackTrace(); } } private static String digestToString(byte[] digest) { StringBuilder result = new StringBuilder(); for (int i = 0; i < digest.length; ++i) result.append(String.format("%02x", digest[i])); return result.toString(); } private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception { byte[] buffer = new byte[blockSize]; int bytes; MessageDigest md = MessageDigest.getInstance("SHA-256"); List<byte[]> digests = new ArrayList<>(); while ((bytes = in.read(buffer)) > 0) { md.reset(); md.update(buffer, 0, bytes); digests.add(md.digest()); } int length = digests.size(); if (length == 0) return null; while (length > 1) { int j = 0; for (int i = 0; i < length; i += 2, ++j) { byte[] digest1 = digests.get(i); if (i + 1 < length) { byte[] digest2 = digests.get(i + 1); md.reset(); md.update(digest1); md.update(digest2); digests.set(j, md.digest()); } else { digests.set(j, digest1); } } length = j; } return digests.get(0); } }
#include <glib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> guchar* sha256_merkle_tree(FILE* in, size_t block_size) { gchar* buffer = g_malloc(block_size); GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free); gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256); GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256); size_t bytes; while ((bytes = fread(buffer, 1, block_size, in)) > 0) { g_checksum_reset(checksum); g_checksum_update(checksum, (guchar*)buffer, bytes); gsize len = digest_length; guchar* digest = g_malloc(len); g_checksum_get_digest(checksum, digest, &len); g_ptr_array_add(hashes, digest); } g_free(buffer); guint hashes_length = hashes->len; if (hashes_length == 0) { g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return NULL; } while (hashes_length > 1) { guint j = 0; for (guint i = 0; i < hashes_length; i += 2, ++j) { guchar* digest1 = g_ptr_array_index(hashes, i); guchar* digest_out = g_ptr_array_index(hashes, j); if (i + 1 < hashes_length) { guchar* digest2 = g_ptr_array_index(hashes, i + 1); g_checksum_reset(checksum); g_checksum_update(checksum, digest1, digest_length); g_checksum_update(checksum, digest2, digest_length); gsize len = digest_length; g_checksum_get_digest(checksum, digest_out, &len); } else { memcpy(digest_out, digest1, digest_length); } } hashes_length = j; } guchar* result = g_ptr_array_steal_index(hashes, 0); g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return result; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s filename\n", argv[0]); return EXIT_FAILURE; } FILE* in = fopen(argv[1], "rb"); if (in) { guchar* digest = sha256_merkle_tree(in, 1024); fclose(in); if (digest) { gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256); for (gssize i = 0; i < length; ++i) printf("%02x", digest[i]); printf("\n"); g_free(digest); } } else { perror(argv[1]); return EXIT_FAILURE; } return EXIT_SUCCESS; }
Transform the following Java implementation into C, maintaining the same output and logic.
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("äàâáçñßæεбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
#include <ctype.h> #include <stdio.h> void str_toupper(char *s) { while(*s) { *s=toupper(*s); s++; } } void str_tolower(char *s) { while(*s) { *s=tolower(*s); s++; } } int main(int argc, char *argv[]) { char t[255]="alphaBETA"; str_toupper(t); printf("uppercase: %s\n", t); str_tolower(t); printf("lowercase: %s\n", t); return 0; }
Please provide an equivalent version of this Java code in C.
import javax.swing.*; public class GetInputSwing { public static void main(String[] args) throws Exception { int number = Integer.parseInt( JOptionPane.showInputDialog ("Enter an Integer")); String string = JOptionPane.showInputDialog ("Enter a String"); } }
#include <gtk/gtk.h> void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg; gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]); msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "You wrote '%s' and selected the number %d%s", c, (gint)v, (v==75000) ? "" : " which is wrong (75000 expected)!"); gtk_widget_show_all(GTK_WIDGET(msg)); (void)gtk_dialog_run(GTK_DIALOG(msg)); gtk_widget_destroy(GTK_WIDGET(msg)); if ( v==75000 ) gtk_main_quit(); } int main(int argc, char **argv) { GtkWindow *win; GtkEntry *entry; GtkSpinButton *spin; GtkButton *okbutton; GtkLabel *entry_l, *spin_l; GtkHBox *hbox[2]; GtkVBox *vbox; GtkWidget *widgs[2]; gtk_init(&argc, &argv); win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, "Insert values"); entry_l = (GtkLabel *)gtk_label_new("Insert a string"); spin_l = (GtkLabel *)gtk_label_new("Insert 75000"); entry = (GtkEntry *)gtk_entry_new(); spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1); widgs[0] = GTK_WIDGET(entry); widgs[1] = GTK_WIDGET(spin); okbutton = (GtkButton *)gtk_button_new_with_label("Ok"); hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1); vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin)); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
final PVector t = new PVector(20, 30, 60); void setup() { size(450, 400); noLoop(); background(0, 0, 200); stroke(-1); sc(7, 400, -60, t); } PVector sc(int o, float l, final int a, final PVector s) { if (o > 0) { sc(--o, l *= .5, -a, s).z += a; sc(o, l, a, s).z += a; sc(o, l, -a, s); } else line(s.x, s.y, s.x += cos(radians(s.z)) * l, s.y += sin(radians(s.z)) * l); return s; }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct cursor_tag { double x; double y; int angle; } cursor_t; void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; } void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, "L%g,%g\n", cursor->x, cursor->y); } void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } } void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, "<svg xmlns='http: size, size); fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n"); fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='"); fprintf(out, "M%g,%g\n", cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, "'/>\n</svg>\n"); } int main(int argc, char** argv) { const char* filename = "sierpinski_arrowhead.svg"; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, "w"); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
Translate this program into C but keep the logic exactly as in Java.
import java.io.File; import java.util.*; import static java.lang.System.out; public class TextProcessing1 { public static void main(String[] args) throws Exception { Locale.setDefault(new Locale("en", "US")); Metrics metrics = new Metrics(); int dataGap = 0; String gapBeginDate = null; try (Scanner lines = new Scanner(new File("readings.txt"))) { while (lines.hasNextLine()) { double lineTotal = 0.0; int linePairs = 0; int lineInvalid = 0; String lineDate; try (Scanner line = new Scanner(lines.nextLine())) { lineDate = line.next(); while (line.hasNext()) { final double value = line.nextDouble(); if (line.nextInt() <= 0) { if (dataGap == 0) gapBeginDate = lineDate; dataGap++; lineInvalid++; continue; } lineTotal += value; linePairs++; metrics.addDataGap(dataGap, gapBeginDate, lineDate); dataGap = 0; } } metrics.addLine(lineTotal, linePairs); metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal); } metrics.report(); } } private static class Metrics { private List<String[]> gapDates; private int maxDataGap = -1; private double total; private int pairs; private int lineResultCount; void addLine(double tot, double prs) { total += tot; pairs += prs; } void addDataGap(int gap, String begin, String end) { if (gap > 0 && gap >= maxDataGap) { if (gap > maxDataGap) { maxDataGap = gap; gapDates = new ArrayList<>(); } gapDates.add(new String[]{begin, end}); } } void lineResult(String date, int invalid, int prs, double tot) { if (lineResultCount >= 3) return; out.printf("%10s out: %2d in: %2d tot: %10.3f avg: %10.3f%n", date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0); lineResultCount++; } void report() { out.printf("%ntotal = %10.3f%n", total); out.printf("readings = %6d%n", pairs); out.printf("average = %010.3f%n", total / pairs); out.printf("%nmaximum run(s) of %d invalid measurements: %n", maxDataGap); for (String[] dates : gapDates) out.printf("begins at %s and ends at %s%n", dates[0], dates[1]); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> static int badHrs, maxBadHrs; static double hrsTot = 0.0; static int rdgsTot = 0; char bhEndDate[40]; int mungeLine( char *line, int lno, FILE *fout ) { char date[40], *tkn; int dHrs, flag, hrs2, hrs; double hrsSum; int hrsCnt = 0; double avg; tkn = strtok(line, "."); if (tkn) { int n = sscanf(tkn, "%s %d", &date, &hrs2); if (n<2) { printf("badly formated line - %d %s\n", lno, tkn); return 0; } hrsSum = 0.0; while( tkn= strtok(NULL, ".")) { n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs); if (n>=2) { if (flag > 0) { hrsSum += 1.0*hrs2 + .001*dHrs; hrsCnt += 1; if (maxBadHrs < badHrs) { maxBadHrs = badHrs; strcpy(bhEndDate, date); } badHrs = 0; } else { badHrs += 1; } hrs2 = hrs; } else { printf("bad file syntax line %d: %s\n",lno, tkn); } } avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0; fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n", date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt); hrsTot += hrsSum; rdgsTot += hrsCnt; } return 1; } int main() { FILE *infile, *outfile; int lineNo = 0; char line[512]; const char *ifilename = "readings.txt"; outfile = fopen("V0.txt", "w"); infile = fopen(ifilename, "rb"); if (!infile) { printf("Can't open %s\n", ifilename); exit(1); } while (NULL != fgets(line, 512, infile)) { lineNo += 1; if (0 == mungeLine(line, lineNo, outfile)) printf("Bad line at %d",lineNo); } fclose(infile); fprintf(outfile, "File: %s\n", ifilename); fprintf(outfile, "Total:  %.3f\n", hrsTot); fprintf(outfile, "Readings: %d\n", rdgsTot); fprintf(outfile, "Average:  %.3f\n", hrsTot/rdgsTot); fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs); fprintf(outfile, "Ends on date %s\n", bhEndDate); fclose(outfile); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digester { public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); } static String hexDigest(String str, String digestName) { try { MessageDigest md = MessageDigest.getInstance(digestName); byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8)); char[] hex = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4); hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f); } return new String(hex); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> const char *string = "The quick brown fox jumped over the lazy dog's back"; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", result[i]); printf("\n"); return EXIT_SUCCESS; }
Convert this Java block to C, preserving its control flow and logic.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import java.time.*; import java.time.format.*; class Main { public static void main(String args[]) { String dateStr = "March 7 2009 7:30pm EST"; DateTimeFormatter df = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("MMMM d yyyy h:mma zzz") .toFormatter(); ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12); System.out.println("Date: " + dateStr); System.out.println("+12h: " + after12Hours.format(df)); ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET")); System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df)); } }
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST"; strptime(d, "%B %d %Y %I:%M%p %Z", &ts); t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); return EXIT_SUCCESS; }
Please provide an equivalent version of this Java code in C.
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await(); Thread.sleep(num * 1000); System.out.println(num); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { int[] nums = new int[args.length]; for (int i = 0; i < args.length; i++) nums[i] = Integer.parseInt(args[i]); sleepSortAndPrint(nums); } }
>>>>>,----------[++++++++ ++[->+>+<<]>+>[-<<+>>]+++ +++++[-<------>]>>+>,---- ------<<+[->>>>>+<<<<<]>> ]>>>[<<<<[<<<[->>+<<[->+> [-]<<]]>[-<+>]>[-<<<.>>>> ->>>>>[>>>>>]<-<<<<[<<<<< ]+<]<<<<]>>>>>[>>>>>]<]
Please provide an equivalent version of this Java code in C.
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int a[10][10], i, j; srand(time(NULL)); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) a[i][j] = rand() % 20 + 1; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf(" %d", a[i][j]); if (a[i][j] == 20) goto Done; } printf("\n"); } Done: printf("\n"); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Please provide an equivalent version of this Java code in C.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Keep all operations the same but rewrite the snippet in C.
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
Generate an equivalent C version of this Java code.
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
#include <stdio.h> #include <stdlib.h> #define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ stk_##name stk_##name##_create(size_t init_size) { \ stk_##name s; if (!init_size) init_size = 4; \ s = malloc(sizeof(struct stk_##name##_t)); \ if (!s) return 0; \ s->buf = malloc(sizeof(type) * init_size); \ if (!s->buf) { free(s); return 0; } \ s->len = 0, s->alloc = init_size; \ return s; } \ int stk_##name##_push(stk_##name s, type item) { \ type *tmp; \ if (s->len >= s->alloc) { \ tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ if (!tmp) return -1; s->buf = tmp; \ s->alloc *= 2; } \ s->buf[s->len++] = item; \ return s->len; } \ type stk_##name##_pop(stk_##name s) { \ type tmp; \ if (!s->len) abort(); \ tmp = s->buf[--s->len]; \ if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ s->alloc /= 2; \ s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ return tmp; } \ void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) #define stk_size(s) ((s)->len) DECL_STACK_TYPE(int, int) int main(void) { int i; stk_int stk = stk_int_create(0); printf("pushing: "); for (i = 'a'; i <= 'z'; i++) { printf(" %c", i); stk_int_push(stk, i); } printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); printf("\npoppoing:"); while (stk_size(stk)) printf(" %c", stk_int_pop(stk)); printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); stk_int_delete(stk); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
public class TotientFunction { public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max)); } } private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; } private static final int max = 10000000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
Please provide an equivalent version of this Java code in C.
public class TotientFunction { public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max)); } } private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; } private static final int max = 10000000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
int a = 3; if (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } unless (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } switch (a) { case 2: puts ("a is 2"); break; case 3: puts ("a is 3"); break; case 4: puts ("a is 4"); break; default: puts("is neither"); }
Write a version of this Java function in C with identical behavior.
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Fractran{ public static void main(String []args){ new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); } final int limit = 15; Vector<Integer> num = new Vector<>(); Vector<Integer> den = new Vector<>(); public Fractran(String prog, Integer val){ compile(prog); dump(); exec(2); } void compile(String prog){ Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); Matcher matcher = regexp.matcher(prog); while(matcher.find()){ num.add(Integer.parseInt(matcher.group(1))); den.add(Integer.parseInt(matcher.group(2))); matcher = regexp.matcher(matcher.group(3)); } } void exec(Integer val){ int n = 0; while(val != null && n<limit){ System.out.println(n+": "+val); val = step(val); n++; } } Integer step(int val){ int i=0; while(i<den.size() && val%den.get(i) != 0) i++; if(i<den.size()) return num.get(i)*val/den.get(i); return null; } void dump(){ for(int i=0; i<den.size(); i++) System.out.print(num.get(i)+"/"+den.get(i)+" "); System.out.println(); } }
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); else gmp_printf(" %Zd", val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf("\nhalt: %Zd has no divisors\n", val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); return 0; }
Convert the following code from Java to C, ensuring the logic remains intact.
import java.util.Arrays; public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); } public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1); } public static void stoogeSort(int[] L, int i, int j) { if (L[j] < L[i]) { int tmp = L[i]; L[i] = L[j]; L[j] = tmp; } if (j - i > 1) { int t = (j - i + 1) / 3; stoogeSort(L, i, j - t); stoogeSort(L, i + t, j); stoogeSort(L, i, j - t); } } }
#include <stdio.h> #define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } int main(int argc, char *argv[]) { int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; int i, n; n = sizeof(nums)/sizeof(int); StoogeSort(nums, 0, n-1); for(i = 0; i <= n-1; i++) printf("%5d", nums[i]); return 0; }
Generate an equivalent C version of this Java code.
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; private final Random m_random = new Random(); public GaltonBox( final int pinRows, final int ballCount ) { m_pinRows = pinRows; m_startRow = pinRows + 1; m_balls = new Position[ ballCount ]; for ( int ball = 0; ball < ballCount; ball++ ) m_balls[ ball ] = new Position( m_startRow, 0, 'o' ); } private static class Position { int m_row; int m_col; char m_char; Position( final int row, final int col, final char ch ) { m_row = row; m_col = col; m_char = ch; } } public void run() { for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) { ballsInPlay = dropBalls(); print(); } } private int dropBalls() { int ballsInPlay = 0; int ballToStart = -1; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == m_startRow ) ballToStart = ball; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( ball == ballToStart ) { m_balls[ ball ].m_row = m_pinRows; ballsInPlay++; } else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) { m_balls[ ball ].m_row -= 1; m_balls[ ball ].m_col += m_random.nextInt( 2 ); if ( 0 != m_balls[ ball ].m_row ) ballsInPlay++; } return ballsInPlay; } private void print() { for ( int row = m_startRow; row --> 1; ) { for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == row ) printBall( m_balls[ ball ] ); System.out.println(); printPins( row ); } printCollectors(); System.out.println(); } private static void printBall( final Position pos ) { for ( int col = pos.m_row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = 0; col < pos.m_col; col++ ) System.out.print( " " ); System.out.print( pos.m_char ); } private void printPins( final int row ) { for ( int col = row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = m_startRow - row; col --> 0; ) System.out.print( ". " ); System.out.println(); } private void printCollectors() { final List<List<Position>> collectors = new ArrayList<List<Position>>(); for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = new ArrayList<Position>(); collectors.add( collector ); for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col ) collector.add( m_balls[ ball ] ); } for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) { for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = collectors.get( col ); final int pos = row + collector.size() - rows; System.out.print( '|' ); if ( pos >= 0 ) System.out.print( collector.get( pos ).m_char ); else System.out.print( ' ' ); } System.out.println( '|' ); } } private static final int longest( final List<List<Position>> collectors ) { int result = 0; for ( final List<Position> collector : collectors ) result = Math.max( collector.size(), result ); return result; } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b; #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts("\033[H"), i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++, putchar(' ')) printf(B(i, j) == '*' ? C(i - 1, j) ? "\033[32m%c\033[m" : "\033[31m%c\033[m" : "%c", B(i, j)); } void init() { int i, j; puts("\033[H\033[J"); b = malloc(w * h); memset(b, ' ', w * h); x = malloc(sizeof(int) * BALLS * 2); y = x + BALLS; for (i = 0; i < n; i++) for (j = -i; j <= i; j += 2) B(2 * i+2, j + w/2) = '*'; srand(time(0)); } void move(int idx) { int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0; if (yy < 0) return; if (yy == h - 1) { y[idx] = -1; return; } switch(c = B(yy + 1, xx)) { case ' ': yy++; break; case '*': sl = 1; default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1)) if (!rnd(sl++)) o = 1; if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1)) if (!rnd(sl++)) o = -1; if (!o) kill = 1; xx += o; } c = V(idx); V(idx) = ' '; idx[y] = yy, idx[x] = xx; B(yy, xx) = c; if (kill) idx[y] = -1; } int run(void) { static int step = 0; int i; for (i = 0; i < cnt; i++) move(i); if (2 == ++step && cnt < BALLS) { step = 0; x[cnt] = w/2; y[cnt] = 0; if (V(cnt) != ' ') return 0; V(cnt) = rnd(80) + 43; cnt++; } return 1; } int main(int c, char **v) { if (c < 2 || (n = atoi(v[1])) <= 3) n = 5; if (n >= 20) n = 20; w = n * 2 + 1; init(); do { show_board(), usleep(60000); } while (run()); return 0; }
Please provide an equivalent version of this Java code in C.
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toString(arr)); } while (circleSortR(arr, 0, arr.length - 1, 0) != 0); } private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps; int high = hi; int low = lo; int mid = (hi - lo) / 2; while (lo < hi) { if (arr[lo] > arr[hi]) { swap(arr, lo, hi); numSwaps++; } lo++; hi--; } if (lo == hi && arr[lo] > arr[hi + 1]) { swap(arr, lo, hi + 1); numSwaps++; } numSwaps = circleSortR(arr, low, low + mid, numSwaps); numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps); return numSwaps; } private static void swap(int[] arr, int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } }
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf("%d ", x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); } int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x)); return 0; }
Generate an equivalent C version of this Java code.
package kronecker; public class ProductFractals { public static int[][] product(final int[][] a, final int[][] b) { final int[][] c = new int[a.length*b.length][]; for (int ix = 0; ix < c.length; ix++) { final int num_cols = a[0].length*b[0].length; c[ix] = new int[num_cols]; } for (int ia = 0; ia < a.length; ia++) { for (int ja = 0; ja < a[ia].length; ja++) { for (int ib = 0; ib < b.length; ib++) { for (int jb = 0; jb < b[ib].length; jb++) { c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb]; } } } } return c; } public static void show_matrix(final int[][] m, final char nz, final char z) { for (int im = 0; im < m.length; im++) { for (int jm = 0; jm < m[im].length; jm++) { System.out.print(m[im][jm] == 0 ? z : nz); } System.out.println(); } } public static int[][] power(final int[][] m, final int n) { int[][] m_pow = m; for (int ix = 1; ix < n; ix++) { m_pow = product(m, m_pow); } return m_pow; } private static void test(final int[][] m, final int n) { System.out.println("Test matrix"); show_matrix(m, '*', ' '); final int[][] m_pow = power(m, n); System.out.println("Matrix power " + n); show_matrix(m_pow, '*', ' '); } private static void test1() { final int[][] m = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}; test(m, 4); } private static void test2() { final int[][] m = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; test(m, 4); } private static void test3() { final int[][] m = {{1, 0, 1}, {1, 0, 1}, {0, 1, 0}}; test(m, 4); } public static void main(final String[] args) { test1(); test2(); test3(); } }
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = fopen(inputFile,"r"); int i,j,k,l; unsigned long prod; int** matrix; cell *coreList,*tempList,*resultList; fscanf(fp,"%d%d",&ROW,&COL); matrix = (int**)malloc(ROW*sizeof(int*)); for(i=0;i<ROW;i++){ matrix[i] = (int*)malloc(COL*sizeof(int)); for(j=0;j<COL;j++){ fscanf(fp,"%d",&matrix[i][j]); if(matrix[i][j]==1) SUM++; } } coreList = (cell*)malloc(SUM*sizeof(cell)); resultList = (cell*)malloc(SUM*sizeof(cell)); k = 0; for(i=0;i<ROW;i++){ for(j=0;j<COL;j++){ if(matrix[i][j]==1){ coreList[k].row = i+1; coreList[k].col = j+1; resultList[k].row = i+1; resultList[k].col = j+1; k++; } } } prod = k; for(i=2;i<=power;i++){ tempList = (cell*)malloc(prod*k*sizeof(cell)); l = 0; for(j=0;j<prod;j++){ for(k=0;k<SUM;k++){ tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row; tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col; l++; } } free(resultList); prod *= k; resultList = (cell*)malloc(prod*sizeof(cell)); for(j=0;j<prod;j++){ resultList[j].row = tempList[j].row; resultList[j].col = tempList[j].col; } free(tempList); } return resultList; } int main(){ char fileName[100]; int power,i,length; cell* resultList; printf("Enter input file name : "); scanf("%s",fileName); printf("Enter power : "); scanf("%d",&power); resultList = kroneckerProduct(fileName,power); initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal"); length = raiseTo(SUM,power); for(i=0;i<length;i++){ putpixel(resultList[i].row,resultList[i].col,15); } getch(); closegraph(); return 0; }
Generate an equivalent C version of this Java code.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{ put( "needspeeling", false ); put( "seedsremoved", false ); }}; public static void main( final String[] args ) { System.out.println( parseFile( args[ 0 ] ) ); } public static Map<String, Object> parseFile( final String fileName ) { final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS ); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( fileName ) ); for ( String line; null != ( line = reader.readLine() ); ) { parseLine( line, result ); } } catch ( final IOException x ) { throw new RuntimeException( "Oops: " + x, x ); } finally { if ( null != reader ) try { reader.close(); } catch ( final IOException x2 ) { System.err.println( "Could not close " + fileName + " - " + x2 ); } } return result; } private static void parseLine( final String line, final Map<String, Object> map ) { if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) return; final Matcher matcher = LINE_PATTERN.matcher( line ); if ( ! matcher.matches() ) { System.err.println( "Bad config line: " + line ); return; } final String key = matcher.group( 1 ).trim().toLowerCase(); final String value = matcher.group( 2 ).trim(); if ( "".equals( value ) ) { map.put( key, true ); } else if ( -1 == value.indexOf( ',' ) ) { map.put( key, value ); } else { final String[] values = value.split( "," ); for ( int i = 0; i < values.length; i++ ) { values[ i ] = values[ i ].trim(); } map.put( key, Arrays.asList( values ) ); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si("FULLNAME", this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, "Sorry, something went wrong :-(\n"); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value("YES", 0); if (populate_configs(&confs)) { return 1; } printf( "Full name: %s\n" "Favorite fruit: %s\n" "Need spelling: %s\n" "Seeds removed: %s\n", confs.fullname, confs.favouritefruit, confs.needspeeling ? "True" : "False", confs.seedsremoved ? "True" : "False" ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); } #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.Comparator; import java.util.Arrays; public class Test { public static void main(String[] args) { String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; Arrays.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { int c = s2.length() - s1.length(); if (c == 0) c = s1.compareToIgnoreCase(s2); return c; } }); for (String s: strings) System.out.print(s + " "); } }
#include <stdlib.h> #include <string.h> #include <strings.h> int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
Write a version of this Java function in C with identical behavior.
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0) System.out.print(", "); System.out.print(p); ++count; } } System.out.println(); System.out.println("Next 4 circular primes:"); int repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; BigInteger bignum = BigInteger.valueOf(repunit); for (int count = 0; count < 4; ) { if (bignum.isProbablePrime(15)) { if (count > 0) System.out.print(", "); System.out.printf("R(%d)", digits); ++count; } ++digits; bignum = bignum.multiply(BigInteger.TEN); bignum = bignum.add(BigInteger.ONE); } System.out.println(); testRepunit(5003); testRepunit(9887); testRepunit(15073); testRepunit(25031); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static int cycle(int n) { int m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } private static boolean isCircularPrime(int p) { if (!isPrime(p)) return false; int p2 = cycle(p); while (p2 != p) { if (p2 < p || !isPrime(p2)) return false; p2 = cycle(p2); } return true; } private static void testRepunit(int digits) { BigInteger repunit = repunit(digits); if (repunit.isProbablePrime(15)) System.out.printf("R(%d) is probably prime.\n", digits); else System.out.printf("R(%d) is not prime.\n", digits); } private static BigInteger repunit(int digits) { char[] ch = new char[digits]; Arrays.fill(ch, '1'); return new BigInteger(new String(ch)); } }
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } uint32_t cycle(uint32_t n) { uint32_t m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } bool is_circular_prime(uint32_t p) { if (!is_prime(p)) return false; uint32_t p2 = cycle(p); while (p2 != p) { if (p2 < p || !is_prime(p2)) return false; p2 = cycle(p2); } return true; } void test_repunit(uint32_t digits) { char* str = malloc(digits + 1); if (str == 0) { fprintf(stderr, "Out of memory\n"); exit(1); } memset(str, '1', digits); str[digits] = 0; mpz_t bignum; mpz_init_set_str(bignum, str, 10); free(str); if (mpz_probab_prime_p(bignum, 10)) printf("R(%u) is probably prime.\n", digits); else printf("R(%u) is not prime.\n", digits); mpz_clear(bignum); } int main() { uint32_t p = 2; printf("First 19 circular primes:\n"); for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) printf(", "); printf("%u", p); ++count; } } printf("\n"); printf("Next 4 circular primes:\n"); uint32_t repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; mpz_t bignum; mpz_init_set_ui(bignum, repunit); for (int count = 0; count < 4; ) { if (mpz_probab_prime_p(bignum, 15)) { if (count > 0) printf(", "); printf("R(%u)", digits); ++count; } ++digits; mpz_mul_ui(bignum, bignum, 10); mpz_add_ui(bignum, bignum, 1); } mpz_clear(bignum); printf("\n"); test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
Translate the given Java code snippet into C without altering its behavior.
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; public class Rotate { private static class State { private final String text = "Hello World! "; private int startIndex = 0; private boolean rotateRight = true; } public static void main(String[] args) { State state = new State(); JLabel label = new JLabel(state.text); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { state.rotateRight = !state.rotateRight; } }); TimerTask task = new TimerTask() { public void run() { int delta = state.rotateRight ? 1 : -1; state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length(); label.setText(rotate(state.text, state.startIndex)); } }; Timer timer = new Timer(false); timer.schedule(task, 0, 500); JFrame rot = new JFrame(); rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); rot.add(label); rot.pack(); rot.setLocationRelativeTo(null); rot.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { timer.cancel(); } }); rot.setVisible(true); } private static String rotate(String text, int startIdx) { char[] rotated = new char[text.length()]; for (int i = 0; i < text.length(); i++) { rotated[i] = text.charAt((i + startIdx) % text.length()); } return String.valueOf(rotated); } }
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r = malloc(l+1); for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++) r[j] = t[i]; r[l] = 0; return r; } gboolean scroll_it(gpointer data) { if ( direction > 0 ) cx = (cx + 1) % slen; else cx = (cx + slen - 1 ) % slen; gchar *scrolled = rotateby(hello, cx, slen); gtk_label_set_text(label, scrolled); free(scrolled); return TRUE; } int main(int argc, char **argv) { GtkWidget *win; GtkButton *button; PangoFontDescription *pd; gtk_init(&argc, &argv); win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(win), "Basic Animation"); g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL); label = (GtkLabel *)gtk_label_new(hello); pd = pango_font_description_new(); pango_font_description_set_family(pd, "monospace"); gtk_widget_modify_font(GTK_WIDGET(label), pd); button = (GtkButton *)gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button)); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL); slen = strlen(hello); g_timeout_add(125, scroll_it, NULL); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Produce a functionally identical C code for the snippet given in Java.
public static int[] sort(int[] old) { for (int shift = Integer.SIZE - 1; shift > -1; shift--) { int[] tmp = new int[old.length]; int j = 0; for (int i = 0; i < old.length; i++) { boolean move = old[i] << shift >= 0; if (shift == 0 ? !move : move) { tmp[j] = old[i]; j++; } else { old[i - j] = old[i]; } } for (int i = j; i < tmp.length; i++) { tmp[i] = old[i - j]; } old = tmp; } return old; }
#include <stdio.h> #include <limits.h> #include <stdlib.h> #include <time.h> #define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) #define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); static void swap(unsigned *a, unsigned *b) { unsigned tmp = *a; *a = *b; *b = tmp; } static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) { if (!bit || to < from + 1) return; unsigned *ll = from, *rr = to - 1; for (;;) { while (ll < rr && !(*ll & bit)) ll++; while (ll < rr && (*rr & bit)) rr--; if (ll >= rr) break; swap(ll, rr); } if (!(bit & *ll) && ll < to) ll++; bit >>= 1; rad_sort_u(from, ll, bit); rad_sort_u(ll, to, bit); } static void radix_sort(int *a, const size_t len) { size_t i; unsigned *x = (unsigned*) a; for (i = 0; i < len; i++) x[i] ^= INT_MIN; rad_sort_u(x, x + len, INT_MIN); for (i = 0; i < len; i++) x[i] ^= INT_MIN; } int main(void) { srand(time(NULL)); int x[16]; for (size_t i = 0; i < ARR_LEN(x); i++) x[i] = RAND_RNG(-128,127) radix_sort(x, ARR_LEN(x)); for (size_t i = 0; i < ARR_LEN(x); i++) printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.util.Arrays; import java.util.List; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public interface PythagComp{ static void main(String... args){ System.out.println(run(20)); } static List<List<Integer>> run(int n){ return range(1, n).mapToObj( x -> range(x, n).mapToObj( y -> range(y, n).mapToObj( z -> new Integer[]{x, y, z} ) ) ) .flatMap(identity()) .flatMap(identity()) .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) .map(Arrays::asList) .collect(toList()) ; } }
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
Please provide an equivalent version of this Java code in C.
public static void sort(int[] nums){ for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ int smallest = Integer.MAX_VALUE; int smallestAt = currentPlace+1; for(int check = currentPlace; check<nums.length;check++){ if(nums[check]<smallest){ smallestAt = check; smallest = nums[check]; } } int temp = nums[currentPlace]; nums[currentPlace] = nums[smallestAt]; nums[smallestAt] = temp; } }
#include <stdio.h> void selection_sort (int *a, int n) { int i, j, m, t; for (i = 0; i < n; i++) { for (j = i, m = i; j < n; j++) { if (a[j] < a[m]) { m = j; } } t = a[i]; a[i] = a[m]; a[m] = t; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); selection_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Translate the given Java code snippet into C without altering its behavior.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Convert this Java block to C, preserving its control flow and logic.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
public class ArrayCallback7 { interface IntConsumer { void run(int x); } interface IntToInt { int run(int x); } static void forEach(int[] arr, IntConsumer consumer) { for (int i : arr) { consumer.run(i); } } static void update(int[] arr, IntToInt mapper) { for (int i = 0; i < arr.length; i++) { arr[i] = mapper.run(arr[i]); } } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); update(numbers, new IntToInt() { @Override public int run(int x) { return x * x; } }); forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); } }
#ifndef CALLBACK_H #define CALLBACK_H void map(int* array, int len, void(*callback)(int,int)); #endif
Translate this program into C but keep the logic exactly as in Java.
class Singleton { private static Singleton myInstance; public static Singleton getInstance() { if (myInstance == null) { synchronized(Singleton.class) { if (myInstance == null) { myInstance = new Singleton(); } } } return myInstance; } protected Singleton() { } }
#ifndef SILLY_H #define SILLY_H extern void JumpOverTheDog( int numberOfTimes); extern int PlayFetchWithDog( float weightOfStick); #endif
Maintain the same structure and functionality when rewriting this code in C.
public class SafeAddition { private static double stepDown(double d) { return Math.nextAfter(d, Double.NEGATIVE_INFINITY); } private static double stepUp(double d) { return Math.nextUp(d); } private static double[] safeAdd(double a, double b) { return new double[]{stepDown(a + b), stepUp(a + b)}; } public static void main(String[] args) { double a = 1.2; double b = 0.03; double[] result = safeAdd(a, b); System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]); } }
#include <fenv.h> #include <stdio.h> void safe_add(volatile double interval[2], volatile double a, volatile double b) { #pragma STDC FENV_ACCESS ON unsigned int orig; orig = fegetround(); fesetround(FE_DOWNWARD); interval[0] = a + b; fesetround(FE_UPWARD); interval[1] = a + b; fesetround(orig); } int main() { const double nums[][2] = { {1, 2}, {0.1, 0.2}, {1e100, 1e-100}, {1e308, 1e308}, }; double ival[2]; int i; for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) { safe_add(ival, nums[i][0], nums[i][1]); printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]); printf(" [%.17g, %.17g]\n", ival[0], ival[1]); printf(" size %.17g\n\n", ival[1] - ival[0]); } return 0; }
Translate the given Java code snippet into C without altering its behavior.
String dog = "Benjamin"; String Dog = "Samba"; String DOG = "Bernie"; @Inject Console console; console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
#include <stdio.h> static const char *dog = "Benjamin"; static const char *Dog = "Samba"; static const char *DOG = "Bernie"; int main() { printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
for (int i = 10; i >= 0; i--) { System.out.println(i); }
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
Keep all operations the same but rewrite the snippet in C.
import java.io.*; public class Test { public static void main(String[] args) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) { bw.write("abc"); } } }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.", freopen("sample.txt","wb",stdout)); }
Generate a C translation of this Java snippet without changing its computational steps.
for (Integer i = 0; i < 5; i++) { String line = ''; for (Integer j = 0; j < i; j++) { line += '*'; } System.debug(line); } List<String> lines = new List<String> { '*', '**', '***', '****', '*****' }; for (String line : lines) { System.debug(line); }
int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) putchar('*'); puts(""); }
Convert this Java block to C, preserving its control flow and logic.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
Change the following Java code into C without altering its purpose.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
Generate an equivalent C version of this Java code.
public class NonContinuousSubsequences { public static void main(String args[]) { seqR("1234", "", 0, 0); } private static void seqR(String s, String c, int i, int added) { if (i == s.length()) { if (c.trim().length() > added) System.out.println(c); } else { seqR(s, c + s.charAt(i), i + 1, added + 1); seqR(s, c + ' ', i + 1, added); } } }
#include <assert.h> #include <stdio.h> int main(int c, char **v) { unsigned int n = 1 << (c - 1), i = n, j, k; assert(n); while (i--) { if (!(i & (i + (i & -(int)i)))) continue; for (j = n, k = 1; j >>= 1; k++) if (i & j) printf("%s ", v[k]); putchar('\n'); } return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n) { if (n < 2) return n == 1 ? "1" : ""; StringBuilder f1 = new StringBuilder("1"); StringBuilder f2 = new StringBuilder("0"); for (n = n - 2; n > 0; n--) { String tmp = f2.toString(); f2.append(f1); f1.setLength(0); f1.append(tmp); } return f2.toString(); } void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) { for (int n = 0; n < wordFractal.length(); n++) { g.drawLine(x, y, x + dx, y + dy); x += dx; y += dy; if (wordFractal.charAt(n) == '0') { int tx = dx; dx = (n % 2 == 0) ? -dy : dy; dy = (n % 2 == 0) ? tx : -tx; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawWordFractal(g, 20, 20, 1, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Fibonacci Word Fractal"); f.setResizable(false); f.add(new FibonacciWordFractal(23), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include <stdio.h> int main(void) { puts( "%!PS-Adobe-3.0 EPSF\n" "%%BoundingBox: -10 -10 400 565\n" "/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n" "/b{a 90 rotate}def"); char i; for (i = 'c'; i <= 'z'; i++) printf("/%c{%c %c}def\n", i, i-1, i-2); puts("0 setlinewidth z showpage\n%%EOF"); return 0; }
Produce a functionally identical C code for the snippet given in Java.
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
#include <stdbool.h> #include <stdint.h> #include <stdio.h> bool isPrime(int64_t n) { int64_t i; if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; if (n % 7 == 0) return n == 7; if (n % 11 == 0) return n == 11; if (n % 13 == 0) return n == 13; if (n % 17 == 0) return n == 17; if (n % 19 == 0) return n == 19; for (i = 23; i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } int countTwinPrimes(int limit) { int count = 0; int64_t p3 = true, p2 = true, p1 = false; int64_t i; for (i = 5; i <= limit; i++) { p3 = p2; p2 = p1; p1 = isPrime(i); if (p3 && p1) { count++; } } return count; } void test(int limit) { int count = countTwinPrimes(limit); printf("Number of twin prime pairs less than %d is %d\n", limit, count); } int main() { test(10); test(100); test(1000); test(10000); test(100000); test(1000000); test(10000000); test(100000000); return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.Locale; public class Test { public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); } public static void unity(int n) { System.out.printf("%n%d: ", n); for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) { double real = Math.cos(angle); if (Math.abs(real) < 1.0E-3) real = 0.0; double imag = Math.sin(angle); if (Math.abs(imag) < 1.0E-3) imag = 0.0; System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
#include <stdio.h> #include <math.h> int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i; for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a), s = sin(a); if (c) printf("%.2g", c); printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s); printf(i == n - 1 ?"\n":", "); } return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
#include <stdio.h> #include <string.h> void longmulti(const char *a, const char *b, char *c) { int i = 0, j = 0, k = 0, n, carry; int la, lb; if (!strcmp(a, "0") || !strcmp(b, "0")) { c[0] = '0', c[1] = '\0'; return; } if (a[0] == '-') { i = 1; k = !k; } if (b[0] == '-') { j = 1; k = !k; } if (i || j) { if (k) c[0] = '-'; longmulti(a + i, b + j, c + k); return; } la = strlen(a); lb = strlen(b); memset(c, '0', la + lb); c[la + lb] = '\0'; # define I(a) (a - '0') for (i = la - 1; i >= 0; i--) { for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) { n = I(a[i]) * I(b[j]) + I(c[k]) + carry; carry = n / 10; c[k] = (n % 10) + '0'; } c[k] += carry; } # undef I if (c[0] == '0') memmove(c, c + 1, la + lb); return; } int main() { char c[1024]; longmulti("-18446744073709551616", "-18446744073709551616", c); printf("%s\n", c); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PellsEquation { public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } } private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } } private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b; while ( true ) { int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; } private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; } }
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { return makePair(1, 0); } else { int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } } return makePair(a, b); } } void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); } int main() { test(61); test(109); test(181); test(277); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); } public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdbool.h> #include <curses.h> #include <string.h> #define MAX_NUM_TRIES 72 #define LINE_BEGIN 7 #define LAST_LINE 18 int yp=LINE_BEGIN, xp=0; char number[5]; char guess[5]; #define MAX_STR 256 void mvaddstrf(int y, int x, const char *fmt, ...) { va_list args; char buf[MAX_STR]; va_start(args, fmt); vsprintf(buf, fmt, args); move(y, x); clrtoeol(); addstr(buf); va_end(args); } void ask_for_a_number() { int i=0; char symbols[] = "123456789"; move(5,0); clrtoeol(); addstr("Enter four digits: "); while(i<4) { int c = getch(); if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) { addch(c); symbols[c-'1'] = 0; guess[i++] = c; } } } void choose_the_number() { int i=0, j; char symbols[] = "123456789"; while(i<4) { j = rand() % 9; if ( symbols[j] != 0 ) { number[i++] = symbols[j]; symbols[j] = 0; } } }
Rewrite the snippet below in C so it works the same as the original Java code.
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
#include <stdio.h> void bubble_sort (int *a, int n) { int i, t, j = n, s = 1; while (s) { s = 0; for (i = 1; i < j; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } j--; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); bubble_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }