Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this Java block to C, preserving its control flow and logic.
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { System.out.printf("%d ", s); count++; } } System.out.printf("%n%n"); for (int i = 2 ; i <=5 ; i++ ) { long n = (long) Math.pow(10, i); System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n)); } } private static final long getSmarandachePrime(long n) { if ( n < 10 ) { switch ((int) n) { case 1: return 2; case 2: return 3; case 3: return 5; case 4: return 7; } } long s = getNextSmarandache(7); long result = 0; for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { count++; result = s; } } return result; } private static final boolean isPrime(long test) { if ( test % 2 == 0 ) return false; for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static long getNextSmarandache(long n) { if ( n % 10 == 3 ) { return n+4; } long retVal = n-4; int k = 0; while ( n % 10 == 7 ) { k++; n /= 10; } long digit = n % 10; long coeff = (digit == 2 ? 1 : 2); retVal += coeff * Math.pow(10, k); while ( k > 1 ) { retVal -= 5 * Math.pow(10, k-1); k--; } return retVal; } }
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> typedef uint32_t integer; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; } } bool is_prime(integer n) { 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; static const integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (int i = 0; i < 8; ++i) { if (p * p > n) return true; if (n % p == 0) return false; p += wheel[i]; } } } int main() { setlocale(LC_ALL, ""); const integer limit = 1000000000; integer n = 0, max = 0; printf("First 25 SPDS primes:\n"); for (int i = 0; n < limit; ) { n = next_prime_digit_number(n); if (!is_prime(n)) continue; if (i < 25) { if (i > 0) printf(" "); printf("%'u", n); } else if (i == 25) printf("\n"); ++i; if (i == 100) printf("Hundredth SPDS prime: %'u\n", n); else if (i == 1000) printf("Thousandth SPDS prime: %'u\n", n); else if (i == 10000) printf("Ten thousandth SPDS prime: %'u\n", n); max = n; } printf("Largest SPDS prime less than %'u: %'u\n", limit, max); return 0; }
Translate the given Java code snippet into C without altering its behavior.
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { System.out.printf("%d ", s); count++; } } System.out.printf("%n%n"); for (int i = 2 ; i <=5 ; i++ ) { long n = (long) Math.pow(10, i); System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n)); } } private static final long getSmarandachePrime(long n) { if ( n < 10 ) { switch ((int) n) { case 1: return 2; case 2: return 3; case 3: return 5; case 4: return 7; } } long s = getNextSmarandache(7); long result = 0; for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { count++; result = s; } } return result; } private static final boolean isPrime(long test) { if ( test % 2 == 0 ) return false; for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static long getNextSmarandache(long n) { if ( n % 10 == 3 ) { return n+4; } long retVal = n-4; int k = 0; while ( n % 10 == 7 ) { k++; n /= 10; } long digit = n % 10; long coeff = (digit == 2 ? 1 : 2); retVal += coeff * Math.pow(10, k); while ( k > 1 ) { retVal -= 5 * Math.pow(10, k-1); k--; } return retVal; } }
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> typedef uint32_t integer; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; } } bool is_prime(integer n) { 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; static const integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (int i = 0; i < 8; ++i) { if (p * p > n) return true; if (n % p == 0) return false; p += wheel[i]; } } } int main() { setlocale(LC_ALL, ""); const integer limit = 1000000000; integer n = 0, max = 0; printf("First 25 SPDS primes:\n"); for (int i = 0; n < limit; ) { n = next_prime_digit_number(n); if (!is_prime(n)) continue; if (i < 25) { if (i > 0) printf(" "); printf("%'u", n); } else if (i == 25) printf("\n"); ++i; if (i == 100) printf("Hundredth SPDS prime: %'u\n", n); else if (i == 1000) printf("Thousandth SPDS prime: %'u\n", n); else if (i == 10000) printf("Ten thousandth SPDS prime: %'u\n", n); max = n; } printf("Largest SPDS prime less than %'u: %'u\n", limit, max); return 0; }
Please provide an equivalent version of this Java code in C.
import java.util.Random; public class QuickSelect { private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) { E pivotVal = arr[pivot]; swap(arr, pivot, right); int storeIndex = left; for (int i = left; i < right; i++) { if (arr[i].compareTo(pivotVal) < 0) { swap(arr, i, storeIndex); storeIndex++; } } swap(arr, right, storeIndex); return storeIndex; } private static <E extends Comparable<? super E>> E select(E[] arr, int n) { int left = 0; int right = arr.length - 1; Random rand = new Random(); while (right >= left) { int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left); if (pivotIndex == n) { return arr[pivotIndex]; } else if (pivotIndex < n) { left = pivotIndex + 1; } else { right = pivotIndex - 1; } } return null; } private static void swap(Object[] arr, int i1, int i2) { if (i1 != i2) { Object temp = arr[i1]; arr[i1] = arr[i2]; arr[i2] = temp; } } public static void main(String[] args) { for (int i = 0; i < 10; i++) { Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; System.out.print(select(input, i)); if (i < 9) System.out.print(", "); } System.out.println(); } }
#include <stdio.h> #include <string.h> int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v, st, k) : qselect(v + st, len - st, k - st); } int main(void) { # define N (sizeof(x)/sizeof(x[0])) int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; int y[N]; int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); printf("%d: %d\n", i, qselect(y, 10, i)); } return 0; }
Maintain the same structure and functionality when rewriting this code in C.
public static long backToTen(String num, int oldBase){ return Long.parseLong(num, oldBase); } public static String tenToBase(long num, int newBase){ return Long.toString(num, newBase); }
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> char *to_base(int64_t num, int base) { char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[66] = {'\0'}; char *out; uint64_t n; int i, len = 0, neg = 0; if (base > 36) { fprintf(stderr, "base %d too large\n", base); return 0; } n = ((neg = num < 0)) ? (~num) + 1 : num; do { buf[len++] = tbl[n % base]; } while(n /= base); out = malloc(len + neg + 1); for (i = neg; len > 0; i++) out[i] = buf[--len]; if (neg) out[0] = '-'; return out; } long from_base(const char *num_str, int base) { char *endptr; int result = strtol(num_str, &endptr, base); return result; } int main() { int64_t x; x = ~(1LL << 63) + 1; printf("%lld in base 2: %s\n", x, to_base(x, 2)); x = 383; printf("%lld in base 16: %s\n", x, to_base(x, 16)); return 0; }
Produce a functionally identical C code for the snippet given in Java.
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
Write the same code in C as shown below in Java.
import java.util.*; import java.util.stream.*; public class StateNamePuzzle { static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory",}; public static void main(String[] args) { solve(Arrays.asList(states)); } static void solve(List<String> input) { Map<String, String> orig = input.stream().collect(Collectors.toMap( s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s)); input = new ArrayList<>(orig.keySet()); Map<String, List<String[]>> map = new HashMap<>(); for (int i = 0; i < input.size() - 1; i++) { String pair0 = input.get(i); for (int j = i + 1; j < input.size(); j++) { String[] pair = {pair0, input.get(j)}; String s = pair0 + pair[1]; String key = Arrays.toString(s.chars().sorted().toArray()); List<String[]> val = map.getOrDefault(key, new ArrayList<>()); val.add(pair); map.put(key, val); } } map.forEach((key, list) -> { for (int i = 0; i < list.size() - 1; i++) { String[] a = list.get(i); for (int j = i + 1; j < list.size(); j++) { String[] b = list.get(j); if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4) continue; System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]), orig.get(a[1]), orig.get(b[0]), orig.get(b[1])); } } }); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define USE_FAKES 1 const char *states[] = { #if USE_FAKES "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" }; int n_states = sizeof(states)/sizeof(*states); typedef struct { unsigned char c[26]; const char *name[2]; } letters; void count_letters(letters *l, const char *s) { int c; if (!l->name[0]) l->name[0] = s; else l->name[1] = s; while ((c = *s++)) { if (c >= 'a' && c <= 'z') l->c[c - 'a']++; if (c >= 'A' && c <= 'Z') l->c[c - 'A']++; } } int lcmp(const void *aa, const void *bb) { int i; const letters *a = aa, *b = bb; for (i = 0; i < 26; i++) if (a->c[i] > b->c[i]) return 1; else if (a->c[i] < b->c[i]) return -1; return 0; } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } void no_dup() { int i, j; qsort(states, n_states, sizeof(const char*), scmp); for (i = j = 0; i < n_states;) { while (++i < n_states && !strcmp(states[i], states[j])); if (i < n_states) states[++j] = states[i]; } n_states = j + 1; } void find_mix() { int i, j, n; letters *l, *p; no_dup(); n = n_states * (n_states - 1) / 2; p = l = calloc(n, sizeof(letters)); for (i = 0; i < n_states; i++) for (j = i + 1; j < n_states; j++, p++) { count_letters(p, states[i]); count_letters(p, states[j]); } qsort(l, n, sizeof(letters), lcmp); for (j = 0; j < n; j++) { for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) { if (l[j].name[0] == l[i].name[0] || l[j].name[1] == l[i].name[0] || l[j].name[1] == l[i].name[1]) continue; printf("%s + %s => %s + %s\n", l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]); } } free(l); } int main(void) { find_mix(); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import java.util.zip.* ; public class CRCMaker { public static void main( String[ ] args ) { String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ; CRC32 myCRC = new CRC32( ) ; myCRC.update( toBeEncoded.getBytes( ) ) ; System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ; } }
#include <stdio.h> #include <string.h> #include <zlib.h> int main() { const char *s = "The quick brown fox jumps over the lazy dog"; printf("%lX\n", crc32(0, (const void*)s, strlen(s))); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
grammar csv2html; dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ; header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");}; body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");}; row : field ',' field '\r'? '\n'; field : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");}; Field : ~[,\n\r]+;
#include <stdio.h> const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
grammar csv2html; dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ; header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");}; body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");}; row : field ',' field '\r'? '\n'; field : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");}; Field : ~[,\n\r]+;
#include <stdio.h> const char *input = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; " "he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
Change the following Java code into C without altering its purpose.
public class MyClass{ private int variable; public MyClass(){ } public void someMethod(){ this.variable = 1; } }
#include <stdlib.h> typedef struct sMyClass { int variable; } *MyClass; MyClass MyClass_new() { MyClass pthis = malloc(sizeof *pthis); pthis->variable = 0; return pthis; } void MyClass_delete(MyClass* pthis) { if (pthis) { free(*pthis); *pthis = NULL; } } void MyClass_someMethod(MyClass pthis) { pthis->variable = 1; } MyClass obj = MyClass_new(); MyClass_someMethod(obj); MyClass_delete(&obj);
Write the same code in C as shown below in Java.
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; ans[1] = str.substring(idx); return ans; } public static void main(String[] args){ int count = 0; int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10; for(long i = 1; i <= 1000000; i++){ String sqrStr = Long.toString(i * i, base); for(int j = 0; j < sqrStr.length() / 2 + 1; j++){ String[] parts = splitAt(sqrStr, j); long firstNum = Long.parseLong(parts[0], base); long secNum = Long.parseLong(parts[1], base); if(secNum == 0) break; if(firstNum + secNum == i){ System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]); count++; break; } } } System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base); } }
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
Produce a functionally identical C code for the snippet given in Java.
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; ans[1] = str.substring(idx); return ans; } public static void main(String[] args){ int count = 0; int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10; for(long i = 1; i <= 1000000; i++){ String sqrStr = Long.toString(i * i, base); for(int j = 0; j < sqrStr.length() / 2 + 1; j++){ String[] parts = splitAt(sqrStr, j); long firstNum = Long.parseLong(parts[0], base); long secNum = Long.parseLong(parts[1], base); if(secNum == 0) break; if(firstNum + secNum == i){ System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]); count++; break; } } } System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base); } }
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
Write the same algorithm in C as shown in this Java implementation.
import java.util.*; public class LZW { public static List<Integer> compress(String uncompressed) { int dictSize = 256; Map<String,Integer> dictionary = new HashMap<String,Integer>(); for (int i = 0; i < 256; i++) dictionary.put("" + (char)i, i); String w = ""; List<Integer> result = new ArrayList<Integer>(); for (char c : uncompressed.toCharArray()) { String wc = w + c; if (dictionary.containsKey(wc)) w = wc; else { result.add(dictionary.get(w)); dictionary.put(wc, dictSize++); w = "" + c; } } if (!w.equals("")) result.add(dictionary.get(w)); return result; } public static String decompress(List<Integer> compressed) { int dictSize = 256; Map<Integer,String> dictionary = new HashMap<Integer,String>(); for (int i = 0; i < 256; i++) dictionary.put(i, "" + (char)i); String w = "" + (char)(int)compressed.remove(0); StringBuffer result = new StringBuffer(w); for (int k : compressed) { String entry; if (dictionary.containsKey(k)) entry = dictionary.get(k); else if (k == dictSize) entry = w + w.charAt(0); else throw new IllegalArgumentException("Bad compressed k: " + k); result.append(entry); dictionary.put(dictSize++, w + entry.charAt(0)); w = entry; } return result.toString(); } public static void main(String[] args) { List<Integer> compressed = compress("TOBEORNOTTOBEORTOBEORNOT"); System.out.println(compressed); String decompressed = decompress(compressed); System.out.println(decompressed); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> void* mem_alloc(size_t item_size, size_t n_item) { size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size); x[0] = item_size; x[1] = n_item; return x + 2; } void* mem_extend(void *m, size_t new_n) { size_t *x = (size_t*)m - 2; x = realloc(x, sizeof(size_t) * 2 + *x * new_n); if (new_n > x[1]) memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1])); x[1] = new_n; return x + 2; } inline void _clear(void *m) { size_t *x = (size_t*)m - 2; memset(m, 0, x[0] * x[1]); } #define _new(type, n) mem_alloc(sizeof(type), n) #define _del(m) { free((size_t*)(m) - 2); m = 0; } #define _len(m) *((size_t*)m - 1) #define _setsize(m, n) m = mem_extend(m, n) #define _extend(m) m = mem_extend(m, _len(m) * 2) typedef uint8_t byte; typedef uint16_t ushort; #define M_CLR 256 #define M_EOD 257 #define M_NEW 258 typedef struct { ushort next[256]; } lzw_enc_t; typedef struct { ushort prev, back; byte c; } lzw_dec_t; byte* lzw_encode(byte *in, int max_bits) { int len = _len(in), bits = 9, next_shift = 512; ushort code, c, nc, next_code = M_NEW; lzw_enc_t *d = _new(lzw_enc_t, 512); if (max_bits > 15) max_bits = 15; if (max_bits < 9 ) max_bits = 12; byte *out = _new(ushort, 4); int out_len = 0, o_bits = 0; uint32_t tmp = 0; inline void write_bits(ushort x) { tmp = (tmp << bits) | x; o_bits += bits; if (_len(out) <= out_len) _extend(out); while (o_bits >= 8) { o_bits -= 8; out[out_len++] = tmp >> o_bits; tmp &= (1 << o_bits) - 1; } } for (code = *(in++); --len; ) { c = *(in++); if ((nc = d[code].next[c])) code = nc; else { write_bits(code); nc = d[code].next[c] = next_code++; code = c; } if (next_code == next_shift) { if (++bits > max_bits) { write_bits(M_CLR); bits = 9; next_shift = 512; next_code = M_NEW; _clear(d); } else _setsize(d, next_shift *= 2); } } write_bits(code); write_bits(M_EOD); if (tmp) write_bits(tmp); _del(d); _setsize(out, out_len); return out; } byte* lzw_decode(byte *in) { byte *out = _new(byte, 4); int out_len = 0; inline void write_out(byte c) { while (out_len >= _len(out)) _extend(out); out[out_len++] = c; } lzw_dec_t *d = _new(lzw_dec_t, 512); int len, j, next_shift = 512, bits = 9, n_bits = 0; ushort code, c, t, next_code = M_NEW; uint32_t tmp = 0; inline void get_code() { while(n_bits < bits) { if (len > 0) { len --; tmp = (tmp << 8) | *(in++); n_bits += 8; } else { tmp = tmp << (bits - n_bits); n_bits = bits; } } n_bits -= bits; code = tmp >> n_bits; tmp &= (1 << n_bits) - 1; } inline void clear_table() { _clear(d); for (j = 0; j < 256; j++) d[j].c = j; next_code = M_NEW; next_shift = 512; bits = 9; }; clear_table(); for (len = _len(in); len;) { get_code(); if (code == M_EOD) break; if (code == M_CLR) { clear_table(); continue; } if (code >= next_code) { fprintf(stderr, "Bad sequence\n"); _del(out); goto bail; } d[next_code].prev = c = code; while (c > 255) { t = d[c].prev; d[t].back = c; c = t; } d[next_code - 1].c = c; while (d[c].back) { write_out(d[c].c); t = d[c].back; d[c].back = 0; c = t; } write_out(d[c].c); if (++next_code >= next_shift) { if (++bits > 16) { fprintf(stderr, "Too many bits\n"); _del(out); goto bail; } _setsize(d, next_shift *= 2); } } if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr); _setsize(out, out_len); bail: _del(d); return out; } int main() { int i, fd = open("unixdict.txt", O_RDONLY); if (fd == -1) { fprintf(stderr, "Can't read file\n"); return 1; }; struct stat st; fstat(fd, &st); byte *in = _new(char, st.st_size); read(fd, in, st.st_size); _setsize(in, st.st_size); close(fd); printf("input size: %d\n", _len(in)); byte *enc = lzw_encode(in, 9); printf("encoded size: %d\n", _len(enc)); byte *dec = lzw_decode(enc); printf("decoded size: %d\n", _len(dec)); for (i = 0; i < _len(dec); i++) if (dec[i] != in[i]) { printf("bad decode at %d\n", i); break; } if (i == _len(dec)) printf("Decoded ok\n"); _del(in); _del(enc); _del(dec); return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.*; class Hofstadter { private static List<Integer> getSequence(int rlistSize, int slistSize) { List<Integer> rlist = new ArrayList<Integer>(); List<Integer> slist = new ArrayList<Integer>(); Collections.addAll(rlist, 1, 3, 7); Collections.addAll(slist, 2, 4, 5, 6); List<Integer> list = (rlistSize > 0) ? rlist : slist; int targetSize = (rlistSize > 0) ? rlistSize : slistSize; while (list.size() > targetSize) list.remove(list.size() - 1); while (list.size() < targetSize) { int lastIndex = rlist.size() - 1; int lastr = rlist.get(lastIndex).intValue(); int r = lastr + slist.get(lastIndex).intValue(); rlist.add(Integer.valueOf(r)); for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++) slist.add(Integer.valueOf(s)); } return list; } public static int ffr(int n) { return getSequence(n, 0).get(n - 1).intValue(); } public static int ffs(int n) { return getSequence(0, n).get(n - 1).intValue(); } public static void main(String[] args) { System.out.print("R():"); for (int n = 1; n <= 10; n++) System.out.print(" " + ffr(n)); System.out.println(); Set<Integer> first40R = new HashSet<Integer>(); for (int n = 1; n <= 40; n++) first40R.add(Integer.valueOf(ffr(n))); Set<Integer> first960S = new HashSet<Integer>(); for (int n = 1; n <= 960; n++) first960S.add(Integer.valueOf(ffs(n))); for (int i = 1; i <= 1000; i++) { Integer n = Integer.valueOf(i); if (first40R.contains(n) == first960S.contains(n)) System.out.println("Integer " + i + " either in both or neither set"); } System.out.println("Done"); } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.util.*; class Hofstadter { private static List<Integer> getSequence(int rlistSize, int slistSize) { List<Integer> rlist = new ArrayList<Integer>(); List<Integer> slist = new ArrayList<Integer>(); Collections.addAll(rlist, 1, 3, 7); Collections.addAll(slist, 2, 4, 5, 6); List<Integer> list = (rlistSize > 0) ? rlist : slist; int targetSize = (rlistSize > 0) ? rlistSize : slistSize; while (list.size() > targetSize) list.remove(list.size() - 1); while (list.size() < targetSize) { int lastIndex = rlist.size() - 1; int lastr = rlist.get(lastIndex).intValue(); int r = lastr + slist.get(lastIndex).intValue(); rlist.add(Integer.valueOf(r)); for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++) slist.add(Integer.valueOf(s)); } return list; } public static int ffr(int n) { return getSequence(n, 0).get(n - 1).intValue(); } public static int ffs(int n) { return getSequence(0, n).get(n - 1).intValue(); } public static void main(String[] args) { System.out.print("R():"); for (int n = 1; n <= 10; n++) System.out.print(" " + ffr(n)); System.out.println(); Set<Integer> first40R = new HashSet<Integer>(); for (int n = 1; n <= 40; n++) first40R.add(Integer.valueOf(ffr(n))); Set<Integer> first960S = new HashSet<Integer>(); for (int n = 1; n <= 960; n++) first960S.add(Integer.valueOf(ffs(n))); for (int i = 1; i <= 1000; i++) { Integer n = Integer.valueOf(i); if (first40R.contains(n) == first960S.contains(n)) System.out.println("Integer " + i + " either in both or neither set"); } System.out.println("Done"); } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Translate the given Java code snippet into C without altering its behavior.
public class MagicSquare { public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int base) { if (base % 2 == 0 || base < 3) throw new IllegalArgumentException("base must be odd and > 2"); int[][] grid = new int[base][base]; int r = 0, number = 0; int size = base * base; int c = base / 2; while (number++ < size) { grid[r][c] = number; if (r == 0) { if (c == base - 1) { r++; } else { r = base - 1; c++; } } else { if (c == base - 1) { r--; c = 0; } else { if (grid[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } } } return grid; } }
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
Please provide an equivalent version of this Java code in C.
public class MagicSquare { public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int base) { if (base % 2 == 0 || base < 3) throw new IllegalArgumentException("base must be odd and > 2"); int[][] grid = new int[base][base]; int r = 0, number = 0; int size = base * base; int c = base / 2; while (number++ < size) { grid[r][c] = number; if (r == 0) { if (c == base - 1) { r++; } else { r = base - 1; c++; } } else { if (c == base - 1) { r--; c = 0; } else { if (grid[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } } } return grid; } }
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
Generate an equivalent C version of this Java code.
import java.util.ArrayList; import java.util.List; public class YellowstoneSequence { public static void main(String[] args) { System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30)); } private static List<Integer> yellowstoneSequence(int sequenceCount) { List<Integer> yellowstoneList = new ArrayList<Integer>(); yellowstoneList.add(1); yellowstoneList.add(2); yellowstoneList.add(3); int num = 4; List<Integer> notYellowstoneList = new ArrayList<Integer>(); int yellowSize = 3; while ( yellowSize < sequenceCount ) { int found = -1; for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) { int test = notYellowstoneList.get(index); if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) { found = index; break; } } if ( found >= 0 ) { yellowstoneList.add(notYellowstoneList.remove(found)); yellowSize++; } else { while ( true ) { if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) { yellowstoneList.add(num); yellowSize++; num++; break; } notYellowstoneList.add(num); num++; } } } return yellowstoneList; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.ArrayList; import java.util.List; public class YellowstoneSequence { public static void main(String[] args) { System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30)); } private static List<Integer> yellowstoneSequence(int sequenceCount) { List<Integer> yellowstoneList = new ArrayList<Integer>(); yellowstoneList.add(1); yellowstoneList.add(2); yellowstoneList.add(3); int num = 4; List<Integer> notYellowstoneList = new ArrayList<Integer>(); int yellowSize = 3; while ( yellowSize < sequenceCount ) { int found = -1; for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) { int test = notYellowstoneList.get(index); if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) { found = index; break; } } if ( found >= 0 ) { yellowstoneList.add(notYellowstoneList.remove(found)); yellowSize++; } else { while ( true ) { if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) { yellowstoneList.add(num); yellowSize++; num++; break; } notYellowstoneList.add(num); num++; } } } return yellowstoneList; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Port the provided Java code into C while preserving the original functionality.
import java.util.ArrayList; import java.util.List; public class YellowstoneSequence { public static void main(String[] args) { System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30)); } private static List<Integer> yellowstoneSequence(int sequenceCount) { List<Integer> yellowstoneList = new ArrayList<Integer>(); yellowstoneList.add(1); yellowstoneList.add(2); yellowstoneList.add(3); int num = 4; List<Integer> notYellowstoneList = new ArrayList<Integer>(); int yellowSize = 3; while ( yellowSize < sequenceCount ) { int found = -1; for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) { int test = notYellowstoneList.get(index); if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) { found = index; break; } } if ( found >= 0 ) { yellowstoneList.add(notYellowstoneList.remove(found)); yellowSize++; } else { while ( true ) { if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) { yellowstoneList.add(num); yellowSize++; num++; break; } notYellowstoneList.add(num); num++; } } } return yellowstoneList; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) return; int[][] grid = new int[h][w]; Stack<Integer> stack = new Stack<>(); int half = (w * h) / 2; long bits = (long) Math.pow(2, half) - 1; for (; bits > 0; bits -= 2) { for (int i = 0; i < half; i++) { int r = i / w; int c = i % w; grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0; grid[h - r - 1][w - c - 1] = 1 - grid[r][c]; } stack.push(0); grid[0][0] = 2; int count = 1; while (!stack.empty()) { int pos = stack.pop(); int r = pos / w; int c = pos % w; for (int[] dir : dirs) { int nextR = r + dir[0]; int nextC = c + dir[1]; if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) { if (grid[nextR][nextC] == 1) { stack.push(nextR * w + nextC); grid[nextR][nextC] = 2; count++; } } } } if (count == half) { printResult(grid); } } } static void printResult(int[][] arr) { for (int[] a : arr) System.out.println(Arrays.toString(a)); System.out.println(); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) return; int[][] grid = new int[h][w]; Stack<Integer> stack = new Stack<>(); int half = (w * h) / 2; long bits = (long) Math.pow(2, half) - 1; for (; bits > 0; bits -= 2) { for (int i = 0; i < half; i++) { int r = i / w; int c = i % w; grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0; grid[h - r - 1][w - c - 1] = 1 - grid[r][c]; } stack.push(0); grid[0][0] = 2; int count = 1; while (!stack.empty()) { int pos = stack.pop(); int r = pos / w; int c = pos % w; for (int[] dir : dirs) { int nextR = r + dir[0]; int nextC = c + dir[1]; if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) { if (grid[nextR][nextC] == 1) { stack.push(nextR * w + nextC); grid[nextR][nextC] = 2; count++; } } } } if (count == half) { printResult(grid); } } } static void printResult(int[][] arr) { for (int[] a : arr) System.out.println(Arrays.toString(a)); System.out.println(); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
Produce a functionally identical C code for the snippet given in Java.
public class MertensFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the merten function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", mertenFunction(n)); if ( (n+1) % 20 == 0 ) { System.out.printf("%n"); } } for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) { int zeroCount = 0; int zeroCrossingCount = 0; int positiveCount = 0; int negativeCount = 0; int mSum = 0; int mMin = Integer.MAX_VALUE; int mMinIndex = 0; int mMax = Integer.MIN_VALUE; int mMaxIndex = 0; int nMax = (int) Math.pow(10, exponent); for ( int n = 1 ; n <= nMax ; n++ ) { int m = mertenFunction(n); mSum += m; if ( m < mMin ) { mMin = m; mMinIndex = n; } if ( m > mMax ) { mMax = m; mMaxIndex = n; } if ( m > 0 ) { positiveCount++; } if ( m < 0 ) { negativeCount++; } if ( m == 0 ) { zeroCount++; } if ( m == 0 && mertenFunction(n - 1) != 0 ) { zeroCrossingCount++; } } System.out.printf("%nFor M(x) with x from 1 to %,d%n", nMax); System.out.printf("The maximum of M(x) is M(%,d) = %,d.%n", mMaxIndex, mMax); System.out.printf("The minimum of M(x) is M(%,d) = %,d.%n", mMinIndex, mMin); System.out.printf("The sum of M(x) is %,d.%n", mSum); System.out.printf("The count of positive M(x) is %,d, count of negative M(x) is %,d.%n", positiveCount, negativeCount); System.out.printf("M(x) has %,d zeroes in the interval.%n", zeroCount); System.out.printf("M(x) has %,d crossings in the interval.%n", zeroCrossingCount); } } private static int MU_MAX = 100_000_000; private static int[] MU = null; private static int[] MERTEN = null; private static int mertenFunction(int n) { if ( MERTEN != null ) { return MERTEN[n]; } MU = new int[MU_MAX+1]; MERTEN = new int[MU_MAX+1]; MERTEN[1] = 1; int sqrt = (int) Math.sqrt(MU_MAX); for ( int i = 0 ; i < MU_MAX ; i++ ) { MU[i] = 1; } for ( int i = 2 ; i <= sqrt ; i++ ) { if ( MU[i] == 1 ) { for ( int j = i ; j <= MU_MAX ; j += i ) { MU[j] *= -i; } for ( int j = i*i ; j <= MU_MAX ; j += i*i ) { MU[j] = 0; } } } int sum = 1; for ( int i = 2 ; i <= MU_MAX ; i++ ) { if ( MU[i] == i ) { MU[i] = 1; } else if ( MU[i] == -i ) { MU[i] = -1; } else if ( MU[i] < 0 ) { MU[i] = 1; } else if ( MU[i] > 0 ) { MU[i] = -1; } sum += MU[i]; MERTEN[i] = sum; } return MERTEN[n]; } }
#include <stdio.h> #include <stdlib.h> int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main() { const int max = 1000; int* mertens = mertens_numbers(max); if (mertens == NULL) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 199 Mertens numbers:\n"); const int count = 200; for (int i = 0, column = 0; i < count; ++i) { if (column > 0) printf(" "); if (i == 0) printf(" "); else printf("%2d", mertens[i]); ++column; if (column == 20) { printf("\n"); column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { int m = mertens[i]; if (m == 0) { ++zero; if (previous != 0) ++cross; } previous = m; } free(mertens); printf("M(n) is zero %d times for 1 <= n <= %d.\n", zero, max); printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max); return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
import java.util.*; public class SortComp1 { public static void main(String[] args) { List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange"); List<String> sortedItems = new ArrayList<>(); Comparator<String> interactiveCompare = new Comparator<String>() { int count = 0; Scanner s = new Scanner(System.in); public int compare(String s1, String s2) { System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2); return s.nextInt(); } }; for (String item : items) { System.out.printf("Inserting '%s' into %s\n", item, sortedItems); int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare); if (spotToInsert < 0) spotToInsert = ~spotToInsert; sortedItems.add(spotToInsert, item); } System.out.println(sortedItems); } }
#include <stdio.h> #include <string.h> #include <stdlib.h> int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int response; scanf("%d", &response); return response; } void printOrder(const char *items[], int len) { printf("{ "); for (int i = 0; i < len; ++i) printf("%s ", items[i]); printf("}\n"); } int main(void) { const char *items[] = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }; qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare); printOrder(items, sizeof(items)/sizeof(*items)); return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
import java.util.*; public class SortComp1 { public static void main(String[] args) { List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange"); List<String> sortedItems = new ArrayList<>(); Comparator<String> interactiveCompare = new Comparator<String>() { int count = 0; Scanner s = new Scanner(System.in); public int compare(String s1, String s2) { System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2); return s.nextInt(); } }; for (String item : items) { System.out.printf("Inserting '%s' into %s\n", item, sortedItems); int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare); if (spotToInsert < 0) spotToInsert = ~spotToInsert; sortedItems.add(spotToInsert, item); } System.out.println(sortedItems); } }
#include <stdio.h> #include <string.h> #include <stdlib.h> int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int response; scanf("%d", &response); return response; } void printOrder(const char *items[], int len) { printf("{ "); for (int i = 0; i < len; ++i) printf("%s ", items[i]); printf("}\n"); } int main(void) { const char *items[] = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }; qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare); printOrder(items, sizeof(items)/sizeof(*items)); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
import java.math.BigInteger; import java.util.Locale; public class BenfordsLaw { private static BigInteger[] generateFibonacci(int n) { BigInteger[] fib = new BigInteger[n]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE; for (int i = 2; i < fib.length; i++) { fib[i] = fib[i - 2].add(fib[i - 1]); } return fib; } public static void main(String[] args) { BigInteger[] numbers = generateFibonacci(1000); int[] firstDigits = new int[10]; for (BigInteger number : numbers) { firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++; } for (int i = 1; i < firstDigits.length; i++) { System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n", i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i)); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Port the following code from Java to C with equivalent syntax and logic.
import java.math.BigInteger; import java.util.Locale; public class BenfordsLaw { private static BigInteger[] generateFibonacci(int n) { BigInteger[] fib = new BigInteger[n]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE; for (int i = 2; i < fib.length; i++) { fib[i] = fib[i - 2].add(fib[i - 1]); } return fib; } public static void main(String[] args) { BigInteger[] numbers = generateFibonacci(1000); int[] firstDigits = new int[10]; for (BigInteger number : numbers) { firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++; } for (int i = 1; i < firstDigits.length; i++) { System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n", i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i)); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Convert this Java snippet to C and keep its semantics consistent.
import java.math.BigInteger; import java.util.Locale; public class BenfordsLaw { private static BigInteger[] generateFibonacci(int n) { BigInteger[] fib = new BigInteger[n]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE; for (int i = 2; i < fib.length; i++) { fib[i] = fib[i - 2].add(fib[i - 1]); } return fib; } public static void main(String[] args) { BigInteger[] numbers = generateFibonacci(1000); int[] firstDigits = new int[10]; for (BigInteger number : numbers) { firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++; } for (int i = 1; i < firstDigits.length; i++) { System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n", i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i)); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Convert this Java snippet to C and keep its semantics consistent.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class NauticalBell extends Thread { public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.join(); } catch (InterruptedException e) { System.out.println(e); } } @Override public void run() { DateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); int numBells = 0; long time = System.currentTimeMillis(); long next = time - (time % (24 * 60 * 60 * 1000)); while (next < time) { next += 30 * 60 * 1000; numBells = 1 + (numBells % 8); } while (true) { long wait = 100L; time = System.currentTimeMillis(); if (time - next >= 0) { String bells = numBells == 1 ? "bell" : "bells"; String timeString = sdf.format(time); System.out.printf("%s : %d %s\n", timeString, numBells, bells); next += 30 * 60 * 1000; wait = next - time; numBells = 1 + (numBells % 8); } try { Thread.sleep(wait); } catch (InterruptedException e) { return; } } } }
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
Write the same algorithm in C as shown in this Java implementation.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class NauticalBell extends Thread { public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.join(); } catch (InterruptedException e) { System.out.println(e); } } @Override public void run() { DateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); int numBells = 0; long time = System.currentTimeMillis(); long next = time - (time % (24 * 60 * 60 * 1000)); while (next < time) { next += 30 * 60 * 1000; numBells = 1 + (numBells % 8); } while (true) { long wait = 100L; time = System.currentTimeMillis(); if (time - next >= 0) { String bells = numBells == 1 ? "bell" : "bells"; String timeString = sdf.format(time); System.out.printf("%s : %d %s\n", timeString, numBells, bells); next += 30 * 60 * 1000; wait = next - time; numBells = 1 + (numBells % 8); } try { Thread.sleep(wait); } catch (InterruptedException e) { return; } } } }
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
Maintain the same structure and functionality when rewriting this code in C.
public static long fib(int n) { if (n < 0) throw new IllegalArgumentException("n can not be a negative number"); return new Object() { private long fibInner(int n) { return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2)); } }.fibInner(n); }
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
Translate the given Java code snippet into C without altering its behavior.
public static long fib(int n) { if (n < 0) throw new IllegalArgumentException("n can not be a negative number"); return new Object() { private long fibInner(int n) { return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2)); } }.fibInner(n); }
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
String strOrig = 'brooms'; String str1 = strOrig.substring(1, strOrig.length()); system.debug(str1); String str2 = strOrig.substring(0, strOrig.length()-1); system.debug(str2); String str3 = strOrig.substring(1, strOrig.length()-1); system.debug(str3); String strOrig = 'brooms'; String str1 = strOrig.replaceAll( '^.', '' ); system.debug(str1); String str2 = strOrig.replaceAll( '.$', '' ) ; system.debug(str2); String str3 = strOrig.replaceAll( '^.|.$', '' ); system.debug(str3);
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
String strOrig = 'brooms'; String str1 = strOrig.substring(1, strOrig.length()); system.debug(str1); String str2 = strOrig.substring(0, strOrig.length()-1); system.debug(str2); String str3 = strOrig.substring(1, strOrig.length()-1); system.debug(str3); String strOrig = 'brooms'; String str1 = strOrig.replaceAll( '^.', '' ); system.debug(str1); String str2 = strOrig.replaceAll( '.$', '' ) ; system.debug(str2); String str3 = strOrig.replaceAll( '^.|.$', '' ); system.debug(str3);
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import java.util.*; public class LegendrePrimeCounter { public static void main(String[] args) { LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000); for (int i = 0, n = 1; i < 10; ++i, n *= 10) System.out.printf("10^%d\t%d\n", i, counter.primeCount((n))); } private List<Integer> primes; public LegendrePrimeCounter(int limit) { primes = generatePrimes((int)Math.sqrt((double)limit)); } public int primeCount(int n) { if (n < 2) return 0; int a = primeCount((int)Math.sqrt((double)n)); return phi(n, a) + a - 1; } private int phi(int x, int a) { if (a == 0) return x; if (a == 1) return x - (x >> 1); int pa = primes.get(a - 1); if (x <= pa) return 1; return phi(x, a - 1) - phi(x / pa, a - 1); } private static List<Integer> generatePrimes(int limit) { boolean[] sieve = new boolean[limit >> 1]; Arrays.fill(sieve, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } List<Integer> primes = new ArrayList<>(); if (limit > 2) primes.add(2); for (int i = 1; i < sieve.length; ++i) { if (sieve[i]) primes.add((i << 1) + 1); } return primes; } }
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <stdint.h> #include <time.h> const uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128}; #define half(n) ((int64_t)((n) - 1) >> 1) #define divide(nm, d) ((uint64_t)((double)nm / (double)d)) int64_t countPrimes(uint64_t n) { if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2; uint64_t rtlmt = (uint64_t)sqrt((double)n); int64_t mxndx = (int64_t)((rtlmt - 1) / 2); int arrlen = (int)(mxndx + 1); uint32_t *smalls = malloc(arrlen * 4); uint32_t *roughs = malloc(arrlen * 4); int64_t *larges = malloc(arrlen * 8); for (int i = 0; i < arrlen; ++i) { smalls[i] = (uint32_t)i; roughs[i] = (uint32_t)(i + i + 1); larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2); } int cullbuflen = (int)((mxndx + 8) / 8); uint8_t *cullbuf = calloc(cullbuflen, 1); int64_t nbps = 0; int rilmt = arrlen; for (int64_t i = 1; ; ++i) { int64_t sqri = (i + i) * (i + 1); if (sqri > mxndx) break; if (cullbuf[i >> 3] & masks[i & 7]) continue; cullbuf[i >> 3] |= masks[i & 7]; uint64_t bp = (uint64_t)(i + i + 1); for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) { cullbuf[c >> 3] |= masks[c & 7]; } int nri = 0; for (int ori = 0; ori < rilmt; ++ori) { uint32_t r = roughs[ori]; int64_t rci = (int64_t)(r >> 1); if (cullbuf[rci >> 3] & masks[rci & 7]) continue; uint64_t d = (uint64_t)r * bp; int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] : (int64_t)smalls[half(divide(n, d))]; larges[nri] = larges[ori] - t + nbps; roughs[nri] = r; nri++; } int64_t si = mxndx; for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) { uint32_t c = smalls[pm >> 1]; uint64_t e = (pm * bp) >> 1; for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps; } rilmt = nri; nbps++; } int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2); int ri, sri; for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri]; for (ri = 1; ; ++ri) { uint64_t p = (uint64_t)roughs[ri]; uint64_t m = n / p; int ei = (int)smalls[half((uint64_t)m/p)] - nbps; if (ei <= ri) break; ans -= (int64_t)((ei - ri) * (nbps + ri - 1)); for (sri = ri + 1; sri < ei + 1; ++sri) { ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))]; } } free(smalls); free(roughs); free(larges); free(cullbuf); return ans + 1; } int main() { uint64_t n; int i; clock_t start = clock(); for (i = 0, n = 1; i < 10; ++i, n *= 10) { printf("10^%d %ld\n", i, countPrimes(n)); } clock_t end = clock(); printf("\nTook %f seconds\n", (double) (end - start) / CLOCKS_PER_SEC); return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public class Query { public static boolean call(byte[] data, int[] length) throws java.io.UnsupportedEncodingException { String message = "Here am I"; byte[] mb = message.getBytes("utf-8"); if (length[0] < mb.length) return false; length[0] = mb.length; System.arraycopy(mb, 0, data, 0, mb.length); return true; } }
#include <stdio.h> extern int Query (char * Data, size_t * Length); int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer); if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.io.File; import java.util.Scanner; public class LongestStringChallenge { public static void main(String[] args) throws Exception { String lines = "", longest = ""; try (Scanner sc = new Scanner(new File("lines.txt"))) { while(sc.hasNext()) { String line = sc.nextLine(); if (longer(longest, line)) lines = longest = line; else if (!longer(line, longest)) lines = lines.concat("\n").concat(line); } } System.out.println(lines); } static boolean longer(String a, String b) { try { String dummy = a.substring(b.length()); } catch (StringIndexOutOfBoundsException e) { return true; } return false; } }
#include <stdio.h> #include <string.h> int cmp(const char *p, const char *q) { while (*p && *q) p = &p[1], q = &q[1]; return *p; } int main() { char line[65536]; char buf[1000000] = {0}; char *last = buf; char *next = buf; while (gets(line)) { strcat(line, "\n"); if (cmp(last, line)) continue; if (cmp(line, last)) next = buf; last = next; strcpy(next, line); while (*next) next = &next[1]; } printf("%s", buf); return 0; }
Translate the given Java code snippet into C without altering its behavior.
import java.io.*; public class CreateFileTest { public static void main(String args[]) { try { new File("output.txt").createNewFile(); new File(File.separator + "output.txt").createNewFile(); new File("docs").mkdir(); new File(File.separator + "docs").mkdir(); } catch (IOException e) { System.err.println(e.getMessage()); } } }
#include <stdio.h> int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh); return 0; }
Convert the following code from Java to C, ensuring the logic remains intact.
public class UnprimeableNumbers { private static int MAX = 10_000_000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { sieve(); System.out.println("First 35 unprimeable numbers:"); displayUnprimeableNumbers(35); int n = 600; System.out.printf("%nThe %dth unprimeable number = %,d%n%n", n, nthUnprimeableNumber(n)); int[] lowest = genLowest(); System.out.println("Least unprimeable number that ends in:"); for ( int i = 0 ; i <= 9 ; i++ ) { System.out.printf(" %d is %,d%n", i, lowest[i]); } } private static int[] genLowest() { int[] lowest = new int[10]; int count = 0; int test = 1; while ( count < 10 ) { test++; if ( unPrimable(test) && lowest[test % 10] == 0 ) { lowest[test % 10] = test; count++; } } return lowest; } private static int nthUnprimeableNumber(int maxCount) { int test = 1; int count = 0; int result = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; result = test; } } return result; } private static void displayUnprimeableNumbers(int maxCount) { int test = 1; int count = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; System.out.printf("%d ", test); } } System.out.println(); } private static boolean unPrimable(int test) { if ( primes[test] ) { return false; } String s = test + ""; for ( int i = 0 ; i < s.length() ; i++ ) { for ( int j = 0 ; j <= 9 ; j++ ) { if ( primes[Integer.parseInt(replace(s, i, j))] ) { return false; } } } return true; } private static String replace(String str, int position, int value) { char[] sChar = str.toCharArray(); sChar[position] = (char) value; return str.substring(0, position) + value + str.substring(position + 1); } 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; } } } } }
#include <assert.h> #include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> typedef struct bit_array_tag { uint32_t size; uint32_t* array; } bit_array; bool bit_array_create(bit_array* b, uint32_t size) { uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t)); if (array == NULL) return false; b->size = size; b->array = array; return true; } void bit_array_destroy(bit_array* b) { free(b->array); b->array = NULL; } void bit_array_set(bit_array* b, uint32_t index, bool value) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); if (value) *p |= bit; else *p &= ~bit; } bool bit_array_get(const bit_array* b, uint32_t index) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); return (*p & bit) != 0; } typedef struct sieve_tag { uint32_t limit; bit_array not_prime; } sieve; bool sieve_create(sieve* s, uint32_t limit) { if (!bit_array_create(&s->not_prime, limit/2)) return false; for (uint32_t p = 3; p * p <= limit; p += 2) { if (bit_array_get(&s->not_prime, p/2 - 1) == false) { uint32_t inc = 2 * p; for (uint32_t q = p * p; q <= limit; q += inc) bit_array_set(&s->not_prime, q/2 - 1, true); } } s->limit = limit; return true; } void sieve_destroy(sieve* s) { bit_array_destroy(&s->not_prime); } bool is_prime(const sieve* s, uint32_t n) { assert(n <= s->limit); if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; return bit_array_get(&s->not_prime, n/2 - 1) == false; } uint32_t count_digits(uint32_t n) { uint32_t digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) { uint32_t p = 1; uint32_t changed = 0; for (; index > 0; p *= 10, n /= 10, --index) changed += p * (n % 10); changed += (10 * (n/10) + new_digit) * p; return changed; } bool unprimeable(const sieve* s, uint32_t n) { if (is_prime(s, n)) return false; uint32_t d = count_digits(n); for (uint32_t i = 0; i < d; ++i) { for (uint32_t j = 0; j <= 9; ++j) { uint32_t m = change_digit(n, i, j); if (m != n && is_prime(s, m)) return false; } } return true; } int main() { const uint32_t limit = 10000000; setlocale(LC_ALL, ""); sieve s = { 0 }; if (!sieve_create(&s, limit)) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 35 unprimeable numbers:\n"); uint32_t n = 100; uint32_t lowest[10] = { 0 }; for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) { if (unprimeable(&s, n)) { if (count < 35) { if (count != 0) printf(", "); printf("%'u", n); } ++count; if (count == 600) printf("\n600th unprimeable number: %'u\n", n); uint32_t last_digit = n % 10; if (lowest[last_digit] == 0) { lowest[last_digit] = n; ++found; } } } sieve_destroy(&s); for (uint32_t i = 0; i < 10; ++i) printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]); return 0; }
Write the same code in C as shown below in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PascalsTrianglePuzzle { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d), Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d), Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d)); List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d); List<Double> solution = cramersRule(mat, b); System.out.println("Solution = " + cramersRule(mat, b)); System.out.printf("X = %.2f%n", solution.get(8)); System.out.printf("Y = %.2f%n", solution.get(9)); System.out.printf("Z = %.2f%n", solution.get(10)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
#include <stdio.h> #include <math.h> void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n"); return 0; }
Translate this program into C but keep the logic exactly as in Java.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PascalsTrianglePuzzle { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d), Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d), Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d)); List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d); List<Double> solution = cramersRule(mat, b); System.out.println("Solution = " + cramersRule(mat, b)); System.out.printf("X = %.2f%n", solution.get(8)); System.out.printf("Y = %.2f%n", solution.get(9)); System.out.printf("Z = %.2f%n", solution.get(10)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
#include <stdio.h> #include <math.h> void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n"); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PascalsTrianglePuzzle { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d), Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d), Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d)); List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d); List<Double> solution = cramersRule(mat, b); System.out.println("Solution = " + cramersRule(mat, b)); System.out.printf("X = %.2f%n", solution.get(8)); System.out.printf("Y = %.2f%n", solution.get(9)); System.out.printf("Z = %.2f%n", solution.get(10)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
#include <stdio.h> #include <math.h> void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n"); return 0; }
Write the same algorithm in C as shown in this Java implementation.
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class ChernicksCarmichaelNumbers { public static void main(String[] args) { for ( long n = 3 ; n < 10 ; n++ ) { long m = 0; boolean foundComposite = true; List<Long> factors = null; while ( foundComposite ) { m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5); factors = U(n, m); foundComposite = false; for ( long factor : factors ) { if ( ! isPrime(factor) ) { foundComposite = true; break; } } } System.out.printf("U(%d, %d) = %s = %s %n", n, m, display(factors), multiply(factors)); } } private static String display(List<Long> factors) { return factors.toString().replace("[", "").replace("]", "").replaceAll(", ", " * "); } private static BigInteger multiply(List<Long> factors) { BigInteger result = BigInteger.ONE; for ( long factor : factors ) { result = result.multiply(BigInteger.valueOf(factor)); } return result; } private static List<Long> U(long n, long m) { List<Long> factors = new ArrayList<>(); factors.add(6*m + 1); factors.add(12*m + 1); for ( int i = 1 ; i <= n-2 ; i++ ) { factors.add(((long)Math.pow(2, i)) * 9 * m + 1); } return factors; } 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 <stdlib.h> #include <gmp.h> typedef unsigned long long int u64; #define TRUE 1 #define FALSE 0 int primality_pretest(u64 k) { if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23); return TRUE; } int probprime(u64 k, mpz_t n) { mpz_set_ui(n, k); return mpz_probab_prime_p(n, 0); } int is_chernick(int n, u64 m, mpz_t z) { u64 t = 9 * m; if (primality_pretest(6 * m + 1) == FALSE) return FALSE; if (primality_pretest(12 * m + 1) == FALSE) return FALSE; for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE; if (probprime(6 * m + 1, z) == FALSE) return FALSE; if (probprime(12 * m + 1, z) == FALSE) return FALSE; for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE; return TRUE; } int main(int argc, char const *argv[]) { mpz_t z; mpz_inits(z, NULL); for (int n = 3; n <= 10; n ++) { u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1; if (n > 5) multiplier *= 5; for (u64 k = 1; ; k++) { u64 m = k * multiplier; if (is_chernick(n, m, z) == TRUE) { printf("a(%d) has m = %llu\n", n, m); break; } } } return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.util.Objects; public class FindTriangle { private static final double EPS = 0.001; private static final double EPS_SQUARE = EPS * EPS; public static class Point { private final double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } @Override public String toString() { return String.format("(%f, %f)", x, y); } } public static class Triangle { private final Point p1, p2, p3; public Triangle(Point p1, Point p2, Point p3) { this.p1 = Objects.requireNonNull(p1); this.p2 = Objects.requireNonNull(p2); this.p3 = Objects.requireNonNull(p3); } public Point getP1() { return p1; } public Point getP2() { return p2; } public Point getP3() { return p3; } private boolean pointInTriangleBoundingBox(Point p) { var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS; var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS; var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS; var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS; return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY()); } private static double side(Point p1, Point p2, Point p) { return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY()); } private boolean nativePointInTriangle(Point p) { boolean checkSide1 = side(p1, p2, p) >= 0; boolean checkSide2 = side(p2, p3, p) >= 0; boolean checkSide3 = side(p3, p1, p) >= 0; return checkSide1 && checkSide2 && checkSide3; } private double distanceSquarePointToSegment(Point p1, Point p2, Point p) { double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY()); double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength; if (dotProduct < 0) { return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY()); } if (dotProduct <= 1) { double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY()); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY()); } private boolean accuratePointInTriangle(Point p) { if (!pointInTriangleBoundingBox(p)) { return false; } if (nativePointInTriangle(p)) { return true; } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { return true; } return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE; } public boolean within(Point p) { Objects.requireNonNull(p); return accuratePointInTriangle(p); } @Override public String toString() { return String.format("Triangle[%s, %s, %s]", p1, p2, p3); } } private static void test(Triangle t, Point p) { System.out.println(t); System.out.printf("Point %s is within triangle? %s\n", p, t.within(p)); } public static void main(String[] args) { var p1 = new Point(1.5, 2.4); var p2 = new Point(5.1, -3.1); var p3 = new Point(-3.8, 1.2); var tri = new Triangle(p1, p2, p3); test(tri, new Point(0, 0)); test(tri, new Point(0, 1)); test(tri, new Point(3, 1)); System.out.println(); p1 = new Point(1.0 / 10, 1.0 / 9); p2 = new Point(100.0 / 8, 100.0 / 3); p3 = new Point(100.0 / 4, 100.0 / 9); tri = new Triangle(p1, p2, p3); var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY())); test(tri, pt); System.out.println(); p3 = new Point(-100.0 / 8, 100.0 / 6); tri = new Triangle(p1, p2, p3); test(tri, pt); } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf("(%f, %f)", x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf("Triangle is ["); printPoint(x1, y1); printf(", "); printPoint(x2, y2); printf(", "); printPoint(x3, y3); printf("] \n"); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf("Point "); printPoint(x, y); printf(" is within triangle? "); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf("true\n"); } else { printf("false\n"); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf("\n"); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import java.util.Objects; public class FindTriangle { private static final double EPS = 0.001; private static final double EPS_SQUARE = EPS * EPS; public static class Point { private final double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } @Override public String toString() { return String.format("(%f, %f)", x, y); } } public static class Triangle { private final Point p1, p2, p3; public Triangle(Point p1, Point p2, Point p3) { this.p1 = Objects.requireNonNull(p1); this.p2 = Objects.requireNonNull(p2); this.p3 = Objects.requireNonNull(p3); } public Point getP1() { return p1; } public Point getP2() { return p2; } public Point getP3() { return p3; } private boolean pointInTriangleBoundingBox(Point p) { var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS; var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS; var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS; var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS; return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY()); } private static double side(Point p1, Point p2, Point p) { return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY()); } private boolean nativePointInTriangle(Point p) { boolean checkSide1 = side(p1, p2, p) >= 0; boolean checkSide2 = side(p2, p3, p) >= 0; boolean checkSide3 = side(p3, p1, p) >= 0; return checkSide1 && checkSide2 && checkSide3; } private double distanceSquarePointToSegment(Point p1, Point p2, Point p) { double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY()); double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength; if (dotProduct < 0) { return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY()); } if (dotProduct <= 1) { double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY()); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY()); } private boolean accuratePointInTriangle(Point p) { if (!pointInTriangleBoundingBox(p)) { return false; } if (nativePointInTriangle(p)) { return true; } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { return true; } return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE; } public boolean within(Point p) { Objects.requireNonNull(p); return accuratePointInTriangle(p); } @Override public String toString() { return String.format("Triangle[%s, %s, %s]", p1, p2, p3); } } private static void test(Triangle t, Point p) { System.out.println(t); System.out.printf("Point %s is within triangle? %s\n", p, t.within(p)); } public static void main(String[] args) { var p1 = new Point(1.5, 2.4); var p2 = new Point(5.1, -3.1); var p3 = new Point(-3.8, 1.2); var tri = new Triangle(p1, p2, p3); test(tri, new Point(0, 0)); test(tri, new Point(0, 1)); test(tri, new Point(3, 1)); System.out.println(); p1 = new Point(1.0 / 10, 1.0 / 9); p2 = new Point(100.0 / 8, 100.0 / 3); p3 = new Point(100.0 / 4, 100.0 / 9); tri = new Triangle(p1, p2, p3); var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY())); test(tri, pt); System.out.println(); p3 = new Point(-100.0 / 8, 100.0 / 6); tri = new Triangle(p1, p2, p3); test(tri, pt); } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf("(%f, %f)", x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf("Triangle is ["); printPoint(x1, y1); printf(", "); printPoint(x2, y2); printf(", "); printPoint(x3, y3); printf("] \n"); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf("Point "); printPoint(x, y); printf(" is within triangle? "); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf("true\n"); } else { printf("false\n"); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf("\n"); return 0; }
Translate this program into C but keep the logic exactly as in Java.
import java.util.Objects; public class FindTriangle { private static final double EPS = 0.001; private static final double EPS_SQUARE = EPS * EPS; public static class Point { private final double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } @Override public String toString() { return String.format("(%f, %f)", x, y); } } public static class Triangle { private final Point p1, p2, p3; public Triangle(Point p1, Point p2, Point p3) { this.p1 = Objects.requireNonNull(p1); this.p2 = Objects.requireNonNull(p2); this.p3 = Objects.requireNonNull(p3); } public Point getP1() { return p1; } public Point getP2() { return p2; } public Point getP3() { return p3; } private boolean pointInTriangleBoundingBox(Point p) { var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS; var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS; var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS; var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS; return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY()); } private static double side(Point p1, Point p2, Point p) { return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY()); } private boolean nativePointInTriangle(Point p) { boolean checkSide1 = side(p1, p2, p) >= 0; boolean checkSide2 = side(p2, p3, p) >= 0; boolean checkSide3 = side(p3, p1, p) >= 0; return checkSide1 && checkSide2 && checkSide3; } private double distanceSquarePointToSegment(Point p1, Point p2, Point p) { double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY()); double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength; if (dotProduct < 0) { return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY()); } if (dotProduct <= 1) { double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY()); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY()); } private boolean accuratePointInTriangle(Point p) { if (!pointInTriangleBoundingBox(p)) { return false; } if (nativePointInTriangle(p)) { return true; } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { return true; } return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE; } public boolean within(Point p) { Objects.requireNonNull(p); return accuratePointInTriangle(p); } @Override public String toString() { return String.format("Triangle[%s, %s, %s]", p1, p2, p3); } } private static void test(Triangle t, Point p) { System.out.println(t); System.out.printf("Point %s is within triangle? %s\n", p, t.within(p)); } public static void main(String[] args) { var p1 = new Point(1.5, 2.4); var p2 = new Point(5.1, -3.1); var p3 = new Point(-3.8, 1.2); var tri = new Triangle(p1, p2, p3); test(tri, new Point(0, 0)); test(tri, new Point(0, 1)); test(tri, new Point(3, 1)); System.out.println(); p1 = new Point(1.0 / 10, 1.0 / 9); p2 = new Point(100.0 / 8, 100.0 / 3); p3 = new Point(100.0 / 4, 100.0 / 9); tri = new Triangle(p1, p2, p3); var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY())); test(tri, pt); System.out.println(); p3 = new Point(-100.0 / 8, 100.0 / 6); tri = new Triangle(p1, p2, p3); test(tri, pt); } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf("(%f, %f)", x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf("Triangle is ["); printPoint(x1, y1); printf(", "); printPoint(x2, y2); printf(", "); printPoint(x3, y3); printf("] \n"); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf("Point "); printPoint(x, y); printf(" is within triangle? "); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf("true\n"); } else { printf("false\n"); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf("\n"); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
public class TauFunction { 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; } public static void main(String[] args) { final int limit = 100; System.out.printf("Count of divisors for the first %d positive integers:\n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%3d", divisorCount(n)); if (n % 20 == 0) { System.out.println(); } } } }
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Count of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%3d", divisor_count(n)); if (n % 20 == 0) { printf("\n"); } } return 0; }
Keep all operations the same but rewrite the snippet in C.
public class TauFunction { 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; } public static void main(String[] args) { final int limit = 100; System.out.printf("Count of divisors for the first %d positive integers:\n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%3d", divisorCount(n)); if (n % 20 == 0) { System.out.println(); } } } }
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Count of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%3d", divisor_count(n)); if (n % 20 == 0) { printf("\n"); } } return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.math.BigInteger; public class PrimorialPrimes { final static int sieveLimit = 1550_000; static boolean[] notPrime = sieve(sieveLimit); public static void main(String[] args) { int count = 0; for (int i = 1; i < 1000_000 && count < 20; i++) { BigInteger b = primorial(i); if (b.add(BigInteger.ONE).isProbablePrime(1) || b.subtract(BigInteger.ONE).isProbablePrime(1)) { System.out.printf("%d ", i); count++; } } } static BigInteger primorial(int n) { if (n == 0) return BigInteger.ONE; BigInteger result = BigInteger.ONE; for (int i = 0; i < sieveLimit && n > 0; i++) { if (notPrime[i]) continue; result = result.multiply(BigInteger.valueOf(i)); n--; } return result; } public static boolean[] sieve(int limit) { boolean[] composite = new boolean[limit]; composite[0] = composite[1] = true; int max = (int) Math.sqrt(limit); for (int n = 2; n <= max; n++) { if (!composite[n]) { for (int k = n * n; k < limit; k += n) { composite[k] = true; } } } return composite; } }
#include <gmp.h> int main(void) { mpz_t p, s; mpz_init_set_ui(p, 1); mpz_init_set_ui(s, 1); for (int n = 1, i = 0; i < 20; n++) { mpz_nextprime(s, s); mpz_mul(p, p, s); mpz_add_ui(p, p, 1); if (mpz_probab_prime_p(p, 25)) { mpz_sub_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_sub_ui(p, p, 2); if (mpz_probab_prime_p(p, 25)) { mpz_add_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_add_ui(p, p, 1); } mpz_clear(s); mpz_clear(p); }
Please provide an equivalent version of this Java code in C.
import java.math.BigInteger; public class PrimorialPrimes { final static int sieveLimit = 1550_000; static boolean[] notPrime = sieve(sieveLimit); public static void main(String[] args) { int count = 0; for (int i = 1; i < 1000_000 && count < 20; i++) { BigInteger b = primorial(i); if (b.add(BigInteger.ONE).isProbablePrime(1) || b.subtract(BigInteger.ONE).isProbablePrime(1)) { System.out.printf("%d ", i); count++; } } } static BigInteger primorial(int n) { if (n == 0) return BigInteger.ONE; BigInteger result = BigInteger.ONE; for (int i = 0; i < sieveLimit && n > 0; i++) { if (notPrime[i]) continue; result = result.multiply(BigInteger.valueOf(i)); n--; } return result; } public static boolean[] sieve(int limit) { boolean[] composite = new boolean[limit]; composite[0] = composite[1] = true; int max = (int) Math.sqrt(limit); for (int n = 2; n <= max; n++) { if (!composite[n]) { for (int k = n * n; k < limit; k += n) { composite[k] = true; } } } return composite; } }
#include <gmp.h> int main(void) { mpz_t p, s; mpz_init_set_ui(p, 1); mpz_init_set_ui(s, 1); for (int n = 1, i = 0; i < 20; n++) { mpz_nextprime(s, s); mpz_mul(p, p, s); mpz_add_ui(p, p, 1); if (mpz_probab_prime_p(p, 25)) { mpz_sub_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_sub_ui(p, p, 2); if (mpz_probab_prime_p(p, 25)) { mpz_add_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_add_ui(p, p, 1); } mpz_clear(s); mpz_clear(p); }
Port the provided Java code into C while preserving the original functionality.
import java.util.HashMap; import java.util.Map; public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } } public class Sequence { private final String seq; public Sequence(String sq) { this.seq = sq; } public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s : %s\n", seq.length(), seq.substring(i)); } public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); } System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s : %s\n", key, value)); System.out.printf("%5s: %s\n", "SUM", seq.length()); } public void runSequence() { this.prettyPrint(); this.displayCount(); } }
#include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf("Sequence:\n"); while(genomeIterator!=NULL){ printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf("\n\nBase Count\n----------\n\n"); printf("%3c%3s%*d\n",'A',":",width+1,Adenine); printf("%3c%3s%*d\n",'T',":",width+1,Thymine); printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); printf("%3c%3s%*d\n",'G',":",width+1,Guanine); printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf("Usage : %s <Gene file name>\n",argv[0]); return 0; } FILE *fp = fopen(argv[1],"r"); while(fscanf(fp,"%s",str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.util.HashMap; import java.util.Map; public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } } public class Sequence { private final String seq; public Sequence(String sq) { this.seq = sq; } public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s : %s\n", seq.length(), seq.substring(i)); } public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); } System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s : %s\n", key, value)); System.out.printf("%5s: %s\n", "SUM", seq.length()); } public void runSequence() { this.prettyPrint(); this.displayCount(); } }
#include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf("Sequence:\n"); while(genomeIterator!=NULL){ printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf("\n\nBase Count\n----------\n\n"); printf("%3c%3s%*d\n",'A',":",width+1,Adenine); printf("%3c%3s%*d\n",'T',":",width+1,Thymine); printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); printf("%3c%3s%*d\n",'G',":",width+1,Guanine); printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf("Usage : %s <Gene file name>\n",argv[0]); return 0; } FILE *fp = fopen(argv[1],"r"); while(fscanf(fp,"%s",str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
Translate the given Java code snippet into C without altering its behavior.
package diningphilosophers; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; enum PhilosopherState { Get, Eat, Pon } class Fork { public static final int ON_TABLE = -1; static int instances = 0; public int id; public AtomicInteger holder = new AtomicInteger(ON_TABLE); Fork() { id = instances++; } } class Philosopher implements Runnable { static final int maxWaitMs = 100; static AtomicInteger token = new AtomicInteger(0); static int instances = 0; static Random rand = new Random(); AtomicBoolean end = new AtomicBoolean(false); int id; PhilosopherState state = PhilosopherState.Get; Fork left; Fork right; int timesEaten = 0; Philosopher() { id = instances++; left = Main.forks.get(id); right = Main.forks.get((id+1)%Main.philosopherCount); } void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); } catch (InterruptedException ex) {} } void waitForFork(Fork fork) { do { if (fork.holder.get() == Fork.ON_TABLE) { fork.holder.set(id); return; } else { sleep(); } } while (true); } public void run() { do { if (state == PhilosopherState.Pon) { state = PhilosopherState.Get; } else { if (token.get() == id) { waitForFork(left); waitForFork(right); token.set((id+2)% Main.philosopherCount); state = PhilosopherState.Eat; timesEaten++; sleep(); left.holder.set(Fork.ON_TABLE); right.holder.set(Fork.ON_TABLE); state = PhilosopherState.Pon; sleep(); } else { sleep(); } } } while (!end.get()); } } public class Main { static final int philosopherCount = 5; static final int runSeconds = 15; static ArrayList<Fork> forks = new ArrayList<Fork>(); static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>(); public static void main(String[] args) { for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork()); for (int i = 0 ; i < philosopherCount ; i++) philosophers.add(new Philosopher()); for (Philosopher p : philosophers) new Thread(p).start(); long endTime = System.currentTimeMillis() + (runSeconds * 1000); do { StringBuilder sb = new StringBuilder("|"); for (Philosopher p : philosophers) { sb.append(p.state.toString()); sb.append("|"); } sb.append(" |"); for (Fork f : forks) { int holder = f.holder.get(); sb.append(holder==-1?" ":String.format("P%02d",holder)); sb.append("|"); } System.out.println(sb.toString()); try {Thread.sleep(1000);} catch (Exception ex) {} } while (System.currentTimeMillis() < endTime); for (Philosopher p : philosophers) p.end.set(true); for (Philosopher p : philosophers) System.out.printf("P%02d: ate %,d times, %,d/sec\n", p.id, p.timesEaten, p.timesEaten/runSeconds); } }
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdarg.h> #define N 5 const char *names[N] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" }; pthread_mutex_t forks[N]; #define M 5 const char *topic[M] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" }; #define lock pthread_mutex_lock #define unlock pthread_mutex_unlock #define xy(x, y) printf("\033[%d;%dH", x, y) #define clear_eol(x) print(x, 12, "\033[K") void print(int y, int x, const char *fmt, ...) { static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; va_list ap; va_start(ap, fmt); lock(&screen); xy(y + 1, x), vprintf(fmt, ap); xy(N + 1, 1), fflush(stdout); unlock(&screen); } void eat(int id) { int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % N; clear_eol(id); print(id, 12, "..oO (forks, need forks)"); for (i = 0; i < 2; i++) { lock(forks + f[i]); if (!i) clear_eol(id); print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]); sleep(1); } for (i = 0, ration = 3 + rand() % 8; i < ration; i++) print(id, 24 + i * 4, "nom"), sleep(1); for (i = 0; i < 2; i++) unlock(forks + f[i]); } void think(int id) { int i, t; char buf[64] = {0}; do { clear_eol(id); sprintf(buf, "..oO (%s)", topic[t = rand() % M]); for (i = 0; buf[i]; i++) { print(id, i+12, "%c", buf[i]); if (i < 5) usleep(200000); } usleep(500000 + rand() % 1000000); } while (t); } void* philosophize(void *a) { int id = *(int*)a; print(id, 1, "%10s", names[id]); while(1) think(id), eat(id); } int main() { int i, id[N]; pthread_t tid[N]; for (i = 0; i < N; i++) pthread_mutex_init(forks + (id[i] = i), 0); for (i = 0; i < N; i++) pthread_create(tid + i, 0, philosophize, id + i); return pthread_join(tid[0], 0); }
Convert this Java snippet to C and keep its semantics consistent.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { sum = 0; j = i; while (j > 0) { d = j % b; sum += fact[d]; j /= b; } if (sum == i) printf("%llu ", i); } printf("\n\n"); } return 0; }
Write the same algorithm in C as shown in this Java implementation.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { sum = 0; j = i; while (j > 0) { d = j % b; sum += fact[d]; j /= b; } if (sum == i) printf("%llu ", i); } printf("\n\n"); } return 0; }
Convert this Java block to C, preserving its control flow and logic.
import java.util.List; import java.util.function.Function; public class LogisticCurveFitting { private static final double K = 7.8e9; private static final int N0 = 27; private static final List<Double> ACTUAL = List.of( 27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0, 61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0, 4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0, 31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0, 69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0, 80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0, 95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0, 133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0, 271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0, 656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0 ); private static double f(double r) { var sq = 0.0; var len = ACTUAL.size(); for (int i = 0; i < len; i++) { var eri = Math.exp(r * i); var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K); var diff = guess - ACTUAL.get(i); sq += diff * diff; } return sq; } private static double solve(Function<Double, Double> fn) { return solve(fn, 0.5, 0.0); } private static double solve(Function<Double, Double> fn, double guess, double epsilon) { double delta; if (guess != 0.0) { delta = guess; } else { delta = 1.0; } var f0 = fn.apply(guess); var factor = 2.0; while (delta > epsilon && guess != guess - delta) { var nf = fn.apply(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn.apply(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else { factor = 0.5; } } delta *= factor; } return guess; } public static void main(String[] args) { var r = solve(LogisticCurveFitting::f); var r0 = Math.exp(12.0 * r); System.out.printf("r = %.16f, R0 = %.16f\n", r, r0); } }
#include <math.h> #include <stdio.h> const double K = 7.8e9; const int n0 = 27; const double actual[] = { 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652 }; const size_t actual_size = sizeof(actual) / sizeof(double); double f(double r) { double sq = 0; size_t i; for (i = 0; i < actual_size; ++i) { double eri = exp(r * i); double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K); double diff = guess - actual[i]; sq += diff * diff; } return sq; } double solve(double (*fn)(double), double guess, double epsilon) { double delta, f0, factor; for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2; delta > epsilon && guess != guess - delta; delta *= factor) { double nf = (*fn)(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else { factor = 0.5; } } } return guess; } double solve_default(double (*fn)(double)) { return solve(fn, 0.5, 0); } int main() { double r = solve_default(f); double R0 = exp(12 * r); printf("r = %f, R0 = %f\n", r, R0); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.util.Arrays; import java.util.LinkedList; public class Strand{ public static <E extends Comparable<? super E>> LinkedList<E> strandSort(LinkedList<E> list){ if(list.size() <= 1) return list; LinkedList<E> result = new LinkedList<E>(); while(list.size() > 0){ LinkedList<E> sorted = new LinkedList<E>(); sorted.add(list.removeFirst()); for(Iterator<E> it = list.iterator(); it.hasNext(); ){ E elem = it.next(); if(sorted.peekLast().compareTo(elem) <= 0){ sorted.addLast(elem); it.remove(); } } result = merge(sorted, result); } return result; } private static <E extends Comparable<? super E>> LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){ LinkedList<E> result = new LinkedList<E>(); while(!left.isEmpty() && !right.isEmpty()){ if(left.peek().compareTo(right.peek()) <= 0) result.add(left.remove()); else result.add(right.remove()); } result.addAll(left); result.addAll(right); return result; } public static void main(String[] args){ System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5)))); System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5)))); System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6)))); } }
#include <stdio.h> typedef struct node_t *node, node_t; struct node_t { int v; node next; }; typedef struct { node head, tail; } slist; void push(slist *l, node e) { if (!l->head) l->head = e; if (l->tail) l->tail->next = e; l->tail = e; } node removehead(slist *l) { node e = l->head; if (e) { l->head = e->next; e->next = 0; } return e; } void join(slist *a, slist *b) { push(a, b->head); a->tail = b->tail; } void merge(slist *a, slist *b) { slist r = {0}; while (a->head && b->head) push(&r, removehead(a->head->v <= b->head->v ? a : b)); join(&r, a->head ? a : b); *a = r; b->head = b->tail = 0; } void sort(int *ar, int len) { node_t all[len]; for (int i = 0; i < len; i++) all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0; slist list = {all, all + len - 1}, rem, strand = {0}, res = {0}; for (node e = 0; list.head; list = rem) { rem.head = rem.tail = 0; while ((e = removehead(&list))) push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e); merge(&res, &strand); } for (int i = 0; res.head; i++, res.head = res.head->next) ar[i] = res.head->v; } void show(const char *title, int *x, int len) { printf("%s ", title); for (int i = 0; i < len; i++) printf("%3d ", x[i]); putchar('\n'); } int main(void) { int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2}; # define SIZE sizeof(x)/sizeof(int) show("before sort:", x, SIZE); sort(x, sizeof(x)/sizeof(int)); show("after sort: ", x, SIZE); return 0; }
Port the provided Java code into C while preserving the original functionality.
public class additivePrimes { public static void main(String[] args) { int additive_primes = 0; for (int i = 2; i < 500; i++) { if(isPrime(i) && isPrime(digitSum(i))){ additive_primes++; System.out.print(i + " "); } } System.out.print("\nFound " + additive_primes + " additive primes less than 500"); } static boolean isPrime(int n) { int counter = 1; if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) { return false; } while (counter * 6 - 1 <= Math.sqrt(n)) { if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) { return false; } else { counter++; } } return true; } static int digitSum(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } }
#include <stdbool.h> #include <stdio.h> #include <string.h> void memoizeIsPrime( bool * result, const int N ) { result[2] = true; result[3] = true; int prime[N]; prime[0] = 3; int end = 1; for (int n = 5; n < N; n += 2) { bool n_is_prime = true; for (int i = 0; i < end; ++i) { const int PRIME = prime[i]; if (n % PRIME == 0) { n_is_prime = false; break; } if (PRIME * PRIME > n) { break; } } if (n_is_prime) { prime[end++] = n; result[n] = true; } } } int sumOfDecimalDigits( int n ) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } int main( void ) { const int N = 500; printf( "Rosetta Code: additive primes less than %d:\n", N ); bool is_prime[N]; memset( is_prime, 0, sizeof(is_prime) ); memoizeIsPrime( is_prime, N ); printf( " 2" ); int count = 1; for (int i = 3; i < N; i += 2) { if (is_prime[i] && is_prime[sumOfDecimalDigits( i )]) { printf( "%4d", i ); ++count; if ((count % 10) == 0) { printf( "\n" ); } } } printf( "\nThose were %d additive primes.\n", count ); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Integer> perfectTotient(int n) { int test = 2; List<Integer> results = new ArrayList<Integer>(); for ( int i = 0 ; i < n ; test++ ) { int phiLoop = test; int sum = 0; do { phiLoop = phi[phiLoop]; sum += phiLoop; } while ( phiLoop > 1); if ( sum == test ) { i++; results.add(test); } } return results; } private static final int max = 100000; 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<stdlib.h> #include<stdio.h> long totient(long n){ long 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; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot; for(m=1;count<n;m++){ tot = m; sum = 0; while(tot != 1){ tot = totient(tot); sum += tot; } if(sum == m) ptList[count++] = m; } return ptList; } long main(long argC, char* argV[]) { long *ptList,i,n; if(argC!=2) printf("Usage : %s <number of perfect Totient numbers required>",argV[0]); else{ n = atoi(argV[1]); ptList = perfectTotients(n); printf("The first %d perfect Totient numbers are : \n[",n); for(i=0;i<n;i++) printf(" %d,",ptList[i]); printf("\b]"); } return 0; }
Generate an equivalent C version of this Java code.
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Integer> perfectTotient(int n) { int test = 2; List<Integer> results = new ArrayList<Integer>(); for ( int i = 0 ; i < n ; test++ ) { int phiLoop = test; int sum = 0; do { phiLoop = phi[phiLoop]; sum += phiLoop; } while ( phiLoop > 1); if ( sum == test ) { i++; results.add(test); } } return results; } private static final int max = 100000; 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<stdlib.h> #include<stdio.h> long totient(long n){ long 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; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot; for(m=1;count<n;m++){ tot = m; sum = 0; while(tot != 1){ tot = totient(tot); sum += tot; } if(sum == m) ptList[count++] = m; } return ptList; } long main(long argC, char* argV[]) { long *ptList,i,n; if(argC!=2) printf("Usage : %s <number of perfect Totient numbers required>",argV[0]); else{ n = atoi(argV[1]); ptList = perfectTotients(n); printf("The first %d perfect Totient numbers are : \n[",n); for(i=0;i<n;i++) printf(" %d,",ptList[i]); printf("\b]"); } return 0; }
Produce a functionally identical C code for the snippet given in Java.
interface Thingable { String thing(); } class Delegator { public Thingable delegate; public String operation() { if (delegate == null) return "default implementation"; else return delegate.thing(); } } class Delegate implements Thingable { public String thing() { return "delegate implementation"; } } public class DelegateExample { public static void main(String[] args) { Delegator a = new Delegator(); assert a.operation().equals("default implementation"); Delegate d = new Delegate(); a.delegate = d; assert a.operation().equals("delegate implementation"); a.delegate = new Thingable() { public String thing() { return "anonymous delegate implementation"; } }; assert a.operation().equals("anonymous delegate implementation"); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef const char * (*Responder)( int p1); typedef struct sDelegate { Responder operation; } *Delegate; Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->operation = rspndr; return dl; } const char *DelegateThing(Delegate dl, int p1) { return (dl->operation)? (*dl->operation)(p1) : NULL; } typedef struct sDelegator { int param; char *phrase; Delegate delegate; } *Delegator; const char * defaultResponse( int p1) { return "default implementation"; } static struct sDelegate defaultDel = { &defaultResponse }; Delegator NewDelegator( int p, char *phrase) { Delegator d = malloc(sizeof(struct sDelegator)); d->param = p; d->phrase = phrase; d->delegate = &defaultDel; return d; } const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy) { const char *rtn; if (delroy) { rtn = DelegateThing(delroy, p1); if (!rtn) { rtn = DelegateThing(theDelegator->delegate, p1); } } else rtn = DelegateThing(theDelegator->delegate, p1); printf("%s\n", theDelegator->phrase ); return rtn; } const char *thing1( int p1) { printf("We're in thing1 with value %d\n" , p1); return "delegate implementation"; } int main() { Delegate del1 = NewDelegate(&thing1); Delegate del2 = NewDelegate(NULL); Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby."); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, NULL)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del1)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del2)); return 0; }
Translate this program into C but keep the logic exactly as in Java.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("Sum of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%4d", divisorSum(n)); if (n % 10 == 0) { System.out.println(); } } } }
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("Sum of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%4d", divisorSum(n)); if (n % 10 == 0) { System.out.println(); } } } }
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
Convert this Java block to C, preserving its control flow and logic.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("Sum of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%4d", divisorSum(n)); if (n % 10 == 0) { System.out.println(); } } } }
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AbbreviationsEasy { private static final Scanner input = new Scanner(System.in); private static final String COMMAND_TABLE = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" + " COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" + " NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" + " Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" + " MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" + " READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" + " RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; public static void main(String[] args) { String[] cmdTableArr = COMMAND_TABLE.split("\\s+"); Map<String, Integer> cmd_table = new HashMap<String, Integer>(); for (String word : cmdTableArr) { cmd_table.put(word, countCaps(word)); } System.out.print("Please enter your command to verify: "); String userInput = input.nextLine(); String[] user_input = userInput.split("\\s+"); for (String s : user_input) { boolean match = false; for (String cmd : cmd_table.keySet()) { if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) { String temp = cmd.toUpperCase(); if (temp.startsWith(s.toUpperCase())) { System.out.print(temp + " "); match = true; } } } if (!match) { System.out.print("*error* "); } } } private static int countCaps(String word) { int numCaps = 0; for (int i = 0; i < word.length(); i++) { if (Character.isUpperCase(word.charAt(i))) { numCaps++; } } return numCaps; } }
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Keep all operations the same but rewrite the snippet in C.
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AbbreviationsEasy { private static final Scanner input = new Scanner(System.in); private static final String COMMAND_TABLE = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" + " COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" + " NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" + " Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" + " MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" + " READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" + " RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; public static void main(String[] args) { String[] cmdTableArr = COMMAND_TABLE.split("\\s+"); Map<String, Integer> cmd_table = new HashMap<String, Integer>(); for (String word : cmdTableArr) { cmd_table.put(word, countCaps(word)); } System.out.print("Please enter your command to verify: "); String userInput = input.nextLine(); String[] user_input = userInput.split("\\s+"); for (String s : user_input) { boolean match = false; for (String cmd : cmd_table.keySet()) { if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) { String temp = cmd.toUpperCase(); if (temp.startsWith(s.toUpperCase())) { System.out.print(temp + " "); match = true; } } } if (!match) { System.out.print("*error* "); } } } private static int countCaps(String word) { int numCaps = 0; for (int i = 0; i < word.length(); i++) { if (Character.isUpperCase(word.charAt(i))) { numCaps++; } } return numCaps; } }
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Write a version of this Java function in C with identical behavior.
final int immutableInt = 4; int mutableInt = 4; mutableInt = 6; immutableInt = 6;
#define PI 3.14159265358979323 #define MINSIZE 10 #define MAXSIZE 100
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import java.awt.*; import java.awt.geom.Line2D; import java.util.*; import java.util.List; import javax.swing.*; public class SutherlandHodgman extends JFrame { SutherlandHodgmanPanel panel; public static void main(String[] args) { JFrame f = new SutherlandHodgman(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } public SutherlandHodgman() { Container content = getContentPane(); content.setLayout(new BorderLayout()); panel = new SutherlandHodgmanPanel(); content.add(panel, BorderLayout.CENTER); setTitle("SutherlandHodgman"); pack(); setLocationRelativeTo(null); } } class SutherlandHodgmanPanel extends JPanel { List<double[]> subject, clipper, result; public SutherlandHodgmanPanel() { setPreferredSize(new Dimension(600, 500)); double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}; double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}; subject = new ArrayList<>(Arrays.asList(subjPoints)); result = new ArrayList<>(subject); clipper = new ArrayList<>(Arrays.asList(clipPoints)); clipPolygon(); } private void clipPolygon() { int len = clipper.size(); for (int i = 0; i < len; i++) { int len2 = result.size(); List<double[]> input = result; result = new ArrayList<>(len2); double[] A = clipper.get((i + len - 1) % len); double[] B = clipper.get(i); for (int j = 0; j < len2; j++) { double[] P = input.get((j + len2 - 1) % len2); double[] Q = input.get(j); if (isInside(A, B, Q)) { if (!isInside(A, B, P)) result.add(intersection(A, B, P, Q)); result.add(Q); } else if (isInside(A, B, P)) result.add(intersection(A, B, P, Q)); } } } private boolean isInside(double[] a, double[] b, double[] c) { return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]); } private double[] intersection(double[] a, double[] b, double[] p, double[] q) { double A1 = b[1] - a[1]; double B1 = a[0] - b[0]; double C1 = A1 * a[0] + B1 * a[1]; double A2 = q[1] - p[1]; double B2 = p[0] - q[0]; double C2 = A2 * p[0] + B2 * p[1]; double det = A1 * B2 - A2 * B1; double x = (B2 * C1 - B1 * C2) / det; double y = (A1 * C2 - A2 * C1) / det; return new double[]{x, y}; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.translate(80, 60); g2.setStroke(new BasicStroke(3)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPolygon(g2, subject, Color.blue); drawPolygon(g2, clipper, Color.red); drawPolygon(g2, result, Color.green); } private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) { g2.setColor(color); int len = points.size(); Line2D line = new Line2D.Double(); for (int i = 0; i < len; i++) { double[] p1 = points.get(i); double[] p2 = points.get((i + 1) % len); line.setLine(p1[0], p1[1], p2[0], p2[1]); g2.draw(line); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double x, y; } vec_t, *vec; inline double dot(vec a, vec b) { return a->x * b->x + a->y * b->y; } inline double cross(vec a, vec b) { return a->x * b->y - a->y * b->x; } inline vec vsub(vec a, vec b, vec res) { res->x = a->x - b->x; res->y = a->y - b->y; return res; } int left_of(vec a, vec b, vec c) { vec_t tmp1, tmp2; double x; vsub(b, a, &tmp1); vsub(c, b, &tmp2); x = cross(&tmp1, &tmp2); return x < 0 ? -1 : x > 0; } int line_sect(vec x0, vec x1, vec y0, vec y1, vec res) { vec_t dx, dy, d; vsub(x1, x0, &dx); vsub(y1, y0, &dy); vsub(x0, y0, &d); double dyx = cross(&dy, &dx); if (!dyx) return 0; dyx = cross(&d, &dx) / dyx; if (dyx <= 0 || dyx >= 1) return 0; res->x = y0->x + dyx * dy.x; res->y = y0->y + dyx * dy.y; return 1; } typedef struct { int len, alloc; vec v; } poly_t, *poly; poly poly_new() { return (poly)calloc(1, sizeof(poly_t)); } void poly_free(poly p) { free(p->v); free(p); } void poly_append(poly p, vec v) { if (p->len >= p->alloc) { p->alloc *= 2; if (!p->alloc) p->alloc = 4; p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc); } p->v[p->len++] = *v; } int poly_winding(poly p) { return left_of(p->v, p->v + 1, p->v + 2); } void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res) { int i, side0, side1; vec_t tmp; vec v0 = sub->v + sub->len - 1, v1; res->len = 0; side0 = left_of(x0, x1, v0); if (side0 != -left) poly_append(res, v0); for (i = 0; i < sub->len; i++) { v1 = sub->v + i; side1 = left_of(x0, x1, v1); if (side0 + side1 == 0 && side0) if (line_sect(x0, x1, v0, v1, &tmp)) poly_append(res, &tmp); if (i == sub->len - 1) break; if (side1 != -left) poly_append(res, v1); v0 = v1; side0 = side1; } } poly poly_clip(poly sub, poly clip) { int i; poly p1 = poly_new(), p2 = poly_new(), tmp; int dir = poly_winding(clip); poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2); for (i = 0; i < clip->len - 1; i++) { tmp = p2; p2 = p1; p1 = tmp; if(p1->len == 0) { p2->len = 0; break; } poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2); } poly_free(p1); return p2; } int main() { int i; vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}}; vec_t s[] = { {50,150}, {200,50}, {350,150}, {350,300},{250,300},{200,250}, {150,350},{100,250},{100,200}}; #define clen (sizeof(c)/sizeof(vec_t)) #define slen (sizeof(s)/sizeof(vec_t)) poly_t clipper = {clen, 0, c}; poly_t subject = {slen, 0, s}; poly res = poly_clip(&subject, &clipper); for (i = 0; i < res->len; i++) printf("%g %g\n", res->v[i].x, res->v[i].y); FILE * eps = fopen("test.eps", "w"); fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n" "/l {lineto} def /m{moveto} def /s{setrgbcolor} def" "/c {closepath} def /gs {fill grestore stroke} def\n"); fprintf(eps, "0 setlinewidth %g %g m ", c[0].x, c[0].y); for (i = 1; i < clen; i++) fprintf(eps, "%g %g l ", c[i].x, c[i].y); fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n"); fprintf(eps, "%g %g m ", s[0].x, s[0].y); for (i = 1; i < slen; i++) fprintf(eps, "%g %g l ", s[i].x, s[i].y); fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n"); fprintf(eps, "2 setlinewidth [10 8] 0 setdash %g %g m ", res->v[0].x, res->v[0].y); for (i = 1; i < res->len; i++) fprintf(eps, "%g %g l ", res->v[i].x, res->v[i].y); fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n"); fprintf(eps, "%%%%EOF"); fclose(eps); printf("test.eps written\n"); return 0; }
Change the following Java code into C without altering its purpose.
import java.util.HashMap; import java.util.Map; import java.util.Objects; public class BaconCipher { private static final Map<Character, String> codes; static { codes = new HashMap<>(); codes.putAll(Map.of( 'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA", 'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB" )); codes.putAll(Map.of( 'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA", 'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB" )); codes.putAll(Map.of( 'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA", 'z', "BBAAB", ' ', "BBBAA" )); } private static String encode(String plainText, String message) { String pt = plainText.toLowerCase(); StringBuilder sb = new StringBuilder(); for (char c : pt.toCharArray()) { if ('a' <= c && c <= 'z') sb.append(codes.get(c)); else sb.append(codes.get(' ')); } String et = sb.toString(); String mg = message.toLowerCase(); sb.setLength(0); int count = 0; for (char c : mg.toCharArray()) { if ('a' <= c && c <= 'z') { if (et.charAt(count) == 'A') sb.append(c); else sb.append(((char) (c - 32))); count++; if (count == et.length()) break; } else sb.append(c); } return sb.toString(); } private static String decode(String message) { StringBuilder sb = new StringBuilder(); for (char c : message.toCharArray()) { if ('a' <= c && c <= 'z') sb.append('A'); if ('A' <= c && c <= 'Z') sb.append('B'); } String et = sb.toString(); sb.setLength(0); for (int i = 0; i < et.length(); i += 5) { String quintet = et.substring(i, i + 5); Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null); sb.append(key); } return sb.toString(); } public static void main(String[] args) { String plainText = "the quick brown fox jumps over the lazy dog"; String message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; String cipherText = encode(plainText, message); System.out.printf("Cipher text ->\n\n%s\n", cipherText); String decodedText = decode(cipherText); System.out.printf("\nHidden text ->\n\n%s\n", decodedText); } }
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import java.util.HashMap; import java.util.Map; import java.util.Objects; public class BaconCipher { private static final Map<Character, String> codes; static { codes = new HashMap<>(); codes.putAll(Map.of( 'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA", 'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB" )); codes.putAll(Map.of( 'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA", 'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB" )); codes.putAll(Map.of( 'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA", 'z', "BBAAB", ' ', "BBBAA" )); } private static String encode(String plainText, String message) { String pt = plainText.toLowerCase(); StringBuilder sb = new StringBuilder(); for (char c : pt.toCharArray()) { if ('a' <= c && c <= 'z') sb.append(codes.get(c)); else sb.append(codes.get(' ')); } String et = sb.toString(); String mg = message.toLowerCase(); sb.setLength(0); int count = 0; for (char c : mg.toCharArray()) { if ('a' <= c && c <= 'z') { if (et.charAt(count) == 'A') sb.append(c); else sb.append(((char) (c - 32))); count++; if (count == et.length()) break; } else sb.append(c); } return sb.toString(); } private static String decode(String message) { StringBuilder sb = new StringBuilder(); for (char c : message.toCharArray()) { if ('a' <= c && c <= 'z') sb.append('A'); if ('A' <= c && c <= 'Z') sb.append('B'); } String et = sb.toString(); sb.setLength(0); for (int i = 0; i < et.length(); i += 5) { String quintet = et.substring(i, i + 5); Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null); sb.append(key); } return sb.toString(); } public static void main(String[] args) { String plainText = "the quick brown fox jumps over the lazy dog"; String message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; String cipherText = encode(plainText, message); System.out.printf("Cipher text ->\n\n%s\n", cipherText); String decodedText = decode(cipherText); System.out.printf("\nHidden text ->\n\n%s\n", decodedText); } }
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
Keep all operations the same but rewrite the snippet in C.
public class Blah { public static void main(String[] args) { print2dArray(getSpiralArray(5)); } public static int[][] getSpiralArray(int dimension) { int[][] spiralArray = new int[dimension][dimension]; int numConcentricSquares = (int) Math.ceil((dimension) / 2.0); int j; int sideLen = dimension; int currNum = 0; for (int i = 0; i < numConcentricSquares; i++) { for (j = 0; j < sideLen; j++) { spiralArray[i][i + j] = currNum++; } for (j = 1; j < sideLen; j++) { spiralArray[i + j][dimension - 1 - i] = currNum++; } for (j = sideLen - 2; j > -1; j--) { spiralArray[dimension - 1 - i][i + j] = currNum++; } for (j = sideLen - 2; j > 0; j--) { spiralArray[i + j][i] = currNum++; } sideLen -= 2; } return spiralArray; } public static void print2dArray(int[][] array) { for (int[] row : array) { for (int elem : row) { System.out.printf("%3d", elem); } System.out.println(); } } }
#include <stdio.h> #include <stdlib.h> #define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j] int main(int c, char **v) { int i, j, m = 0, n = 0; if (c >= 2) m = atoi(v[1]); if (c >= 3) n = atoi(v[2]); if (m <= 0) m = 5; if (n <= 0) n = m; int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n); s[0] = (int*)(s + m); for (i = 1; i < m; i++) s[i] = s[i - 1] + n; int dx = 1, dy = 0, val = 0, t; for (i = j = 0; valid(i, j); i += dy, j += dx ) { for (; valid(i, j); j += dx, i += dy) s[i][j] = ++val; j -= dx; i -= dy; t = dy; dy = dx; dx = -t; } for (t = 2; val /= 10; t++); for(i = 0; i < m; i++) for(j = 0; j < n || !putchar('\n'); j++) printf("%*d", t, s[i][j]); return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
public class Blah { public static void main(String[] args) { print2dArray(getSpiralArray(5)); } public static int[][] getSpiralArray(int dimension) { int[][] spiralArray = new int[dimension][dimension]; int numConcentricSquares = (int) Math.ceil((dimension) / 2.0); int j; int sideLen = dimension; int currNum = 0; for (int i = 0; i < numConcentricSquares; i++) { for (j = 0; j < sideLen; j++) { spiralArray[i][i + j] = currNum++; } for (j = 1; j < sideLen; j++) { spiralArray[i + j][dimension - 1 - i] = currNum++; } for (j = sideLen - 2; j > -1; j--) { spiralArray[dimension - 1 - i][i + j] = currNum++; } for (j = sideLen - 2; j > 0; j--) { spiralArray[i + j][i] = currNum++; } sideLen -= 2; } return spiralArray; } public static void print2dArray(int[][] array) { for (int[] row : array) { for (int elem : row) { System.out.printf("%3d", elem); } System.out.println(); } } }
#include <stdio.h> #include <stdlib.h> #define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j] int main(int c, char **v) { int i, j, m = 0, n = 0; if (c >= 2) m = atoi(v[1]); if (c >= 3) n = atoi(v[2]); if (m <= 0) m = 5; if (n <= 0) n = m; int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n); s[0] = (int*)(s + m); for (i = 1; i < m; i++) s[i] = s[i - 1] + n; int dx = 1, dy = 0, val = 0, t; for (i = j = 0; valid(i, j); i += dy, j += dx ) { for (; valid(i, j); j += dx, i += dy) s[i][j] = ++val; j -= dx; i -= dy; t = dy; dy = dx; dx = -t; } for (t = 2; val /= 10; t++); for(i = 0; i < m; i++) for(j = 0; j < n || !putchar('\n'); j++) printf("%*d", t, s[i][j]); return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
module OptionalParameters { typedef Type<String >.Orderer as ColumnOrderer; typedef Type<String[]>.Orderer as RowOrderer; static String[][] sort(String[][] table, ColumnOrderer? orderer = Null, Int column = 0, Boolean reverse = False, ) { orderer ?:= (s1, s2) -> s1 <=> s2; ColumnOrderer byString = reverse ? ((s1, s2) -> orderer(s1, s2).reversed) : orderer; RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]); return table.sorted(byColumn); } void run() { String[][] table = [ ["c", "x", "i"], ["a", "y", "p"], ["b", "z", "a"], ]; show("original input", table); show("by default sort on column 0", sort(table)); show("by column 2", sort(table, column=2)); show("by column 2 reversed", sort(table, column=2, reverse=True)); } void show(String title, String[][] table) { @Inject Console console; console.print($"{title}:"); for (val row : table) { console.print($" {row}"); } console.print(); } }
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #include <string.h> typedef const char * String; typedef struct sTable { String * *rows; int n_rows,n_cols; } *Table; typedef int (*CompareFctn)(String a, String b); struct { CompareFctn compare; int column; int reversed; } sortSpec; int CmprRows( const void *aa, const void *bb) { String *rA = *(String *const *)aa; String *rB = *(String *const *)bb; int sortCol = sortSpec.column; String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol]; String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol]; return sortSpec.compare( left, right ); } int sortTable(Table tbl, const char* argSpec,... ) { va_list vl; const char *p; int c; sortSpec.compare = &strcmp; sortSpec.column = 0; sortSpec.reversed = 0; va_start(vl, argSpec); if (argSpec) for (p=argSpec; *p; p++) { switch (*p) { case 'o': sortSpec.compare = va_arg(vl,CompareFctn); break; case 'c': c = va_arg(vl,int); if ( 0<=c && c<tbl->n_cols) sortSpec.column = c; break; case 'r': sortSpec.reversed = (0!=va_arg(vl,int)); break; } } va_end(vl); qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows); return 0; } void printTable( Table tbl, FILE *fout, const char *colFmts[]) { int row, col; for (row=0; row<tbl->n_rows; row++) { fprintf(fout, " "); for(col=0; col<tbl->n_cols; col++) { fprintf(fout, colFmts[col], tbl->rows[row][col]); } fprintf(fout, "\n"); } fprintf(fout, "\n"); } int ord(char v) { return v-'0'; } int cmprStrgs(String s1, String s2) { const char *p1 = s1; const char *p2 = s2; const char *mrk1, *mrk2; while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++; } if (isdigit(*p1) && isdigit(*p2)) { long v1, v2; if ((*p1 == '0') ||(*p2 == '0')) { while (p1 > s1) { p1--; p2--; if (*p1 != '0') break; } if (!isdigit(*p1)) { p1++; p2++; } } mrk1 = p1; mrk2 = p2; v1 = 0; while(isdigit(*p1)) { v1 = 10*v1+ord(*p1); p1++; } v2 = 0; while(isdigit(*p2)) { v2 = 10*v2+ord(*p2); p2++; } if (v1 == v2) return(p2-mrk2)-(p1-mrk1); return v1 - v2; } if (tolower(*p1) != tolower(*p2)) return (tolower(*p1) - tolower(*p2)); for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++); return (*p1 -*p2); } int main() { const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"}; String r1[] = { "a101", "red", "Java" }; String r2[] = { "ab40", "gren", "Smalltalk" }; String r3[] = { "ab9", "blue", "Fortran" }; String r4[] = { "ab09", "ylow", "Python" }; String r5[] = { "ab1a", "blak", "Factor" }; String r6[] = { "ab1b", "brwn", "C Sharp" }; String r7[] = { "Ab1b", "pink", "Ruby" }; String r8[] = { "ab1", "orng", "Scheme" }; String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 }; struct sTable table; table.rows = rows; table.n_rows = 8; table.n_cols = 3; sortTable(&table, ""); printf("sort on col 0, ascending\n"); printTable(&table, stdout, colFmts); sortTable(&table, "ro", 1, &cmprStrgs); printf("sort on col 0, reverse.special\n"); printTable(&table, stdout, colFmts); sortTable(&table, "c", 1); printf("sort on col 1, ascending\n"); printTable(&table, stdout, colFmts); sortTable(&table, "cr", 2, 1); printf("sort on col 2, reverse\n"); printTable(&table, stdout, colFmts); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { static double p = 3; static BufferedImage I; static int px[], py[], color[], cells = 100, size = 1000; public Voronoi() { super("Voronoi Diagram"); setBounds(0, 0, size, size); setDefaultCloseOperation(EXIT_ON_CLOSE); int n = 0; Random rand = new Random(); I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); px = new int[cells]; py = new int[cells]; color = new int[cells]; for (int i = 0; i < cells; i++) { px[i] = rand.nextInt(size); py[i] = rand.nextInt(size); color[i] = rand.nextInt(16777215); } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { n = 0; for (byte i = 0; i < cells; i++) { if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) { n = i; } } I.setRGB(x, y, color[n]); } } Graphics2D g = I.createGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < cells; i++) { g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5)); } try { ImageIO.write(I, "png", new File("voronoi.png")); } catch (IOException e) { } } public void paint(Graphics g) { g.drawImage(I, 0, 0, this); } static double distance(int x1, int x2, int y1, int y2) { double d; d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); return d; } public static void main(String[] args) { new Voronoi().setVisible(true); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N_SITES 150 double site[N_SITES][2]; unsigned char rgb[N_SITES][3]; int size_x = 640, size_y = 480; inline double sq2(double x, double y) { return x * x + y * y; } #define for_k for (k = 0; k < N_SITES; k++) int nearest_site(double x, double y) { int k, ret = 0; double d, dist = 0; for_k { d = sq2(x - site[k][0], y - site[k][1]); if (!k || d < dist) { dist = d, ret = k; } } return ret; } int at_edge(int *color, int y, int x) { int i, j, c = color[y * size_x + x]; for (i = y - 1; i <= y + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = x - 1; j <= x + 1; j++) { if (j < 0 || j >= size_x) continue; if (color[i * size_x + j] != c) return 1; } } return 0; } #define AA_RES 4 void aa_color(unsigned char *pix, int y, int x) { int i, j, n; double r = 0, g = 0, b = 0, xx, yy; for (i = 0; i < AA_RES; i++) { yy = y + 1. / AA_RES * i + .5; for (j = 0; j < AA_RES; j++) { xx = x + 1. / AA_RES * j + .5; n = nearest_site(xx, yy); r += rgb[n][0]; g += rgb[n][1]; b += rgb[n][2]; } } pix[0] = r / (AA_RES * AA_RES); pix[1] = g / (AA_RES * AA_RES); pix[2] = b / (AA_RES * AA_RES); } #define for_i for (i = 0; i < size_y; i++) #define for_j for (j = 0; j < size_x; j++) void gen_map() { int i, j, k; int *nearest = malloc(sizeof(int) * size_y * size_x); unsigned char *ptr, *buf, color; ptr = buf = malloc(3 * size_x * size_y); for_i for_j nearest[i * size_x + j] = nearest_site(j, i); for_i for_j { if (!at_edge(nearest, i, j)) memcpy(ptr, rgb[nearest[i * size_x + j]], 3); else aa_color(ptr, i, j); ptr += 3; } for (k = 0; k < N_SITES; k++) { color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255; for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) { if (j < 0 || j >= size_x) continue; ptr = buf + 3 * (i * size_x + j); ptr[0] = ptr[1] = ptr[2] = color; } } } printf("P6\n%d %d\n255\n", size_x, size_y); fflush(stdout); fwrite(buf, size_y * size_x * 3, 1, stdout); } #define frand(x) (rand() / (1. + RAND_MAX) * x) int main() { int k; for_k { site[k][0] = frand(size_x); site[k][1] = frand(size_y); rgb [k][0] = frand(256); rgb [k][1] = frand(256); rgb [k][2] = frand(256); } gen_map(); return 0; }
Keep all operations the same but rewrite the snippet in C.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { static double p = 3; static BufferedImage I; static int px[], py[], color[], cells = 100, size = 1000; public Voronoi() { super("Voronoi Diagram"); setBounds(0, 0, size, size); setDefaultCloseOperation(EXIT_ON_CLOSE); int n = 0; Random rand = new Random(); I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); px = new int[cells]; py = new int[cells]; color = new int[cells]; for (int i = 0; i < cells; i++) { px[i] = rand.nextInt(size); py[i] = rand.nextInt(size); color[i] = rand.nextInt(16777215); } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { n = 0; for (byte i = 0; i < cells; i++) { if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) { n = i; } } I.setRGB(x, y, color[n]); } } Graphics2D g = I.createGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < cells; i++) { g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5)); } try { ImageIO.write(I, "png", new File("voronoi.png")); } catch (IOException e) { } } public void paint(Graphics g) { g.drawImage(I, 0, 0, this); } static double distance(int x1, int x2, int y1, int y2) { double d; d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); return d; } public static void main(String[] args) { new Voronoi().setVisible(true); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N_SITES 150 double site[N_SITES][2]; unsigned char rgb[N_SITES][3]; int size_x = 640, size_y = 480; inline double sq2(double x, double y) { return x * x + y * y; } #define for_k for (k = 0; k < N_SITES; k++) int nearest_site(double x, double y) { int k, ret = 0; double d, dist = 0; for_k { d = sq2(x - site[k][0], y - site[k][1]); if (!k || d < dist) { dist = d, ret = k; } } return ret; } int at_edge(int *color, int y, int x) { int i, j, c = color[y * size_x + x]; for (i = y - 1; i <= y + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = x - 1; j <= x + 1; j++) { if (j < 0 || j >= size_x) continue; if (color[i * size_x + j] != c) return 1; } } return 0; } #define AA_RES 4 void aa_color(unsigned char *pix, int y, int x) { int i, j, n; double r = 0, g = 0, b = 0, xx, yy; for (i = 0; i < AA_RES; i++) { yy = y + 1. / AA_RES * i + .5; for (j = 0; j < AA_RES; j++) { xx = x + 1. / AA_RES * j + .5; n = nearest_site(xx, yy); r += rgb[n][0]; g += rgb[n][1]; b += rgb[n][2]; } } pix[0] = r / (AA_RES * AA_RES); pix[1] = g / (AA_RES * AA_RES); pix[2] = b / (AA_RES * AA_RES); } #define for_i for (i = 0; i < size_y; i++) #define for_j for (j = 0; j < size_x; j++) void gen_map() { int i, j, k; int *nearest = malloc(sizeof(int) * size_y * size_x); unsigned char *ptr, *buf, color; ptr = buf = malloc(3 * size_x * size_y); for_i for_j nearest[i * size_x + j] = nearest_site(j, i); for_i for_j { if (!at_edge(nearest, i, j)) memcpy(ptr, rgb[nearest[i * size_x + j]], 3); else aa_color(ptr, i, j); ptr += 3; } for (k = 0; k < N_SITES; k++) { color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255; for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) { if (j < 0 || j >= size_x) continue; ptr = buf + 3 * (i * size_x + j); ptr[0] = ptr[1] = ptr[2] = color; } } } printf("P6\n%d %d\n255\n", size_x, size_y); fflush(stdout); fwrite(buf, size_y * size_x * 3, 1, stdout); } #define frand(x) (rand() / (1. + RAND_MAX) * x) int main() { int k; for_k { site[k][0] = frand(size_x); site[k][1] = frand(size_y); rgb [k][0] = frand(256); rgb [k][1] = frand(256); rgb [k][2] = frand(256); } gen_map(); return 0; }
Convert this Java block to C, preserving its control flow and logic.
public class JNIDemo { static { System.loadLibrary("JNIDemo"); } public static void main(String[] args) { System.out.println(callStrdup("Hello World!")); } private static native String callStrdup(String s); }
#include <stdio.h> void sayHello(char* name){ printf("Hello %s!\n", name); } int doubleNum(int num){ return num * 2; }
Please provide an equivalent version of this Java code in C.
import java.util.*; class SOfN<T> { private static final Random rand = new Random(); private List<T> sample; private int i = 0; private int n; public SOfN(int _n) { n = _n; sample = new ArrayList<T>(n); } public List<T> process(T item) { if (++i <= n) { sample.add(item); } else if (rand.nextInt(i) < n) { sample.set(rand.nextInt(n), item); } return sample; } } public class AlgorithmS { public static void main(String[] args) { int[] bin = new int[10]; for (int trial = 0; trial < 100000; trial++) { SOfN<Integer> s_of_n = new SOfN<Integer>(3); for (int i = 0; i < 9; i++) s_of_n.process(i); for (int s : s_of_n.process(9)) bin[s]++; } System.out.println(Arrays.toString(bin)); } }
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> struct s_env { unsigned int n, i; size_t size; void *sample; }; void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n) { s_env->i = 0; s_env->n = n; s_env->size = size; s_env->sample = malloc(n * size); } void sample_set_i(struct s_env *s_env, unsigned int i, void *item) { memcpy(s_env->sample + i * s_env->size, item, s_env->size); } void *s_of_n(struct s_env *s_env, void *item) { s_env->i++; if (s_env->i <= s_env->n) sample_set_i(s_env, s_env->i - 1, item); else if ((rand() % s_env->i) < s_env->n) sample_set_i(s_env, rand() % s_env->n, item); return s_env->sample; } int *test(unsigned int n, int *items_set, unsigned int num_items) { int i; struct s_env s_env; s_of_n_init(&s_env, sizeof(items_set[0]), n); for (i = 0; i < num_items; i++) { s_of_n(&s_env, (void *) &items_set[i]); } return (int *)s_env.sample; } int main() { unsigned int i, j; unsigned int n = 3; unsigned int num_items = 10; unsigned int *frequencies; int *items_set; srand(time(NULL)); items_set = malloc(num_items * sizeof(int)); frequencies = malloc(num_items * sizeof(int)); for (i = 0; i < num_items; i++) { items_set[i] = i; frequencies[i] = 0; } for (i = 0; i < 100000; i++) { int *res = test(n, items_set, num_items); for (j = 0; j < n; j++) { frequencies[res[j]]++; } free(res); } for (i = 0; i < num_items; i++) { printf(" %d", frequencies[i]); } puts(""); return 0; }
Generate an equivalent C version of this Java code.
import java.util.*; class SOfN<T> { private static final Random rand = new Random(); private List<T> sample; private int i = 0; private int n; public SOfN(int _n) { n = _n; sample = new ArrayList<T>(n); } public List<T> process(T item) { if (++i <= n) { sample.add(item); } else if (rand.nextInt(i) < n) { sample.set(rand.nextInt(n), item); } return sample; } } public class AlgorithmS { public static void main(String[] args) { int[] bin = new int[10]; for (int trial = 0; trial < 100000; trial++) { SOfN<Integer> s_of_n = new SOfN<Integer>(3); for (int i = 0; i < 9; i++) s_of_n.process(i); for (int s : s_of_n.process(9)) bin[s]++; } System.out.println(Arrays.toString(bin)); } }
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> struct s_env { unsigned int n, i; size_t size; void *sample; }; void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n) { s_env->i = 0; s_env->n = n; s_env->size = size; s_env->sample = malloc(n * size); } void sample_set_i(struct s_env *s_env, unsigned int i, void *item) { memcpy(s_env->sample + i * s_env->size, item, s_env->size); } void *s_of_n(struct s_env *s_env, void *item) { s_env->i++; if (s_env->i <= s_env->n) sample_set_i(s_env, s_env->i - 1, item); else if ((rand() % s_env->i) < s_env->n) sample_set_i(s_env, rand() % s_env->n, item); return s_env->sample; } int *test(unsigned int n, int *items_set, unsigned int num_items) { int i; struct s_env s_env; s_of_n_init(&s_env, sizeof(items_set[0]), n); for (i = 0; i < num_items; i++) { s_of_n(&s_env, (void *) &items_set[i]); } return (int *)s_env.sample; } int main() { unsigned int i, j; unsigned int n = 3; unsigned int num_items = 10; unsigned int *frequencies; int *items_set; srand(time(NULL)); items_set = malloc(num_items * sizeof(int)); frequencies = malloc(num_items * sizeof(int)); for (i = 0; i < num_items; i++) { items_set[i] = i; frequencies[i] = 0; } for (i = 0; i < 100000; i++) { int *res = test(n, items_set, num_items); for (j = 0; j < n; j++) { frequencies[res[j]]++; } free(res); } for (i = 0; i < num_items; i++) { printf(" %d", frequencies[i]); } puts(""); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream; public class FaulhabersTriangle { private static final MathContext MC = new MathContext(256); private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static class Frac implements Comparable<Frac> { private long num; private long denom; public static final Frac ZERO = new Frac(0, 1); public Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero"); long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.abs(gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } public Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom); } public Frac unaryMinus() { return new Frac(-num, denom); } public Frac minus(Frac rhs) { return this.plus(rhs.unaryMinus()); } public Frac times(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom); } @Override public int compareTo(Frac o) { double diff = toDouble() - o.toDouble(); return Double.compare(diff, 0.0); } @Override public boolean equals(Object obj) { return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0; } @Override public String toString() { if (denom == 1) { return Long.toString(num); } return String.format("%d/%d", num, denom); } public double toDouble() { return (double) num / denom; } public BigDecimal toBigDecimal() { return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC); } } private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero"); Frac[] a = new Frac[n + 1]; Arrays.fill(a, Frac.ZERO); for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; --j) { a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1)); } } if (n != 1) return a[0]; return a[0].unaryMinus(); } private static long binomial(int n, int k) { if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException(); if (n == 0 || k == 0) return 1; long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b); long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i); return num / den; } private static Frac[] faulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; Arrays.fill(coeffs, Frac.ZERO); Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; ++j) { sign *= -1; coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j)); } return coeffs; } public static void main(String[] args) { for (int i = 0; i <= 9; ++i) { Frac[] coeffs = faulhaberTriangle(i); for (Frac coeff : coeffs) { System.out.printf("%5s ", coeff); } System.out.println(); } System.out.println(); int k = 17; Frac[] cc = faulhaberTriangle(k); int n = 1000; BigDecimal nn = BigDecimal.valueOf(n); BigDecimal np = BigDecimal.ONE; BigDecimal sum = BigDecimal.ZERO; for (Frac c : cc) { np = np.multiply(nn); sum = sum.add(np.multiply(c.toBigDecimal())); } System.out.println(sum.toBigInteger()); } }
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int binomial(int n, int k) { int num, denom, i; if (n < 0 || k < 0 || n < k) return -1; if (n == 0 || k == 0) return 1; num = 1; for (i = k + 1; i <= n; ++i) { num = num * i; } denom = 1; for (i = 2; i <= n - k; ++i) { denom *= i; } return num / denom; } int gcd(int a, int b) { int temp; while (b != 0) { temp = a % b; a = b; b = temp; } return a; } typedef struct tFrac { int num, denom; } Frac; Frac makeFrac(int n, int d) { Frac result; int g; if (d == 0) { result.num = 0; result.denom = 0; return result; } if (n == 0) { d = 1; } else if (d < 0) { n = -n; d = -d; } g = abs(gcd(n, d)); if (g > 1) { n = n / g; d = d / g; } result.num = n; result.denom = d; return result; } Frac negateFrac(Frac f) { return makeFrac(-f.num, f.denom); } Frac subFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom); } Frac multFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom); } bool equalFrac(Frac lhs, Frac rhs) { return (lhs.num == rhs.num) && (lhs.denom == rhs.denom); } bool lessFrac(Frac lhs, Frac rhs) { return (lhs.num * rhs.denom) < (rhs.num * lhs.denom); } void printFrac(Frac f) { char buffer[7]; int len; if (f.denom != 1) { snprintf(buffer, 7, "%d/%d", f.num, f.denom); } else { snprintf(buffer, 7, "%d", f.num); } len = 7 - strlen(buffer); while (len-- > 0) { putc(' ', stdout); } printf(buffer); } Frac bernoulli(int n) { Frac a[16]; int j, m; if (n < 0) { a[0].num = 0; a[0].denom = 0; return a[0]; } for (m = 0; m <= n; ++m) { a[m] = makeFrac(1, m + 1); for (j = m; j >= 1; --j) { a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1)); } } if (n != 1) { return a[0]; } return negateFrac(a[0]); } void faulhaber(int p) { Frac q, *coeffs; int j, sign; coeffs = malloc(sizeof(Frac)*(p + 1)); q = makeFrac(1, p + 1); sign = -1; for (j = 0; j <= p; ++j) { sign = -1 * sign; coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)); } for (j = 0; j <= p; ++j) { printFrac(coeffs[j]); } printf("\n"); free(coeffs); } int main() { int i; for (i = 0; i < 10; ++i) { faulhaber(i); } return 0; }
Translate the given Java code snippet into C without altering its behavior.
public class Arguments { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments given."); for(int i = 0; i < args.length; i++) System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); } }
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
Translate the given Java code snippet into C without altering its behavior.
public class Arguments { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments given."); for(int i = 0; i < args.length; i++) System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); } }
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
Maintain the same structure and functionality when rewriting this code in C.
public class Arguments { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments given."); for(int i = 0; i < args.length; i++) System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); } }
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
Convert this Java snippet to C and keep its semantics consistent.
String[] fruits = ["apples", "oranges"]; String[] grains = ["wheat", "corn"]; String[] all = fruits + grains;
#include <stdlib.h> #include <stdio.h> #include <string.h> #define ARRAY_CONCAT(TYPE, A, An, B, Bn) \ (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE)); void *array_concat(const void *a, size_t an, const void *b, size_t bn, size_t s) { char *p = malloc(s * (an + bn)); memcpy(p, a, an*s); memcpy(p + an*s, b, bn*s); return p; } const int a[] = { 1, 2, 3, 4, 5 }; const int b[] = { 6, 7, 8, 9, 0 }; int main(void) { unsigned int i; int *c = ARRAY_CONCAT(int, a, 5, b, 5); for(i = 0; i < 10; i++) printf("%d\n", c[i]); free(c); return EXIT_SUCCCESS; }
Translate the given Java code snippet into C without altering its behavior.
import java.util.Scanner; public class GetInput { public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); System.out.print("Enter a string: "); String str = s.nextLine(); System.out.print("Enter an integer: "); int i = Integer.parseInt(s.next()); } }
#include <stdio.h> #include <stdlib.h> int main(void) { char str[BUFSIZ]; puts("Enter a string: "); fgets(str, sizeof(str), stdin); long num; char buf[BUFSIZ]; do { puts("Enter 75000: "); fgets(buf, sizeof(buf), stdin); num = strtol(buf, NULL, 10); } while (num != 75000); return EXIT_SUCCESS; }
Port the provided Java code into C while preserving the original functionality.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
#include<stdio.h> #include<conio.h> #include<math.h> #include<dos.h> typedef struct{ char str[3]; int key; }note; note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}}; int main(void) { int i=0; while(!kbhit()) { printf("\t%s",sequence[i].str); sound(261.63*pow(2,sequence[i].key/12.0)); delay(sequence[i].key%12==0?500:1000); i = (i+1)%8; i==0?printf("\n"):printf(""); } nosound(); return 0; }
Translate this program into C but keep the logic exactly as in Java.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
#include<stdio.h> #include<conio.h> #include<math.h> #include<dos.h> typedef struct{ char str[3]; int key; }note; note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}}; int main(void) { int i=0; while(!kbhit()) { printf("\t%s",sequence[i].str); sound(261.63*pow(2,sequence[i].key/12.0)); delay(sequence[i].key%12==0?500:1000); i = (i+1)%8; i==0?printf("\n"):printf(""); } nosound(); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
package hu.pj.alg.test; import hu.pj.alg.ZeroOneKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class ZeroOneKnapsackForTourists { public ZeroOneKnapsackForTourists() { ZeroOneKnapsack zok = new ZeroOneKnapsack(400); zok.add("map", 9, 150); zok.add("compass", 13, 35); zok.add("water", 153, 200); zok.add("sandwich", 50, 160); zok.add("glucose", 15, 60); zok.add("tin", 68, 45); zok.add("banana", 27, 60); zok.add("apple", 39, 40); zok.add("cheese", 23, 30); zok.add("beer", 52, 10); zok.add("suntan cream", 11, 70); zok.add("camera", 32, 30); zok.add("t-shirt", 24, 15); zok.add("trousers", 48, 10); zok.add("umbrella", 73, 40); zok.add("waterproof trousers", 42, 70); zok.add("waterproof overclothes", 43, 75); zok.add("note-case", 22, 80); zok.add("sunglasses", 7, 20); zok.add("towel", 18, 12); zok.add("socks", 4, 50); zok.add("book", 30, 10); List<Item> itemList = zok.calcSolution(); if (zok.isCalculated()) { NumberFormat nf = NumberFormat.getInstance(); System.out.println( "Maximal weight = " + nf.format(zok.getMaxWeight() / 100.0) + " kg" ); System.out.println( "Total weight of solution = " + nf.format(zok.getSolutionWeight() / 100.0) + " kg" ); System.out.println( "Total value = " + zok.getProfit() ); System.out.println(); System.out.println( "You can carry the following materials " + "in the knapsack:" ); for (Item item : itemList) { if (item.getInKnapsack() == 1) { System.out.format( "%1$-23s %2$-3s %3$-5s %4$-15s \n", item.getName(), item.getWeight(), "dag ", "(value = " + item.getValue() + ")" ); } } } else { System.out.println( "The problem is not solved. " + "Maybe you gave wrong data." ); } } public static void main(String[] args) { new ZeroOneKnapsackForTourists(); } }
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; int weight; int value; } item_t; item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, }; int *knapsack (item_t *items, int n, int w) { int i, j, a, b, *mm, **m, *s; mm = calloc((n + 1) * (w + 1), sizeof (int)); m = malloc((n + 1) * sizeof (int *)); m[0] = mm; for (i = 1; i <= n; i++) { m[i] = &mm[i * (w + 1)]; for (j = 0; j <= w; j++) { if (items[i - 1].weight > j) { m[i][j] = m[i - 1][j]; } else { a = m[i - 1][j]; b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value; m[i][j] = a > b ? a : b; } } } s = calloc(n, sizeof (int)); for (i = n, j = w; i > 0; i--) { if (m[i][j] > m[i - 1][j]) { s[i - 1] = 1; j -= items[i - 1].weight; } } free(mm); free(m); return s; } int main () { int i, n, tw = 0, tv = 0, *s; n = sizeof (items) / sizeof (item_t); s = knapsack(items, n, 400); for (i = 0; i < n; i++) { if (s[i]) { printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value); tw += items[i].weight; tv += items[i].value; } } printf("%-22s %5d %5d\n", "totals:", tw, tv); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
package hu.pj.alg.test; import hu.pj.alg.ZeroOneKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class ZeroOneKnapsackForTourists { public ZeroOneKnapsackForTourists() { ZeroOneKnapsack zok = new ZeroOneKnapsack(400); zok.add("map", 9, 150); zok.add("compass", 13, 35); zok.add("water", 153, 200); zok.add("sandwich", 50, 160); zok.add("glucose", 15, 60); zok.add("tin", 68, 45); zok.add("banana", 27, 60); zok.add("apple", 39, 40); zok.add("cheese", 23, 30); zok.add("beer", 52, 10); zok.add("suntan cream", 11, 70); zok.add("camera", 32, 30); zok.add("t-shirt", 24, 15); zok.add("trousers", 48, 10); zok.add("umbrella", 73, 40); zok.add("waterproof trousers", 42, 70); zok.add("waterproof overclothes", 43, 75); zok.add("note-case", 22, 80); zok.add("sunglasses", 7, 20); zok.add("towel", 18, 12); zok.add("socks", 4, 50); zok.add("book", 30, 10); List<Item> itemList = zok.calcSolution(); if (zok.isCalculated()) { NumberFormat nf = NumberFormat.getInstance(); System.out.println( "Maximal weight = " + nf.format(zok.getMaxWeight() / 100.0) + " kg" ); System.out.println( "Total weight of solution = " + nf.format(zok.getSolutionWeight() / 100.0) + " kg" ); System.out.println( "Total value = " + zok.getProfit() ); System.out.println(); System.out.println( "You can carry the following materials " + "in the knapsack:" ); for (Item item : itemList) { if (item.getInKnapsack() == 1) { System.out.format( "%1$-23s %2$-3s %3$-5s %4$-15s \n", item.getName(), item.getWeight(), "dag ", "(value = " + item.getValue() + ")" ); } } } else { System.out.println( "The problem is not solved. " + "Maybe you gave wrong data." ); } } public static void main(String[] args) { new ZeroOneKnapsackForTourists(); } }
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; int weight; int value; } item_t; item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, }; int *knapsack (item_t *items, int n, int w) { int i, j, a, b, *mm, **m, *s; mm = calloc((n + 1) * (w + 1), sizeof (int)); m = malloc((n + 1) * sizeof (int *)); m[0] = mm; for (i = 1; i <= n; i++) { m[i] = &mm[i * (w + 1)]; for (j = 0; j <= w; j++) { if (items[i - 1].weight > j) { m[i][j] = m[i - 1][j]; } else { a = m[i - 1][j]; b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value; m[i][j] = a > b ? a : b; } } } s = calloc(n, sizeof (int)); for (i = n, j = w; i > 0; i--) { if (m[i][j] > m[i - 1][j]) { s[i - 1] = 1; j -= items[i - 1].weight; } } free(mm); free(m); return s; } int main () { int i, n, tw = 0, tv = 0, *s; n = sizeof (items) / sizeof (item_t); s = knapsack(items, n, 400); for (i = 0; i < n; i++) { if (s[i]) { printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value); tw += items[i].weight; tv += items[i].value; } } printf("%-22s %5d %5d\n", "totals:", tw, tv); return 0; }
Write a version of this Java function in C with identical behavior.
import java.io.*; import java.util.*; public class PrimeDescendants { public static void main(String[] args) { try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) { printPrimeDesc(writer, 100); } catch (IOException ex) { ex.printStackTrace(); } } private static void printPrimeDesc(Writer writer, int limit) throws IOException { List<Long> primes = findPrimes(limit); List<Long> ancestor = new ArrayList<>(limit); List<List<Long>> descendants = new ArrayList<>(limit); for (int i = 0; i < limit; ++i) { ancestor.add(Long.valueOf(0)); descendants.add(new ArrayList<Long>()); } for (Long prime : primes) { int p = prime.intValue(); descendants.get(p).add(prime); for (int i = 0; i + p < limit; ++i) { int s = i + p; for (Long n : descendants.get(i)) { Long prod = n * p; descendants.get(s).add(prod); if (prod < limit) ancestor.set(prod.intValue(), Long.valueOf(s)); } } } int totalDescendants = 0; for (int i = 1; i < limit; ++i) { List<Long> ancestors = getAncestors(ancestor, i); writer.write("[" + i + "] Level: " + ancestors.size() + "\n"); writer.write("Ancestors: "); Collections.sort(ancestors); print(writer, ancestors); writer.write("Descendants: "); List<Long> desc = descendants.get(i); if (!desc.isEmpty()) { Collections.sort(desc); if (desc.get(0) == i) desc.remove(0); } writer.write(desc.size() + "\n"); totalDescendants += desc.size(); if (!desc.isEmpty()) print(writer, desc); writer.write("\n"); } writer.write("Total descendants: " + totalDescendants + "\n"); } private static List<Long> findPrimes(int limit) { boolean[] isprime = new boolean[limit]; Arrays.fill(isprime, true); isprime[0] = isprime[1] = false; for (int p = 2; p * p < limit; ++p) { if (isprime[p]) { for (int i = p * p; i < limit; i += p) isprime[i] = false; } } List<Long> primes = new ArrayList<>(); for (int p = 2; p < limit; ++p) { if (isprime[p]) primes.add(Long.valueOf(p)); } return primes; } private static List<Long> getAncestors(List<Long> ancestor, int n) { List<Long> result = new ArrayList<>(); for (Long a = ancestor.get(n); a != 0 && a != n; ) { n = a.intValue(); a = ancestor.get(n); result.add(Long.valueOf(n)); } return result; } private static void print(Writer writer, List<Long> list) throws IOException { if (list.isEmpty()) { writer.write("none\n"); return; } int i = 0; writer.write(String.valueOf(list.get(i++))); for (; i != list.size(); ++i) writer.write(", " + list.get(i)); writer.write("\n"); } }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXPRIME 99 #define MAXPARENT 99 #define NBRPRIMES 30 #define NBRANCESTORS 10 FILE *FileOut; char format[] = ", %lld"; int Primes[NBRPRIMES]; int iPrimes; short Ancestors[NBRANCESTORS]; struct Children { long long Child; struct Children *pNext; }; struct Children *Parents[MAXPARENT+1][2]; int CptDescendants[MAXPARENT+1]; long long MaxDescendant = (long long) pow(3.0, 33.0); short GetParent(long long child); struct Children *AppendChild(struct Children *node, long long child); short GetAncestors(short child); void PrintDescendants(struct Children *node); int GetPrimes(int primes[], int maxPrime); int main() { long long Child; short i, Parent, Level; int TotDesc = 0; if ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0) return 1; for (Child = 1; Child <= MaxDescendant; Child++) { if (Parent = GetParent(Child)) { Parents[Parent][1] = AppendChild(Parents[Parent][1], Child); if (Parents[Parent][0] == NULL) Parents[Parent][0] = Parents[Parent][1]; CptDescendants[Parent]++; } } if (MAXPARENT > MAXPRIME) if (GetPrimes(Primes, MAXPARENT) < 0) return 1; if (fopen_s(&FileOut, "Ancestors.txt", "w")) return 1; for (Parent = 1; Parent <= MAXPARENT; Parent++) { Level = GetAncestors(Parent); fprintf(FileOut, "[%d] Level: %d\n", Parent, Level); if (Level) { fprintf(FileOut, "Ancestors: %d", Ancestors[0]); for (i = 1; i < Level; i++) fprintf(FileOut, ", %d", Ancestors[i]); } else fprintf(FileOut, "Ancestors: None"); if (CptDescendants[Parent]) { fprintf(FileOut, "\nDescendants: %d\n", CptDescendants[Parent]); strcpy_s(format, "%lld"); PrintDescendants(Parents[Parent][0]); fprintf(FileOut, "\n"); } else fprintf(FileOut, "\nDescendants: None\n"); fprintf(FileOut, "\n"); TotDesc += CptDescendants[Parent]; } fprintf(FileOut, "Total descendants %d\n\n", TotDesc); if (fclose(FileOut)) return 1; return 0; } short GetParent(long long child) { long long Child = child; short Parent = 0; short Index = 0; while (Child > 1 && Parent <= MAXPARENT) { if (Index > iPrimes) return 0; while (Child % Primes[Index] == 0) { Child /= Primes[Index]; Parent += Primes[Index]; } Index++; } if (Parent == child || Parent > MAXPARENT || child == 1) return 0; return Parent; } struct Children *AppendChild(struct Children *node, long long child) { static struct Children *NodeNew; if (NodeNew = (struct Children *) malloc(sizeof(struct Children))) { NodeNew->Child = child; NodeNew->pNext = NULL; if (node != NULL) node->pNext = NodeNew; } return NodeNew; } short GetAncestors(short child) { short Child = child; short Parent = 0; short Index = 0; while (Child > 1) { while (Child % Primes[Index] == 0) { Child /= Primes[Index]; Parent += Primes[Index]; } Index++; } if (Parent == child || child == 1) return 0; Index = GetAncestors(Parent); Ancestors[Index] = Parent; return ++Index; } void PrintDescendants(struct Children *node) { static struct Children *NodeCurr; static struct Children *NodePrev; NodeCurr = node; NodePrev = NULL; while (NodeCurr) { fprintf(FileOut, format, NodeCurr->Child); strcpy_s(format, ", %lld"); NodePrev = NodeCurr; NodeCurr = NodeCurr->pNext; free(NodePrev); } return; } int GetPrimes(int primes[], int maxPrime) { if (maxPrime < 2) return -1; int Index = 0, Value = 1; int Max, i; primes[0] = 2; while ((Value += 2) <= maxPrime) { Max = (int) floor(sqrt((double) Value)); for (i = 0; i <= Index; i++) { if (primes[i] > Max) { if (++Index >= NBRPRIMES) return -1; primes[Index] = Value; break; } if (Value % primes[i] == 0) break; } } return Index; }
Port the following code from Java to C with equivalent syntax and logic.
import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.of; import static java.util.stream.Collectors.toList; import java.util.List; public class CartesianProduct { public List<?> product(List<?>... a) { if (a.length >= 2) { List<?> product = a[0]; for (int i = 1; i < a.length; i++) { product = product(product, a[i]); } return product; } return emptyList(); } private <A, B> List<?> product(List<A> a, List<B> b) { return of(a.stream() .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList())) .flatMap(List::stream) .collect(toList())).orElse(emptyList()); } }
#include<string.h> #include<stdlib.h> #include<stdio.h> void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf("("); for(i=0;i<times;i++){ printf("%d,",currentSet[i]); } printf("\b),"); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf("\nNumber of sets : %d",numSets); for(i=0;i<numSets+1;i++){ printf("\nSet %d : ",i+1); for(j=0;j<setLengths[i];j++){ printf(" %d ",sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf("\n%s",str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,"x"); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf("\n{}"); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,"x"); } printf("\n{"); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf("\b}"); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]); else processInputString(argV[1]); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.of; import static java.util.stream.Collectors.toList; import java.util.List; public class CartesianProduct { public List<?> product(List<?>... a) { if (a.length >= 2) { List<?> product = a[0]; for (int i = 1; i < a.length; i++) { product = product(product, a[i]); } return product; } return emptyList(); } private <A, B> List<?> product(List<A> a, List<B> b) { return of(a.stream() .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList())) .flatMap(List::stream) .collect(toList())).orElse(emptyList()); } }
#include<string.h> #include<stdlib.h> #include<stdio.h> void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf("("); for(i=0;i<times;i++){ printf("%d,",currentSet[i]); } printf("\b),"); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf("\nNumber of sets : %d",numSets); for(i=0;i<numSets+1;i++){ printf("\nSet %d : ",i+1); for(j=0;j<setLengths[i];j++){ printf(" %d ",sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf("\n%s",str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,"x"); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf("\n{}"); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,"x"); } printf("\n{"); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf("\b}"); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]); else processInputString(argV[1]); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.util.ArrayList; public class FirstClass{ public interface Function<A,B>{ B apply(A x); } public static <A,B,C> Function<A, C> compose( final Function<B, C> f, final Function<A, B> g) { return new Function<A, C>() { @Override public C apply(A x) { return f.apply(g.apply(x)); } }; } public static void main(String[] args){ ArrayList<Function<Double, Double>> functions = new ArrayList<Function<Double,Double>>(); functions.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.cos(x); } }); functions.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.tan(x); } }); functions.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return x * x; } }); ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>(); inverse.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.acos(x); } }); inverse.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.atan(x); } }); inverse.add( new Function<Double, Double>(){ @Override public Double apply(Double x){ return Math.sqrt(x); } }); System.out.println("Compositions:"); for(int i = 0; i < functions.size(); i++){ System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5)); } System.out.println("Hard-coded compositions:"); System.out.println(Math.cos(Math.acos(0.5))); System.out.println(Math.tan(Math.atan(0.5))); System.out.println(Math.pow(Math.sqrt(0.5), 2)); } }
#include <stdlib.h> #include <stdio.h> #include <math.h> typedef double (*Class2Func)(double); double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); } double Function1( Class2Func f2, double val ) { return f2(val); } Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; } Class2Func funcListA[] = {&functionA, &sin, &cos, &tan }; Class2Func funcListB[] = {&functionB, &asin, &acos, &atan }; double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); } typedef struct sComposition { Class2Func f1; Class2Func f2; } *Composition; Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; } double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); } int main(int argc, char *argv[]) { int ix; Composition c; printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0)); for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9)); } return 0; }
Keep all operations the same but rewrite the snippet in C.
import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Proper{ public static List<Integer> properDivs(int n){ List<Integer> divs = new LinkedList<Integer>(); if(n == 1) return divs; divs.add(1); for(int x = 2; x < n; x++){ if(n % x == 0) divs.add(x); } Collections.sort(divs); return divs; } public static void main(String[] args){ for(int x = 1; x <= 10; x++){ System.out.println(x + ": " + properDivs(x)); } int x = 0, count = 0; for(int n = 1; n <= 20000; n++){ if(properDivs(n).size() > count){ x = n; count = properDivs(n).size(); } } System.out.println(x + ": " + count); } }
#include <stdio.h> #include <stdbool.h> int proper_divisors(const int n, bool print_flag) { int count = 0; for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } } if (print_flag) printf("\n"); return count; } int main(void) { for (int i = 1; i <= 10; ++i) { printf("%d: ", i); proper_divisors(i, true); } int max = 0; int max_i = 1; for (int i = 1; i <= 20000; ++i) { int v = proper_divisors(i, false); if (v >= max) { max = v; max_i = i; } } printf("%d with %d divisors\n", max_i, max); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.io.StringWriter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class XmlCreation { private static final String[] names = {"April", "Tam O'Shanter", "Emily"}; private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"}; public static void main(String[] args) { try { final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); final Element root = doc.createElement("CharacterRemarks"); doc.appendChild(root); for(int i = 0; i < names.length; i++) { final Element character = doc.createElement("Character"); root.appendChild(character); character.setAttribute("name", names[i]); character.appendChild(doc.createTextNode(remarks[i])); } final Source source = new DOMSource(doc); final StringWriter buffer = new StringWriter(); final Result result = new StreamResult(buffer); final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent", "yes"); transformer.transform(source, result); System.out.println(buffer.toString()); } catch (Exception e) { e.printStackTrace(); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libxml/parser.h> #include <libxml/tree.h> const char *names[] = { "April", "Tam O'Shanter", "Emily", NULL }; const char *remarks[] = { "Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift", NULL }; int main() { xmlDoc *doc = NULL; xmlNode *root = NULL, *node; const char **next; int a; doc = xmlNewDoc("1.0"); root = xmlNewNode(NULL, "CharacterRemarks"); xmlDocSetRootElement(doc, root); for(next = names, a = 0; *next != NULL; next++, a++) { node = xmlNewNode(NULL, "Character"); (void)xmlNewProp(node, "name", *next); xmlAddChild(node, xmlNewText(remarks[a])); xmlAddChild(root, node); } xmlElemDump(stdout, doc, root); xmlFreeDoc(doc); xmlCleanupParser(); return EXIT_SUCCESS; }
Produce a functionally identical C code for the snippet given in Java.
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; import javax.swing.JFrame; public class Plot2d extends JApplet { double[] xi; double[] yi; public Plot2d(double[] x, double[] y) { this.xi = x; this.yi = y; } public static double max(double[] t) { double maximum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] > maximum) { maximum = t[i]; } } return maximum; } public static double min(double[] t) { double minimum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] < minimum) { minimum = t[i]; } } return minimum; } public void init() { setBackground(Color.white); setForeground(Color.white); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.black); int x0 = 70; int y0 = 10; int xm = 670; int ym = 410; int xspan = xm - x0; int yspan = ym - y0; double xmax = max(xi); double xmin = min(xi); double ymax = max(yi); double ymin = min(yi); g2.draw(new Line2D.Double(x0, ym, xm, ym)); g2.draw(new Line2D.Double(x0, ym, x0, y0)); for (int j = 0; j < 5; j++) { int interv = 4; g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20); g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)), ym - j * yspan / interv + y0 - 5); g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5)); g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0)); } for (int i = 0; i < xi.length; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); g2.drawString("o", x0 + f - 3, h + 14); } for (int i = 0; i < xi.length - 1; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin)); g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0)); } } public static void main(String args[]) { JFrame f = new JFrame("ShapesDemo2D"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09}; JApplet applet = new Plot2d(r, t); f.getContentPane().add("Center", applet); applet.init(); f.pack(); f.setSize(new Dimension(720, 480)); f.show(); } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <plot.h> #define NP 10 double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, int n) { int i; *minx = *maxx = x[0]; *miny = *maxy = y[0]; for(i=1; i < n; i++) { if ( x[i] < *minx ) *minx = x[i]; if ( x[i] > *maxx ) *maxx = x[i]; if ( y[i] < *miny ) *miny = y[i]; if ( y[i] > *maxy ) *maxy = y[i]; } } #define YLAB_HEIGHT_F 0.1 #define XLAB_WIDTH_F 0.2 #define XDIV (NP*1.0) #define YDIV (NP*1.0) #define EXTRA_W 0.01 #define EXTRA_H 0.01 #define DOTSCALE (1.0/150.0) #define MAXLABLEN 32 #define PUSHSCALE(X,Y) pl_fscale((X),(Y)) #define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y)) #define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy) int main() { int plotter, i; double minx, miny, maxx, maxy; double lx, ly; double xticstep, yticstep, nx, ny; double sx, sy; char labs[MAXLABLEN+1]; plotter = pl_newpl("png", NULL, stdout, NULL); if ( plotter < 0 ) exit(1); pl_selectpl(plotter); if ( pl_openpl() < 0 ) exit(1); minmax(x, y, &minx, &maxx, &miny, &maxy, NP); lx = maxx - minx; ly = maxy - miny; pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly, ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly); xticstep = (ceil(maxx) - floor(minx)) / XDIV; yticstep = (ceil(maxy) - floor(miny)) / YDIV; pl_flinewidth(0.25); if ( lx < ly ) { sx = lx/ly; sy = 1.0; } else { sx = 1.0; sy = ly/lx; } pl_erase(); pl_fbox(floor(minx), floor(miny), ceil(maxx), ceil(maxy)); pl_fontname("HersheySerif"); for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) { pl_fline(floor(minx), ny, ceil(maxx), ny); snprintf(labs, MAXLABLEN, "%6.2lf", ny); FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny); PUSHSCALE(sx,sy); pl_label(labs); POPSCALE(sx,sy); } for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) { pl_fline(nx, floor(miny), nx, ceil(maxy)); snprintf(labs, MAXLABLEN, "%6.2lf", nx); FMOVESCALE(nx, floor(miny)); PUSHSCALE(sx,sy); pl_ftextangle(-90); pl_alabel('l', 'b', labs); POPSCALE(sx,sy); } pl_fillcolorname("red"); pl_filltype(1); for(i=0; i < NP; i++) { pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE, x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE); } pl_flushpl(); pl_closepl(); }
Port the following code from Java to C with equivalent syntax and logic.
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; import javax.swing.JFrame; public class Plot2d extends JApplet { double[] xi; double[] yi; public Plot2d(double[] x, double[] y) { this.xi = x; this.yi = y; } public static double max(double[] t) { double maximum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] > maximum) { maximum = t[i]; } } return maximum; } public static double min(double[] t) { double minimum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] < minimum) { minimum = t[i]; } } return minimum; } public void init() { setBackground(Color.white); setForeground(Color.white); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.black); int x0 = 70; int y0 = 10; int xm = 670; int ym = 410; int xspan = xm - x0; int yspan = ym - y0; double xmax = max(xi); double xmin = min(xi); double ymax = max(yi); double ymin = min(yi); g2.draw(new Line2D.Double(x0, ym, xm, ym)); g2.draw(new Line2D.Double(x0, ym, x0, y0)); for (int j = 0; j < 5; j++) { int interv = 4; g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20); g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)), ym - j * yspan / interv + y0 - 5); g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5)); g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0)); } for (int i = 0; i < xi.length; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); g2.drawString("o", x0 + f - 3, h + 14); } for (int i = 0; i < xi.length - 1; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin)); g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0)); } } public static void main(String args[]) { JFrame f = new JFrame("ShapesDemo2D"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09}; JApplet applet = new Plot2d(r, t); f.getContentPane().add("Center", applet); applet.init(); f.pack(); f.setSize(new Dimension(720, 480)); f.show(); } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <plot.h> #define NP 10 double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, int n) { int i; *minx = *maxx = x[0]; *miny = *maxy = y[0]; for(i=1; i < n; i++) { if ( x[i] < *minx ) *minx = x[i]; if ( x[i] > *maxx ) *maxx = x[i]; if ( y[i] < *miny ) *miny = y[i]; if ( y[i] > *maxy ) *maxy = y[i]; } } #define YLAB_HEIGHT_F 0.1 #define XLAB_WIDTH_F 0.2 #define XDIV (NP*1.0) #define YDIV (NP*1.0) #define EXTRA_W 0.01 #define EXTRA_H 0.01 #define DOTSCALE (1.0/150.0) #define MAXLABLEN 32 #define PUSHSCALE(X,Y) pl_fscale((X),(Y)) #define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y)) #define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy) int main() { int plotter, i; double minx, miny, maxx, maxy; double lx, ly; double xticstep, yticstep, nx, ny; double sx, sy; char labs[MAXLABLEN+1]; plotter = pl_newpl("png", NULL, stdout, NULL); if ( plotter < 0 ) exit(1); pl_selectpl(plotter); if ( pl_openpl() < 0 ) exit(1); minmax(x, y, &minx, &maxx, &miny, &maxy, NP); lx = maxx - minx; ly = maxy - miny; pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly, ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly); xticstep = (ceil(maxx) - floor(minx)) / XDIV; yticstep = (ceil(maxy) - floor(miny)) / YDIV; pl_flinewidth(0.25); if ( lx < ly ) { sx = lx/ly; sy = 1.0; } else { sx = 1.0; sy = ly/lx; } pl_erase(); pl_fbox(floor(minx), floor(miny), ceil(maxx), ceil(maxy)); pl_fontname("HersheySerif"); for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) { pl_fline(floor(minx), ny, ceil(maxx), ny); snprintf(labs, MAXLABLEN, "%6.2lf", ny); FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny); PUSHSCALE(sx,sy); pl_label(labs); POPSCALE(sx,sy); } for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) { pl_fline(nx, floor(miny), nx, ceil(maxy)); snprintf(labs, MAXLABLEN, "%6.2lf", nx); FMOVESCALE(nx, floor(miny)); PUSHSCALE(sx,sy); pl_ftextangle(-90); pl_alabel('l', 'b', labs); POPSCALE(sx,sy); } pl_fillcolorname("red"); pl_filltype(1); for(i=0; i < NP; i++) { pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE, x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE); } pl_flushpl(); pl_closepl(); }
Write the same code in C as shown below in Java.
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.JApplet; import javax.swing.JFrame; public class Plot2d extends JApplet { double[] xi; double[] yi; public Plot2d(double[] x, double[] y) { this.xi = x; this.yi = y; } public static double max(double[] t) { double maximum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] > maximum) { maximum = t[i]; } } return maximum; } public static double min(double[] t) { double minimum = t[0]; for (int i = 1; i < t.length; i++) { if (t[i] < minimum) { minimum = t[i]; } } return minimum; } public void init() { setBackground(Color.white); setForeground(Color.white); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.black); int x0 = 70; int y0 = 10; int xm = 670; int ym = 410; int xspan = xm - x0; int yspan = ym - y0; double xmax = max(xi); double xmin = min(xi); double ymax = max(yi); double ymin = min(yi); g2.draw(new Line2D.Double(x0, ym, xm, ym)); g2.draw(new Line2D.Double(x0, ym, x0, y0)); for (int j = 0; j < 5; j++) { int interv = 4; g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20); g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)), ym - j * yspan / interv + y0 - 5); g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5)); g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0)); } for (int i = 0; i < xi.length; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); g2.drawString("o", x0 + f - 3, h + 14); } for (int i = 0; i < xi.length - 1; i++) { int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin)); int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin)); int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin)); int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin)); g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0)); } } public static void main(String args[]) { JFrame f = new JFrame("ShapesDemo2D"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09}; JApplet applet = new Plot2d(r, t); f.getContentPane().add("Center", applet); applet.init(); f.pack(); f.setSize(new Dimension(720, 480)); f.show(); } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <plot.h> #define NP 10 double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, int n) { int i; *minx = *maxx = x[0]; *miny = *maxy = y[0]; for(i=1; i < n; i++) { if ( x[i] < *minx ) *minx = x[i]; if ( x[i] > *maxx ) *maxx = x[i]; if ( y[i] < *miny ) *miny = y[i]; if ( y[i] > *maxy ) *maxy = y[i]; } } #define YLAB_HEIGHT_F 0.1 #define XLAB_WIDTH_F 0.2 #define XDIV (NP*1.0) #define YDIV (NP*1.0) #define EXTRA_W 0.01 #define EXTRA_H 0.01 #define DOTSCALE (1.0/150.0) #define MAXLABLEN 32 #define PUSHSCALE(X,Y) pl_fscale((X),(Y)) #define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y)) #define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy) int main() { int plotter, i; double minx, miny, maxx, maxy; double lx, ly; double xticstep, yticstep, nx, ny; double sx, sy; char labs[MAXLABLEN+1]; plotter = pl_newpl("png", NULL, stdout, NULL); if ( plotter < 0 ) exit(1); pl_selectpl(plotter); if ( pl_openpl() < 0 ) exit(1); minmax(x, y, &minx, &maxx, &miny, &maxy, NP); lx = maxx - minx; ly = maxy - miny; pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly, ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly); xticstep = (ceil(maxx) - floor(minx)) / XDIV; yticstep = (ceil(maxy) - floor(miny)) / YDIV; pl_flinewidth(0.25); if ( lx < ly ) { sx = lx/ly; sy = 1.0; } else { sx = 1.0; sy = ly/lx; } pl_erase(); pl_fbox(floor(minx), floor(miny), ceil(maxx), ceil(maxy)); pl_fontname("HersheySerif"); for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) { pl_fline(floor(minx), ny, ceil(maxx), ny); snprintf(labs, MAXLABLEN, "%6.2lf", ny); FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny); PUSHSCALE(sx,sy); pl_label(labs); POPSCALE(sx,sy); } for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) { pl_fline(nx, floor(miny), nx, ceil(maxy)); snprintf(labs, MAXLABLEN, "%6.2lf", nx); FMOVESCALE(nx, floor(miny)); PUSHSCALE(sx,sy); pl_ftextangle(-90); pl_alabel('l', 'b', labs); POPSCALE(sx,sy); } pl_fillcolorname("red"); pl_filltype(1); for(i=0; i < NP; i++) { pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE, x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE); } pl_flushpl(); pl_closepl(); }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
String str = "I am a string"; if (str.matches(".*string")) { System.out.println("ends with 'string'"); }
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <regex.h> #include <string.h> int main() { regex_t preg; regmatch_t substmatch[1]; const char *tp = "string$"; const char *t1 = "this is a matching string"; const char *t2 = "this is not a matching string!"; const char *ss = "istyfied"; regcomp(&preg, "string$", REG_EXTENDED); printf("'%s' %smatched with '%s'\n", t1, (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp); printf("'%s' %smatched with '%s'\n", t2, (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp); regfree(&preg); regcomp(&preg, "a[a-z]+", REG_EXTENDED); if ( regexec(&preg, t1, 1, substmatch, 0) == 0 ) { char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) + (strlen(t1) - substmatch[0].rm_eo) + 2); memcpy(ns, t1, substmatch[0].rm_so+1); memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss)); memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo], strlen(&t1[substmatch[0].rm_eo])); ns[ substmatch[0].rm_so + strlen(ss) + strlen(&t1[substmatch[0].rm_eo]) ] = 0; printf("mod string: '%s'\n", ns); free(ns); } else { printf("the string '%s' is the same: no matching!\n", t1); } regfree(&preg); return 0; }
Please provide an equivalent version of this Java code in C.
import java.util.AbstractList; import java.util.Collections; import java.util.Scanner; public class GuessNumber { public static final int LOWER = 0, UPPER = 100; public static void main(String[] args) { System.out.printf("Instructions:\n" + "Think of integer number from %d (inclusive) to %d (exclusive) and\n" + "I will guess it. After each guess, you respond with L, H, or C depending\n" + "on if my guess was too low, too high, or correct.\n", LOWER, UPPER); int result = Collections.binarySearch(new AbstractList<Integer>() { private final Scanner in = new Scanner(System.in); public int size() { return UPPER - LOWER; } public Integer get(int i) { System.out.printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i); String s = in.nextLine(); assert s.length() > 0; switch (Character.toLowerCase(s.charAt(0))) { case 'l': return -1; case 'h': return 1; case 'c': return 0; } return -1; } }, 0); if (result < 0) System.out.println("That is impossible."); else System.out.printf("Your number is %d.\n", result); } }
#include <stdio.h> int main(){ int bounds[ 2 ] = {1, 100}; char input[ 2 ] = " "; int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); do{ switch( input[ 0 ] ){ case 'H': bounds[ 1 ] = choice; break; case 'L': bounds[ 0 ] = choice; break; case 'Y': printf( "\nAwwwright\n" ); return 0; } choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Is the number %d? (Y/H/L) ", choice ); }while( scanf( "%1s", input ) == 1 ); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.util.HashMap; public static void main(String[] args){ String[] keys= {"a", "b", "c"}; int[] vals= {1, 2, 3}; HashMap<String, Integer> hash= new HashMap<String, Integer>(); for(int i= 0; i < keys.length; i++){ hash.put(keys[i], vals[i]); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KeyType const char * #define ValType int #define HASH_SIZE 4096 unsigned strhashkey( const char * key, int max) { unsigned h=0; unsigned hl, hr; while(*key) { h += *key; hl= 0x5C5 ^ (h&0xfff00000 )>>18; hr =(h&0x000fffff ); h = hl ^ hr ^ *key++; } return h % max; } typedef struct sHme { KeyType key; ValType value; struct sHme *link; } *MapEntry; typedef struct he { MapEntry first, last; } HashElement; HashElement hash[HASH_SIZE]; typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc); typedef void (*ValCopyF)(ValType *vdest, ValType vsrc); typedef unsigned (*KeyHashF)( KeyType key, int upperBound ); typedef int (*KeyCmprF)(KeyType key1, KeyType key2); void HashAddH( KeyType key, ValType value, KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { (*copyVal)(&m_ent->value, value); } else { MapEntry last; MapEntry hme = malloc(sizeof(struct sHme)); (*copyKey)(&hme->key, key); (*copyVal)(&hme->value, value); hme->link = NULL; last = hash[hix].last; if (last) { last->link = hme; } else hash[hix].first = hme; hash[hix].last = hme; } } int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { *val = m_ent->value; } return (m_ent != NULL); } void copyStr(const char**dest, const char *src) { *dest = strdup(src); } void copyInt( int *dest, int src) { *dest = src; } int strCompare( const char *key1, const char *key2) { return strcmp(key1, key2) == 0; } void HashAdd( KeyType key, ValType value ) { HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare); } int HashGet(ValType *val, KeyType key) { return HashGetH( val, key, &strhashkey, &strCompare); } int main() { static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" }; static int valuList[] = {1,43,640, 747, 42, 42}; int ix; for (ix=0; ix<6; ix++) { HashAdd(keyList[ix], valuList[ix]); } return 0; }