Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Generate an equivalent Java version of this C code.
#include <gtk/gtk.h> void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg; gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]); msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "You wrote '%s' and selected the number %d%s", c, (gint)v, (v==75000) ? "" : " which is wrong (75000 expected)!"); gtk_widget_show_all(GTK_WIDGET(msg)); (void)gtk_dialog_run(GTK_DIALOG(msg)); gtk_widget_destroy(GTK_WIDGET(msg)); if ( v==75000 ) gtk_main_quit(); } int main(int argc, char **argv) { GtkWindow *win; GtkEntry *entry; GtkSpinButton *spin; GtkButton *okbutton; GtkLabel *entry_l, *spin_l; GtkHBox *hbox[2]; GtkVBox *vbox; GtkWidget *widgs[2]; gtk_init(&argc, &argv); win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, "Insert values"); entry_l = (GtkLabel *)gtk_label_new("Insert a string"); spin_l = (GtkLabel *)gtk_label_new("Insert 75000"); entry = (GtkEntry *)gtk_entry_new(); spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1); widgs[0] = GTK_WIDGET(entry); widgs[1] = GTK_WIDGET(spin); okbutton = (GtkButton *)gtk_button_new_with_label("Ok"); hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1); vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin)); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
import javax.swing.*; public class GetInputSwing { public static void main(String[] args) throws Exception { int number = Integer.parseInt( JOptionPane.showInputDialog ("Enter an Integer")); String string = JOptionPane.showInputDialog ("Enter a String"); } }
Port the provided C code into Java while preserving the original functionality.
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct cursor_tag { double x; double y; int angle; } cursor_t; void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; } void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, "L%g,%g\n", cursor->x, cursor->y); } void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } } void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, "<svg xmlns='http: size, size); fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n"); fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='"); fprintf(out, "M%g,%g\n", cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, "'/>\n</svg>\n"); } int main(int argc, char** argv) { const char* filename = "sierpinski_arrowhead.svg"; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, "w"); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
final PVector t = new PVector(20, 30, 60); void setup() { size(450, 400); noLoop(); background(0, 0, 200); stroke(-1); sc(7, 400, -60, t); } PVector sc(int o, float l, final int a, final PVector s) { if (o > 0) { sc(--o, l *= .5, -a, s).z += a; sc(o, l, a, s).z += a; sc(o, l, -a, s); } else line(s.x, s.y, s.x += cos(radians(s.z)) * l, s.y += sin(radians(s.z)) * l); return s; }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> #include <stdlib.h> #include <string.h> static int badHrs, maxBadHrs; static double hrsTot = 0.0; static int rdgsTot = 0; char bhEndDate[40]; int mungeLine( char *line, int lno, FILE *fout ) { char date[40], *tkn; int dHrs, flag, hrs2, hrs; double hrsSum; int hrsCnt = 0; double avg; tkn = strtok(line, "."); if (tkn) { int n = sscanf(tkn, "%s %d", &date, &hrs2); if (n<2) { printf("badly formated line - %d %s\n", lno, tkn); return 0; } hrsSum = 0.0; while( tkn= strtok(NULL, ".")) { n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs); if (n>=2) { if (flag > 0) { hrsSum += 1.0*hrs2 + .001*dHrs; hrsCnt += 1; if (maxBadHrs < badHrs) { maxBadHrs = badHrs; strcpy(bhEndDate, date); } badHrs = 0; } else { badHrs += 1; } hrs2 = hrs; } else { printf("bad file syntax line %d: %s\n",lno, tkn); } } avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0; fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n", date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt); hrsTot += hrsSum; rdgsTot += hrsCnt; } return 1; } int main() { FILE *infile, *outfile; int lineNo = 0; char line[512]; const char *ifilename = "readings.txt"; outfile = fopen("V0.txt", "w"); infile = fopen(ifilename, "rb"); if (!infile) { printf("Can't open %s\n", ifilename); exit(1); } while (NULL != fgets(line, 512, infile)) { lineNo += 1; if (0 == mungeLine(line, lineNo, outfile)) printf("Bad line at %d",lineNo); } fclose(infile); fprintf(outfile, "File: %s\n", ifilename); fprintf(outfile, "Total:  %.3f\n", hrsTot); fprintf(outfile, "Readings: %d\n", rdgsTot); fprintf(outfile, "Average:  %.3f\n", hrsTot/rdgsTot); fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs); fprintf(outfile, "Ends on date %s\n", bhEndDate); fclose(outfile); return 0; }
import java.io.File; import java.util.*; import static java.lang.System.out; public class TextProcessing1 { public static void main(String[] args) throws Exception { Locale.setDefault(new Locale("en", "US")); Metrics metrics = new Metrics(); int dataGap = 0; String gapBeginDate = null; try (Scanner lines = new Scanner(new File("readings.txt"))) { while (lines.hasNextLine()) { double lineTotal = 0.0; int linePairs = 0; int lineInvalid = 0; String lineDate; try (Scanner line = new Scanner(lines.nextLine())) { lineDate = line.next(); while (line.hasNext()) { final double value = line.nextDouble(); if (line.nextInt() <= 0) { if (dataGap == 0) gapBeginDate = lineDate; dataGap++; lineInvalid++; continue; } lineTotal += value; linePairs++; metrics.addDataGap(dataGap, gapBeginDate, lineDate); dataGap = 0; } } metrics.addLine(lineTotal, linePairs); metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal); } metrics.report(); } } private static class Metrics { private List<String[]> gapDates; private int maxDataGap = -1; private double total; private int pairs; private int lineResultCount; void addLine(double tot, double prs) { total += tot; pairs += prs; } void addDataGap(int gap, String begin, String end) { if (gap > 0 && gap >= maxDataGap) { if (gap > maxDataGap) { maxDataGap = gap; gapDates = new ArrayList<>(); } gapDates.add(new String[]{begin, end}); } } void lineResult(String date, int invalid, int prs, double tot) { if (lineResultCount >= 3) return; out.printf("%10s out: %2d in: %2d tot: %10.3f avg: %10.3f%n", date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0); lineResultCount++; } void report() { out.printf("%ntotal = %10.3f%n", total); out.printf("readings = %6d%n", pairs); out.printf("average = %010.3f%n", total / pairs); out.printf("%nmaximum run(s) of %d invalid measurements: %n", maxDataGap); for (String[] dates : gapDates) out.printf("begins at %s and ends at %s%n", dates[0], dates[1]); } } }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> const char *string = "The quick brown fox jumped over the lazy dog's back"; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", result[i]); printf("\n"); return EXIT_SUCCESS; }
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digester { public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); } static String hexDigest(String str, String digestName) { try { MessageDigest md = MessageDigest.getInstance(digestName); byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8)); char[] hex = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4); hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f); } return new String(hex); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
Translate the given C code snippet into Java without altering its behavior.
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
Translate the given C code snippet into Java without altering its behavior.
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
Convert this C snippet to Java and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST"; strptime(d, "%B %d %Y %I:%M%p %Z", &ts); t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); return EXIT_SUCCESS; }
import java.time.*; import java.time.format.*; class Main { public static void main(String args[]) { String dateStr = "March 7 2009 7:30pm EST"; DateTimeFormatter df = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("MMMM d yyyy h:mma zzz") .toFormatter(); ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12); System.out.println("Date: " + dateStr); System.out.println("+12h: " + after12Hours.format(df)); ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET")); System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df)); } }
Translate this program into Java but keep the logic exactly as in C.
>>>>>,----------[++++++++ ++[->+>+<<]>+>[-<<+>>]+++ +++++[-<------>]>>+>,---- ------<<+[->>>>>+<<<<<]>> ]>>>[<<<<[<<<[->>+<<[->+> [-]<<]]>[-<+>]>[-<<<.>>>> ->>>>>[>>>>>]<-<<<<[<<<<< ]+<]<<<<]>>>>>[>>>>>]<]
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await(); Thread.sleep(num * 1000); System.out.println(num); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { int[] nums = new int[args.length]; for (int i = 0; i < args.length; i++) nums[i] = Integer.parseInt(args[i]); sleepSortAndPrint(nums); } }
Keep all operations the same but rewrite the snippet in Java.
#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int a[10][10], i, j; srand(time(NULL)); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) a[i][j] = rand() % 20 + 1; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf(" %d", a[i][j]); if (a[i][j] == 20) goto Done; } printf("\n"); } Done: printf("\n"); return 0; }
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Please provide an equivalent version of this C code in Java.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Convert this C snippet to Java and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
Please provide an equivalent version of this C code in Java.
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
Please provide an equivalent version of this C code in Java.
#include <stdio.h> #include <stdlib.h> #define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ stk_##name stk_##name##_create(size_t init_size) { \ stk_##name s; if (!init_size) init_size = 4; \ s = malloc(sizeof(struct stk_##name##_t)); \ if (!s) return 0; \ s->buf = malloc(sizeof(type) * init_size); \ if (!s->buf) { free(s); return 0; } \ s->len = 0, s->alloc = init_size; \ return s; } \ int stk_##name##_push(stk_##name s, type item) { \ type *tmp; \ if (s->len >= s->alloc) { \ tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ if (!tmp) return -1; s->buf = tmp; \ s->alloc *= 2; } \ s->buf[s->len++] = item; \ return s->len; } \ type stk_##name##_pop(stk_##name s) { \ type tmp; \ if (!s->len) abort(); \ tmp = s->buf[--s->len]; \ if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ s->alloc /= 2; \ s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ return tmp; } \ void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) #define stk_size(s) ((s)->len) DECL_STACK_TYPE(int, int) int main(void) { int i; stk_int stk = stk_int_create(0); printf("pushing: "); for (i = 'a'; i <= 'z'; i++) { printf(" %c", i); stk_int_push(stk, i); } printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); printf("\npoppoing:"); while (stk_size(stk)) printf(" %c", stk_int_pop(stk)); printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); stk_int_delete(stk); return 0; }
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
Keep all operations the same but rewrite the snippet in Java.
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
public class TotientFunction { public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max)); } } private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; } private static final int max = 10000000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
Port the following code from C to Java with equivalent syntax and logic.
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
public class TotientFunction { public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max)); } } private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; } private static final int max = 10000000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
Convert this C block to Java, preserving its control flow and logic.
int a = 3; if (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } unless (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } switch (a) { case 2: puts ("a is 2"); break; case 3: puts ("a is 3"); break; case 4: puts ("a is 4"); break; default: puts("is neither"); }
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
Maintain the same structure and functionality when rewriting this code in Java.
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); else gmp_printf(" %Zd", val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf("\nhalt: %Zd has no divisors\n", val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); return 0; }
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Fractran{ public static void main(String []args){ new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); } final int limit = 15; Vector<Integer> num = new Vector<>(); Vector<Integer> den = new Vector<>(); public Fractran(String prog, Integer val){ compile(prog); dump(); exec(2); } void compile(String prog){ Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); Matcher matcher = regexp.matcher(prog); while(matcher.find()){ num.add(Integer.parseInt(matcher.group(1))); den.add(Integer.parseInt(matcher.group(2))); matcher = regexp.matcher(matcher.group(3)); } } void exec(Integer val){ int n = 0; while(val != null && n<limit){ System.out.println(n+": "+val); val = step(val); n++; } } Integer step(int val){ int i=0; while(i<den.size() && val%den.get(i) != 0) i++; if(i<den.size()) return num.get(i)*val/den.get(i); return null; } void dump(){ for(int i=0; i<den.size(); i++) System.out.print(num.get(i)+"/"+den.get(i)+" "); System.out.println(); } }
Produce a functionally identical Java code for the snippet given in C.
#include <stdio.h> #define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } int main(int argc, char *argv[]) { int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; int i, n; n = sizeof(nums)/sizeof(int); StoogeSort(nums, 0, n-1); for(i = 0; i <= n-1; i++) printf("%5d", nums[i]); return 0; }
import java.util.Arrays; public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); } public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1); } public static void stoogeSort(int[] L, int i, int j) { if (L[j] < L[i]) { int tmp = L[i]; L[i] = L[j]; L[j] = tmp; } if (j - i > 1) { int t = (j - i + 1) / 3; stoogeSort(L, i, j - t); stoogeSort(L, i + t, j); stoogeSort(L, i, j - t); } } }
Keep all operations the same but rewrite the snippet in Java.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b; #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts("\033[H"), i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++, putchar(' ')) printf(B(i, j) == '*' ? C(i - 1, j) ? "\033[32m%c\033[m" : "\033[31m%c\033[m" : "%c", B(i, j)); } void init() { int i, j; puts("\033[H\033[J"); b = malloc(w * h); memset(b, ' ', w * h); x = malloc(sizeof(int) * BALLS * 2); y = x + BALLS; for (i = 0; i < n; i++) for (j = -i; j <= i; j += 2) B(2 * i+2, j + w/2) = '*'; srand(time(0)); } void move(int idx) { int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0; if (yy < 0) return; if (yy == h - 1) { y[idx] = -1; return; } switch(c = B(yy + 1, xx)) { case ' ': yy++; break; case '*': sl = 1; default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1)) if (!rnd(sl++)) o = 1; if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1)) if (!rnd(sl++)) o = -1; if (!o) kill = 1; xx += o; } c = V(idx); V(idx) = ' '; idx[y] = yy, idx[x] = xx; B(yy, xx) = c; if (kill) idx[y] = -1; } int run(void) { static int step = 0; int i; for (i = 0; i < cnt; i++) move(i); if (2 == ++step && cnt < BALLS) { step = 0; x[cnt] = w/2; y[cnt] = 0; if (V(cnt) != ' ') return 0; V(cnt) = rnd(80) + 43; cnt++; } return 1; } int main(int c, char **v) { if (c < 2 || (n = atoi(v[1])) <= 3) n = 5; if (n >= 20) n = 20; w = n * 2 + 1; init(); do { show_board(), usleep(60000); } while (run()); return 0; }
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; private final Random m_random = new Random(); public GaltonBox( final int pinRows, final int ballCount ) { m_pinRows = pinRows; m_startRow = pinRows + 1; m_balls = new Position[ ballCount ]; for ( int ball = 0; ball < ballCount; ball++ ) m_balls[ ball ] = new Position( m_startRow, 0, 'o' ); } private static class Position { int m_row; int m_col; char m_char; Position( final int row, final int col, final char ch ) { m_row = row; m_col = col; m_char = ch; } } public void run() { for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) { ballsInPlay = dropBalls(); print(); } } private int dropBalls() { int ballsInPlay = 0; int ballToStart = -1; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == m_startRow ) ballToStart = ball; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( ball == ballToStart ) { m_balls[ ball ].m_row = m_pinRows; ballsInPlay++; } else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) { m_balls[ ball ].m_row -= 1; m_balls[ ball ].m_col += m_random.nextInt( 2 ); if ( 0 != m_balls[ ball ].m_row ) ballsInPlay++; } return ballsInPlay; } private void print() { for ( int row = m_startRow; row --> 1; ) { for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == row ) printBall( m_balls[ ball ] ); System.out.println(); printPins( row ); } printCollectors(); System.out.println(); } private static void printBall( final Position pos ) { for ( int col = pos.m_row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = 0; col < pos.m_col; col++ ) System.out.print( " " ); System.out.print( pos.m_char ); } private void printPins( final int row ) { for ( int col = row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = m_startRow - row; col --> 0; ) System.out.print( ". " ); System.out.println(); } private void printCollectors() { final List<List<Position>> collectors = new ArrayList<List<Position>>(); for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = new ArrayList<Position>(); collectors.add( collector ); for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col ) collector.add( m_balls[ ball ] ); } for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) { for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = collectors.get( col ); final int pos = row + collector.size() - rows; System.out.print( '|' ); if ( pos >= 0 ) System.out.print( collector.get( pos ).m_char ); else System.out.print( ' ' ); } System.out.println( '|' ); } } private static final int longest( final List<List<Position>> collectors ) { int result = 0; for ( final List<Position> collector : collectors ) result = Math.max( collector.size(), result ); return result; } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf("%d ", x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); } int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x)); return 0; }
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toString(arr)); } while (circleSortR(arr, 0, arr.length - 1, 0) != 0); } private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps; int high = hi; int low = lo; int mid = (hi - lo) / 2; while (lo < hi) { if (arr[lo] > arr[hi]) { swap(arr, lo, hi); numSwaps++; } lo++; hi--; } if (lo == hi && arr[lo] > arr[hi + 1]) { swap(arr, lo, hi + 1); numSwaps++; } numSwaps = circleSortR(arr, low, low + mid, numSwaps); numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps); return numSwaps; } private static void swap(int[] arr, int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } }
Translate this program into Java but keep the logic exactly as in C.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = fopen(inputFile,"r"); int i,j,k,l; unsigned long prod; int** matrix; cell *coreList,*tempList,*resultList; fscanf(fp,"%d%d",&ROW,&COL); matrix = (int**)malloc(ROW*sizeof(int*)); for(i=0;i<ROW;i++){ matrix[i] = (int*)malloc(COL*sizeof(int)); for(j=0;j<COL;j++){ fscanf(fp,"%d",&matrix[i][j]); if(matrix[i][j]==1) SUM++; } } coreList = (cell*)malloc(SUM*sizeof(cell)); resultList = (cell*)malloc(SUM*sizeof(cell)); k = 0; for(i=0;i<ROW;i++){ for(j=0;j<COL;j++){ if(matrix[i][j]==1){ coreList[k].row = i+1; coreList[k].col = j+1; resultList[k].row = i+1; resultList[k].col = j+1; k++; } } } prod = k; for(i=2;i<=power;i++){ tempList = (cell*)malloc(prod*k*sizeof(cell)); l = 0; for(j=0;j<prod;j++){ for(k=0;k<SUM;k++){ tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row; tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col; l++; } } free(resultList); prod *= k; resultList = (cell*)malloc(prod*sizeof(cell)); for(j=0;j<prod;j++){ resultList[j].row = tempList[j].row; resultList[j].col = tempList[j].col; } free(tempList); } return resultList; } int main(){ char fileName[100]; int power,i,length; cell* resultList; printf("Enter input file name : "); scanf("%s",fileName); printf("Enter power : "); scanf("%d",&power); resultList = kroneckerProduct(fileName,power); initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal"); length = raiseTo(SUM,power); for(i=0;i<length;i++){ putpixel(resultList[i].row,resultList[i].col,15); } getch(); closegraph(); return 0; }
package kronecker; public class ProductFractals { public static int[][] product(final int[][] a, final int[][] b) { final int[][] c = new int[a.length*b.length][]; for (int ix = 0; ix < c.length; ix++) { final int num_cols = a[0].length*b[0].length; c[ix] = new int[num_cols]; } for (int ia = 0; ia < a.length; ia++) { for (int ja = 0; ja < a[ia].length; ja++) { for (int ib = 0; ib < b.length; ib++) { for (int jb = 0; jb < b[ib].length; jb++) { c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb]; } } } } return c; } public static void show_matrix(final int[][] m, final char nz, final char z) { for (int im = 0; im < m.length; im++) { for (int jm = 0; jm < m[im].length; jm++) { System.out.print(m[im][jm] == 0 ? z : nz); } System.out.println(); } } public static int[][] power(final int[][] m, final int n) { int[][] m_pow = m; for (int ix = 1; ix < n; ix++) { m_pow = product(m, m_pow); } return m_pow; } private static void test(final int[][] m, final int n) { System.out.println("Test matrix"); show_matrix(m, '*', ' '); final int[][] m_pow = power(m, n); System.out.println("Matrix power " + n); show_matrix(m_pow, '*', ' '); } private static void test1() { final int[][] m = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}; test(m, 4); } private static void test2() { final int[][] m = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; test(m, 4); } private static void test3() { final int[][] m = {{1, 0, 1}, {1, 0, 1}, {0, 1, 0}}; test(m, 4); } public static void main(final String[] args) { test1(); test2(); test3(); } }
Change the following C code into Java without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si("FULLNAME", this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, "Sorry, something went wrong :-(\n"); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value("YES", 0); if (populate_configs(&confs)) { return 1; } printf( "Full name: %s\n" "Favorite fruit: %s\n" "Need spelling: %s\n" "Seeds removed: %s\n", confs.fullname, confs.favouritefruit, confs.needspeeling ? "True" : "False", confs.seedsremoved ? "True" : "False" ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); } #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{ put( "needspeeling", false ); put( "seedsremoved", false ); }}; public static void main( final String[] args ) { System.out.println( parseFile( args[ 0 ] ) ); } public static Map<String, Object> parseFile( final String fileName ) { final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS ); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( fileName ) ); for ( String line; null != ( line = reader.readLine() ); ) { parseLine( line, result ); } } catch ( final IOException x ) { throw new RuntimeException( "Oops: " + x, x ); } finally { if ( null != reader ) try { reader.close(); } catch ( final IOException x2 ) { System.err.println( "Could not close " + fileName + " - " + x2 ); } } return result; } private static void parseLine( final String line, final Map<String, Object> map ) { if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) return; final Matcher matcher = LINE_PATTERN.matcher( line ); if ( ! matcher.matches() ) { System.err.println( "Bad config line: " + line ); return; } final String key = matcher.group( 1 ).trim().toLowerCase(); final String value = matcher.group( 2 ).trim(); if ( "".equals( value ) ) { map.put( key, true ); } else if ( -1 == value.indexOf( ',' ) ) { map.put( key, value ); } else { final String[] values = value.split( "," ); for ( int i = 0; i < values.length; i++ ) { values[ i ] = values[ i ].trim(); } map.put( key, Arrays.asList( values ) ); } } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <stdlib.h> #include <string.h> #include <strings.h> int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
import java.util.Comparator; import java.util.Arrays; public class Test { public static void main(String[] args) { String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; Arrays.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { int c = s2.length() - s1.length(); if (c == 0) c = s1.compareToIgnoreCase(s2); return c; } }); for (String s: strings) System.out.print(s + " "); } }
Port the following code from C to Java with equivalent syntax and logic.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } uint32_t cycle(uint32_t n) { uint32_t m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } bool is_circular_prime(uint32_t p) { if (!is_prime(p)) return false; uint32_t p2 = cycle(p); while (p2 != p) { if (p2 < p || !is_prime(p2)) return false; p2 = cycle(p2); } return true; } void test_repunit(uint32_t digits) { char* str = malloc(digits + 1); if (str == 0) { fprintf(stderr, "Out of memory\n"); exit(1); } memset(str, '1', digits); str[digits] = 0; mpz_t bignum; mpz_init_set_str(bignum, str, 10); free(str); if (mpz_probab_prime_p(bignum, 10)) printf("R(%u) is probably prime.\n", digits); else printf("R(%u) is not prime.\n", digits); mpz_clear(bignum); } int main() { uint32_t p = 2; printf("First 19 circular primes:\n"); for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) printf(", "); printf("%u", p); ++count; } } printf("\n"); printf("Next 4 circular primes:\n"); uint32_t repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; mpz_t bignum; mpz_init_set_ui(bignum, repunit); for (int count = 0; count < 4; ) { if (mpz_probab_prime_p(bignum, 15)) { if (count > 0) printf(", "); printf("R(%u)", digits); ++count; } ++digits; mpz_mul_ui(bignum, bignum, 10); mpz_add_ui(bignum, bignum, 1); } mpz_clear(bignum); printf("\n"); test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0) System.out.print(", "); System.out.print(p); ++count; } } System.out.println(); System.out.println("Next 4 circular primes:"); int repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; BigInteger bignum = BigInteger.valueOf(repunit); for (int count = 0; count < 4; ) { if (bignum.isProbablePrime(15)) { if (count > 0) System.out.print(", "); System.out.printf("R(%d)", digits); ++count; } ++digits; bignum = bignum.multiply(BigInteger.TEN); bignum = bignum.add(BigInteger.ONE); } System.out.println(); testRepunit(5003); testRepunit(9887); testRepunit(15073); testRepunit(25031); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static int cycle(int n) { int m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } private static boolean isCircularPrime(int p) { if (!isPrime(p)) return false; int p2 = cycle(p); while (p2 != p) { if (p2 < p || !isPrime(p2)) return false; p2 = cycle(p2); } return true; } private static void testRepunit(int digits) { BigInteger repunit = repunit(digits); if (repunit.isProbablePrime(15)) System.out.printf("R(%d) is probably prime.\n", digits); else System.out.printf("R(%d) is not prime.\n", digits); } private static BigInteger repunit(int digits) { char[] ch = new char[digits]; Arrays.fill(ch, '1'); return new BigInteger(new String(ch)); } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r = malloc(l+1); for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++) r[j] = t[i]; r[l] = 0; return r; } gboolean scroll_it(gpointer data) { if ( direction > 0 ) cx = (cx + 1) % slen; else cx = (cx + slen - 1 ) % slen; gchar *scrolled = rotateby(hello, cx, slen); gtk_label_set_text(label, scrolled); free(scrolled); return TRUE; } int main(int argc, char **argv) { GtkWidget *win; GtkButton *button; PangoFontDescription *pd; gtk_init(&argc, &argv); win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(win), "Basic Animation"); g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL); label = (GtkLabel *)gtk_label_new(hello); pd = pango_font_description_new(); pango_font_description_set_family(pd, "monospace"); gtk_widget_modify_font(GTK_WIDGET(label), pd); button = (GtkButton *)gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button)); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL); slen = strlen(hello); g_timeout_add(125, scroll_it, NULL); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; public class Rotate { private static class State { private final String text = "Hello World! "; private int startIndex = 0; private boolean rotateRight = true; } public static void main(String[] args) { State state = new State(); JLabel label = new JLabel(state.text); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { state.rotateRight = !state.rotateRight; } }); TimerTask task = new TimerTask() { public void run() { int delta = state.rotateRight ? 1 : -1; state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length(); label.setText(rotate(state.text, state.startIndex)); } }; Timer timer = new Timer(false); timer.schedule(task, 0, 500); JFrame rot = new JFrame(); rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); rot.add(label); rot.pack(); rot.setLocationRelativeTo(null); rot.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { timer.cancel(); } }); rot.setVisible(true); } private static String rotate(String text, int startIdx) { char[] rotated = new char[text.length()]; for (int i = 0; i < text.length(); i++) { rotated[i] = text.charAt((i + startIdx) % text.length()); } return String.valueOf(rotated); } }
Port the provided C code into Java while preserving the original functionality.
#include <stdio.h> #include <limits.h> #include <stdlib.h> #include <time.h> #define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) #define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); static void swap(unsigned *a, unsigned *b) { unsigned tmp = *a; *a = *b; *b = tmp; } static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) { if (!bit || to < from + 1) return; unsigned *ll = from, *rr = to - 1; for (;;) { while (ll < rr && !(*ll & bit)) ll++; while (ll < rr && (*rr & bit)) rr--; if (ll >= rr) break; swap(ll, rr); } if (!(bit & *ll) && ll < to) ll++; bit >>= 1; rad_sort_u(from, ll, bit); rad_sort_u(ll, to, bit); } static void radix_sort(int *a, const size_t len) { size_t i; unsigned *x = (unsigned*) a; for (i = 0; i < len; i++) x[i] ^= INT_MIN; rad_sort_u(x, x + len, INT_MIN); for (i = 0; i < len; i++) x[i] ^= INT_MIN; } int main(void) { srand(time(NULL)); int x[16]; for (size_t i = 0; i < ARR_LEN(x); i++) x[i] = RAND_RNG(-128,127) radix_sort(x, ARR_LEN(x)); for (size_t i = 0; i < ARR_LEN(x); i++) printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); }
public static int[] sort(int[] old) { for (int shift = Integer.SIZE - 1; shift > -1; shift--) { int[] tmp = new int[old.length]; int j = 0; for (int i = 0; i < old.length; i++) { boolean move = old[i] << shift >= 0; if (shift == 0 ? !move : move) { tmp[j] = old[i]; j++; } else { old[i - j] = old[i]; } } for (int i = j; i < tmp.length; i++) { tmp[i] = old[i - j]; } old = tmp; } return old; }
Convert this C block to Java, preserving its control flow and logic.
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
import java.util.Arrays; import java.util.List; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public interface PythagComp{ static void main(String... args){ System.out.println(run(20)); } static List<List<Integer>> run(int n){ return range(1, n).mapToObj( x -> range(x, n).mapToObj( y -> range(y, n).mapToObj( z -> new Integer[]{x, y, z} ) ) ) .flatMap(identity()) .flatMap(identity()) .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) .map(Arrays::asList) .collect(toList()) ; } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> void selection_sort (int *a, int n) { int i, j, m, t; for (i = 0; i < n; i++) { for (j = i, m = i; j < n; j++) { if (a[j] < a[m]) { m = j; } } t = a[i]; a[i] = a[m]; a[m] = t; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); selection_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
public static void sort(int[] nums){ for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ int smallest = Integer.MAX_VALUE; int smallestAt = currentPlace+1; for(int check = currentPlace; check<nums.length;check++){ if(nums[check]<smallest){ smallestAt = check; smallest = nums[check]; } } int temp = nums[currentPlace]; nums[currentPlace] = nums[smallestAt]; nums[smallestAt] = temp; } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
Translate this program into Java but keep the logic exactly as in C.
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
Port the provided C code into Java while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
Preserve the algorithm and functionality while converting the code from C to Java.
#ifndef CALLBACK_H #define CALLBACK_H void map(int* array, int len, void(*callback)(int,int)); #endif
public class ArrayCallback7 { interface IntConsumer { void run(int x); } interface IntToInt { int run(int x); } static void forEach(int[] arr, IntConsumer consumer) { for (int i : arr) { consumer.run(i); } } static void update(int[] arr, IntToInt mapper) { for (int i = 0; i < arr.length; i++) { arr[i] = mapper.run(arr[i]); } } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); update(numbers, new IntToInt() { @Override public int run(int x) { return x * x; } }); forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); } }
Preserve the algorithm and functionality while converting the code from C to Java.
#ifndef SILLY_H #define SILLY_H extern void JumpOverTheDog( int numberOfTimes); extern int PlayFetchWithDog( float weightOfStick); #endif
class Singleton { private static Singleton myInstance; public static Singleton getInstance() { if (myInstance == null) { synchronized(Singleton.class) { if (myInstance == null) { myInstance = new Singleton(); } } } return myInstance; } protected Singleton() { } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <fenv.h> #include <stdio.h> void safe_add(volatile double interval[2], volatile double a, volatile double b) { #pragma STDC FENV_ACCESS ON unsigned int orig; orig = fegetround(); fesetround(FE_DOWNWARD); interval[0] = a + b; fesetround(FE_UPWARD); interval[1] = a + b; fesetround(orig); } int main() { const double nums[][2] = { {1, 2}, {0.1, 0.2}, {1e100, 1e-100}, {1e308, 1e308}, }; double ival[2]; int i; for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) { safe_add(ival, nums[i][0], nums[i][1]); printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]); printf(" [%.17g, %.17g]\n", ival[0], ival[1]); printf(" size %.17g\n\n", ival[1] - ival[0]); } return 0; }
public class SafeAddition { private static double stepDown(double d) { return Math.nextAfter(d, Double.NEGATIVE_INFINITY); } private static double stepUp(double d) { return Math.nextUp(d); } private static double[] safeAdd(double a, double b) { return new double[]{stepDown(a + b), stepUp(a + b)}; } public static void main(String[] args) { double a = 1.2; double b = 0.03; double[] result = safeAdd(a, b); System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]); } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> static const char *dog = "Benjamin"; static const char *Dog = "Samba"; static const char *DOG = "Bernie"; int main() { printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG); return 0; }
String dog = "Benjamin"; String Dog = "Samba"; String DOG = "Bernie"; @Inject Console console; console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
Rewrite this program in Java while keeping its functionality equivalent to the C version.
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
for (int i = 10; i >= 0; i--) { System.out.println(i); }
Write the same code in Java as shown below in C.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.", freopen("sample.txt","wb",stdout)); }
import java.io.*; public class Test { public static void main(String[] args) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) { bw.write("abc"); } } }
Transform the following C implementation into Java, maintaining the same output and logic.
int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) putchar('*'); puts(""); }
for (Integer i = 0; i < 5; i++) { String line = ''; for (Integer j = 0; j < i; j++) { line += '*'; } System.debug(line); } List<String> lines = new List<String> { '*', '**', '***', '****', '*****' }; for (String line : lines) { System.debug(line); }
Translate this program into Java but keep the logic exactly as in C.
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
Change the following C code into Java without altering its purpose.
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
Generate an equivalent Java version of this C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
Port the following code from C to Java with equivalent syntax and logic.
#include <assert.h> #include <stdio.h> int main(int c, char **v) { unsigned int n = 1 << (c - 1), i = n, j, k; assert(n); while (i--) { if (!(i & (i + (i & -(int)i)))) continue; for (j = n, k = 1; j >>= 1; k++) if (i & j) printf("%s ", v[k]); putchar('\n'); } return 0; }
public class NonContinuousSubsequences { public static void main(String args[]) { seqR("1234", "", 0, 0); } private static void seqR(String s, String c, int i, int added) { if (i == s.length()) { if (c.trim().length() > added) System.out.println(c); } else { seqR(s, c + s.charAt(i), i + 1, added + 1); seqR(s, c + ' ', i + 1, added); } } }
Port the following code from C to Java with equivalent syntax and logic.
#include <stdio.h> int main(void) { puts( "%!PS-Adobe-3.0 EPSF\n" "%%BoundingBox: -10 -10 400 565\n" "/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n" "/b{a 90 rotate}def"); char i; for (i = 'c'; i <= 'z'; i++) printf("/%c{%c %c}def\n", i, i-1, i-2); puts("0 setlinewidth z showpage\n%%EOF"); return 0; }
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n) { if (n < 2) return n == 1 ? "1" : ""; StringBuilder f1 = new StringBuilder("1"); StringBuilder f2 = new StringBuilder("0"); for (n = n - 2; n > 0; n--) { String tmp = f2.toString(); f2.append(f1); f1.setLength(0); f1.append(tmp); } return f2.toString(); } void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) { for (int n = 0; n < wordFractal.length(); n++) { g.drawLine(x, y, x + dx, y + dy); x += dx; y += dy; if (wordFractal.charAt(n) == '0') { int tx = dx; dx = (n % 2 == 0) ? -dy : dy; dy = (n % 2 == 0) ? tx : -tx; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawWordFractal(g, 20, 20, 1, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Fibonacci Word Fractal"); f.setResizable(false); f.add(new FibonacciWordFractal(23), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Keep all operations the same but rewrite the snippet in Java.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> bool isPrime(int64_t n) { int64_t i; if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; if (n % 7 == 0) return n == 7; if (n % 11 == 0) return n == 11; if (n % 13 == 0) return n == 13; if (n % 17 == 0) return n == 17; if (n % 19 == 0) return n == 19; for (i = 23; i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } int countTwinPrimes(int limit) { int count = 0; int64_t p3 = true, p2 = true, p1 = false; int64_t i; for (i = 5; i <= limit; i++) { p3 = p2; p2 = p1; p1 = isPrime(i); if (p3 && p1) { count++; } } return count; } void test(int limit) { int count = countTwinPrimes(limit); printf("Number of twin prime pairs less than %d is %d\n", limit, count); } int main() { test(10); test(100); test(1000); test(10000); test(100000); test(1000000); test(10000000); test(100000000); return 0; }
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> #include <math.h> int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i; for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a), s = sin(a); if (c) printf("%.2g", c); printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s); printf(i == n - 1 ?"\n":", "); } return 0; }
import java.util.Locale; public class Test { public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); } public static void unity(int n) { System.out.printf("%n%d: ", n); for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) { double real = Math.cos(angle); if (Math.abs(real) < 1.0E-3) real = 0.0; double imag = Math.sin(angle); if (Math.abs(imag) < 1.0E-3) imag = 0.0; System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
Generate a Java translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <string.h> void longmulti(const char *a, const char *b, char *c) { int i = 0, j = 0, k = 0, n, carry; int la, lb; if (!strcmp(a, "0") || !strcmp(b, "0")) { c[0] = '0', c[1] = '\0'; return; } if (a[0] == '-') { i = 1; k = !k; } if (b[0] == '-') { j = 1; k = !k; } if (i || j) { if (k) c[0] = '-'; longmulti(a + i, b + j, c + k); return; } la = strlen(a); lb = strlen(b); memset(c, '0', la + lb); c[la + lb] = '\0'; # define I(a) (a - '0') for (i = la - 1; i >= 0; i--) { for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) { n = I(a[i]) * I(b[j]) + I(c[k]) + carry; carry = n / 10; c[k] = (n % 10) + '0'; } c[k] += carry; } # undef I if (c[0] == '0') memmove(c, c + 1, la + lb); return; } int main() { char c[1024]; longmulti("-18446744073709551616", "-18446744073709551616", c); printf("%s\n", c); return 0; }
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
Write the same algorithm in Java as shown in this C implementation.
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { return makePair(1, 0); } else { int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } } return makePair(a, b); } } void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); } int main() { test(61); test(109); test(181); test(277); return 0; }
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PellsEquation { public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } } private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } } private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b; while ( true ) { int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; } private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; } }
Generate a Java translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdbool.h> #include <curses.h> #include <string.h> #define MAX_NUM_TRIES 72 #define LINE_BEGIN 7 #define LAST_LINE 18 int yp=LINE_BEGIN, xp=0; char number[5]; char guess[5]; #define MAX_STR 256 void mvaddstrf(int y, int x, const char *fmt, ...) { va_list args; char buf[MAX_STR]; va_start(args, fmt); vsprintf(buf, fmt, args); move(y, x); clrtoeol(); addstr(buf); va_end(args); } void ask_for_a_number() { int i=0; char symbols[] = "123456789"; move(5,0); clrtoeol(); addstr("Enter four digits: "); while(i<4) { int c = getch(); if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) { addch(c); symbols[c-'1'] = 0; guess[i++] = c; } } } void choose_the_number() { int i=0, j; char symbols[] = "123456789"; while(i<4) { j = rand() % 9; if ( symbols[j] != 0 ) { number[i++] = symbols[j]; symbols[j] = 0; } } }
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); } public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdio.h> void bubble_sort (int *a, int n) { int i, t, j = n, s = 1; while (s) { s = 0; for (i = 1; i < j; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } j--; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); bubble_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
Write a version of this C function in Java with identical behavior.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
Generate an equivalent Java version of this C code.
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> int main(int argc, char **argv) { FILE *in, *out; int c; in = fopen("input.txt", "r"); if (!in) { fprintf(stderr, "Error opening input.txt for reading.\n"); return 1; } out = fopen("output.txt", "w"); if (!out) { fprintf(stderr, "Error opening output.txt for writing.\n"); fclose(in); return 1; } while ((c = fgetc(in)) != EOF) { fputc(c, out); } fclose(out); fclose(in); return 0; }
import java.io.*; public class FileIODemo { public static void main(String[] args) { try { FileInputStream in = new FileInputStream("input.txt"); FileOutputStream out = new FileOutputStream("ouput.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } }
Produce a functionally identical Java code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a, b; if (argc < 3) exit(1); b = atoi(argv[--argc]); if (b == 0) exit(2); a = atoi(argv[--argc]); printf("a+b = %d\n", a+b); printf("a-b = %d\n", a-b); printf("a*b = %d\n", a*b); printf("a/b = %d\n", a/b); printf("a%%b = %d\n", a%b); return 0; }
import java.util.Scanner; public class IntegerArithmetic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int sum = a + b; int difference = a - b; int product = a * b; int division = a / b; int remainder = a % b; System.out.println("a + b = " + sum); System.out.println("a - b = " + difference); System.out.println("a * b = " + product); System.out.println("quotient of a / b = " + division); System.out.println("remainder of a / b = " + remainder); } }
Produce a functionally identical Java code for the snippet given in C.
#include <stdio.h> void transpose(void *dest, void *src, int src_h, int src_w) { int i, j; double (*d)[src_h] = dest, (*s)[src_w] = src; for (i = 0; i < src_h; i++) for (j = 0; j < src_w; j++) d[j][i] = s[i][j]; } int main() { int i, j; double a[3][5] = {{ 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 1, 0, 0, 0, 42}}; double b[5][3]; transpose(b, a, 3, 5); for (i = 0; i < 5; i++) for (j = 0; j < 3; j++) printf("%g%c", b[i][j], j == 2 ? '\n' : ' '); return 0; }
import java.util.Arrays; public class Transpose{ public static void main(String[] args){ double[][] m = {{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}, {5, 25, 125, 625}}; double[][] ans = new double[m[0].length][m.length]; for(int rows = 0; rows < m.length; rows++){ for(int cols = 0; cols < m[0].length; cols++){ ans[cols][rows] = m[rows][cols]; } } for(double[] i:ans){ System.out.println(Arrays.toString(i)); } } }
Keep all operations the same but rewrite the snippet in Java.
#include <stdio.h> #include <stdlib.h> typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG; int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; } int eval(ARG* a) { return a->fn(a); } #define MAKE_ARG(...) (&(ARG){__VA_ARGS__}) #define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__) int A(ARG*); int B(ARG* a) { int k = *a->k -= 1; return A(FUN(a, a->x1, a->x2, a->x3, a->x4)); } int A(ARG* a) { return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a); } int main(int argc, char **argv) { int k = argc == 2 ? strtol(argv[1], 0, 0) : 10; printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1), MAKE_ARG(f1), MAKE_ARG(f0)))); return 0; }
import java.util.function.DoubleSupplier; public class ManOrBoy { static double A(int k, DoubleSupplier x1, DoubleSupplier x2, DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) { DoubleSupplier B = new DoubleSupplier() { int m = k; public double getAsDouble() { return A(--m, this, x1, x2, x3, x4); } }; return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble(); } public static void main(String[] args) { System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0)); } }
Convert this C snippet to Java and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG; int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; } int eval(ARG* a) { return a->fn(a); } #define MAKE_ARG(...) (&(ARG){__VA_ARGS__}) #define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__) int A(ARG*); int B(ARG* a) { int k = *a->k -= 1; return A(FUN(a, a->x1, a->x2, a->x3, a->x4)); } int A(ARG* a) { return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a); } int main(int argc, char **argv) { int k = argc == 2 ? strtol(argv[1], 0, 0) : 10; printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1), MAKE_ARG(f1), MAKE_ARG(f0)))); return 0; }
import java.util.function.DoubleSupplier; public class ManOrBoy { static double A(int k, DoubleSupplier x1, DoubleSupplier x2, DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) { DoubleSupplier B = new DoubleSupplier() { int m = k; public double getAsDouble() { return A(--m, this, x1, x2, x3, x4); } }; return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble(); } public static void main(String[] args) { System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0)); } }
Change the programming language of this snippet from C to Java without modifying what it does.
#include <stdio.h> #include <stdbool.h> bool a(bool in) { printf("I am a\n"); return in; } bool b(bool in) { printf("I am b\n"); return in; } #define TEST(X,Y,O) \ do { \ x = a(X) O b(Y); \ printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \ } while(false); int main() { bool x; TEST(false, true, &&); TEST(true, false, ||); TEST(true, false, &&); TEST(false, false, ||); return 0; }
module test { @Inject Console console; static Boolean show(String name, Boolean value) { console.print($"{name}()={value}"); return value; } void run() { val a = show("a", _); val b = show("b", _); for (Boolean v1 : False..True) { for (Boolean v2 : False..True) { console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}"); console.print(); console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}"); console.print(); } } } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdio.h> #define mod(n,m) ((((n) % (m)) + (m)) % (m)) int is_prime(unsigned int n) { if (n <= 3) { return n > 1; } else if (!(n % 2) || !(n % 3)) { return 0; } else { unsigned int i; for (i = 5; i*i <= n; i += 6) if (!(n % i) || !(n % (i + 2))) return 0; return 1; } } void carmichael3(int p1) { if (!is_prime(p1)) return; int h3, d, p2, p3; for (h3 = 1; h3 < p1; ++h3) { for (d = 1; d < h3 + p1; ++d) { if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) { p2 = 1 + ((p1 - 1) * (h3 + p1)/d); if (!is_prime(p2)) continue; p3 = 1 + (p1 * p2 / h3); if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue; printf("%d %d %d\n", p1, p2, p3); } } } } int main(void) { int p1; for (p1 = 2; p1 < 62; ++p1) carmichael3(p1); return 0; }
public class Test { static int mod(int n, int m) { return ((n % m) + m) % m; } static boolean isPrime(int n) { if (n == 2 || n == 3) return true; else if (n < 2 || n % 2 == 0 || n % 3 == 0) return false; for (int div = 5, inc = 2; Math.pow(div, 2) <= n; div += inc, inc = 6 - inc) if (n % div == 0) return false; return true; } public static void main(String[] args) { for (int p = 2; p < 62; p++) { if (!isPrime(p)) continue; for (int h3 = 2; h3 < p; h3++) { int g = h3 + p; for (int d = 1; d < g; d++) { if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3) continue; int q = 1 + (p - 1) * g / d; if (!isPrime(q)) continue; int r = 1 + (p * q / h3); if (!isPrime(r) || (q * r) % (p - 1) != 1) continue; System.out.printf("%d x %d x %d%n", p, q, r); } } } } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <SDL/SDL.h> unsigned int frames = 0; unsigned int t_acc = 0; void print_fps () { static Uint32 last_t = 0; Uint32 t = SDL_GetTicks(); Uint32 dt = t - last_t; t_acc += dt; if (t_acc > 1000) { unsigned int el_time = t_acc / 1000; printf("- fps: %g\n", (float) frames / (float) el_time); t_acc = 0; frames = 0; } last_t = t; } void blit_noise(SDL_Surface *surf) { unsigned int i; long dim = surf->w * surf->h; while (1) { SDL_LockSurface(surf); for (i=0; i < dim; ++i) { ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0); } SDL_UnlockSurface(surf); SDL_Flip(surf); ++frames; print_fps(); } } int main(void) { SDL_Surface *surf = NULL; srand((unsigned int)time(NULL)); SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE); blit_noise(surf); }
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.util.Arrays; import java.util.Random; import javax.swing.*; public class ImageNoise { int framecount = 0; int fps = 0; BufferedImage image; Kernel kernel; ConvolveOp cop; JFrame frame = new JFrame("Java Image Noise"); JPanel panel = new JPanel() { private int show_fps = 0; private MouseAdapter ma = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { show_fps = (show_fps + 1) % 3; } }; {addMouseListener(ma);} @Override public Dimension getPreferredSize() { return new Dimension(320, 240); } @Override @SuppressWarnings("fallthrough") public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; drawNoise(); g.drawImage(image, 0, 0, null); switch (show_fps) { case 0: int xblur = getWidth() - 130, yblur = getHeight() - 32; BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32); BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(), BufferedImage.TYPE_BYTE_GRAY); cop.filter(bc, bs); g.drawImage(bs, xblur, yblur , null); case 1: g.setColor(Color.RED); g.setFont(new Font("Monospaced", Font.BOLD, 20)); g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10); } framecount++; } }; Timer repainter = new Timer(1, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.repaint(); } }); Timer framerateChecker = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fps = framecount; framecount = 0; } }); public ImageNoise() { float[] vals = new float[121]; Arrays.fill(vals, 1/121f); kernel = new Kernel(11, 11, vals); cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); repainter.start(); framerateChecker.start(); } void drawNoise() { int w = panel.getWidth(), h = panel.getHeight(); if (null == image || image.getWidth() != w || image.getHeight() != h) { image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); } Random rand = new Random(); int[] data = new int[w * h]; for (int x = 0; x < w * h / 32; x++) { int r = rand.nextInt(); for (int i = 0; i < 32; i++) { data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE; r >>>= 1; } } image.getRaster().setPixels(0, 0, w, h, data); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ImageNoise i = new ImageNoise(); } }); } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include "stdio.h" #include "math.h" int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf("%d\n", n); return 0; }
public static boolean perf(int n){ int sum= 0; for(int i= 1;i < n;i++){ if(n % i == 0){ sum+= i; } } return sum == n; }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j] for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) BEAD(i, j) = 1; for (j = 0; j < max; j++) { for (sum = i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } for (i = len - sum; i < len; i++) BEAD(i, j) = 1; } for (i = 0; i < len; i++) { for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; } free(beads); } int main() { int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(x)/sizeof(x[0]); bead_sort(x, len); for (i = 0; i < len; i++) printf("%d\n", x[i]); return 0; }
public class BeadSort { public static void main(String[] args) { BeadSort now=new BeadSort(); int[] arr=new int[(int)(Math.random()*11)+5]; for(int i=0;i<arr.length;i++) arr[i]=(int)(Math.random()*10); System.out.print("Unsorted: "); now.display1D(arr); int[] sort=now.beadSort(arr); System.out.print("Sorted: "); now.display1D(sort); } int[] beadSort(int[] arr) { int max=a[0]; for(int i=1;i<arr.length;i++) if(arr[i]>max) max=arr[i]; char[][] grid=new char[arr.length][max]; int[] levelcount=new int[max]; for(int i=0;i<max;i++) { levelcount[i]=0; for(int j=0;j<arr.length;j++) grid[j][i]='_'; } for(int i=0;i<arr.length;i++) { int num=arr[i]; for(int j=0;num>0;j++) { grid[levelcount[j]++][j]='*'; num--; } } System.out.println(); display2D(grid); int[] sorted=new int[arr.length]; for(int i=0;i<arr.length;i++) { int putt=0; for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++) putt++; sorted[i]=putt; } return sorted; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display1D(char[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display2D(char[][] arr) { for(int i=0;i<arr.length;i++) display1D(arr[i]); System.out.println(); } }
Generate an equivalent Java version of this C code.
#include <stdio.h> #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE]; void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } } void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); } int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999); return 0; }
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <stdio.h> #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE]; void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } } void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); } int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999); return 0; }
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
Translate this program into Java but keep the logic exactly as in C.
#include <stdio.h> #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE]; void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } } void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); } int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999); return 0; }
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
#include <gmp.h> #include <stdio.h> #include <string.h> int main() { mpz_t a; mpz_init_set_ui(a, 5); mpz_pow_ui(a, a, 1 << 18); int len = mpz_sizeinbase(a, 10); printf("GMP says size is: %d\n", len); char *s = mpz_get_str(0, 10, a); printf("size really is %d\n", len = strlen(s)); printf("Digits: %.20s...%s\n", s, s + len - 20); return 0; }
import java.math.BigInteger; class IntegerPower { public static void main(String[] args) { BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact()); String str = power.toString(); int len = str.length(); System.out.printf("5**4**3**2 = %s...%s and has %d digits%n", str.substring(0, 20), str.substring(len - 20), len); } }
Maintain the same structure and functionality when rewriting this code in Java.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *shades = ".:!*oe&#%@"; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } } int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4); return 0; }
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *shades = ".:!*oe&#%@"; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } } int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4); return 0; }
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
Translate this program into Java but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./"; int chr_idx[256] = {0}; char idx_chr[256] = {0}; #define FNAME 0 typedef struct trie_t *trie, trie_t; struct trie_t { trie next[sizeof(chr_legal)]; int eow; }; trie trie_new() { return calloc(sizeof(trie_t), 1); } #define find_word(r, w) trie_trav(r, w, 1) trie trie_trav(trie root, const char * str, int no_create) { int c; while (root) { if ((c = str[0]) == '\0') { if (!root->eow && no_create) return 0; break; } if (! (c = chr_idx[c]) ) { str++; continue; } if (!root->next[c]) { if (no_create) return 0; root->next[c] = trie_new(); } root = root->next[c]; str++; } return root; } int trie_all(trie root, char path[], int depth, int (*callback)(char *)) { int i; if (root->eow && !callback(path)) return 0; for (i = 1; i < sizeof(chr_legal); i++) { if (!root->next[i]) continue; path[depth] = idx_chr[i]; path[depth + 1] = '\0'; if (!trie_all(root->next[i], path, depth + 1, callback)) return 0; } return 1; } void add_index(trie root, const char *word, const char *fname) { trie x = trie_trav(root, word, 0); x->eow = 1; if (!x->next[FNAME]) x->next[FNAME] = trie_new(); x = trie_trav(x->next[FNAME], fname, 0); x->eow = 1; } int print_path(char *path) { printf(" %s", path); return 1; } const char *files[] = { "f1.txt", "source/f2.txt", "other_file" }; const char *text[][5] ={{ "it", "is", "what", "it", "is" }, { "what", "is", "it", 0 }, { "it", "is", "a", "banana", 0 }}; trie init_tables() { int i, j; trie root = trie_new(); for (i = 0; i < sizeof(chr_legal); i++) { chr_idx[(int)chr_legal[i]] = i + 1; idx_chr[i + 1] = chr_legal[i]; } #define USE_ADVANCED_FILE_HANDLING 0 #if USE_ADVANCED_FILE_HANDLING void read_file(const char * fname) { char cmd[1024]; char word[1024]; sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname); FILE *in = popen(cmd, "r"); while (!feof(in)) { fscanf(in, "%1000s", word); add_index(root, word, fname); } pclose(in); }; read_file("f1.txt"); read_file("source/f2.txt"); read_file("other_file"); #else for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) { if (!text[i][j]) break; add_index(root, text[i][j], files[i]); } } #endif return root; } void search_index(trie root, const char *word) { char path[1024]; printf("Search for \"%s\": ", word); trie found = find_word(root, word); if (!found) printf("not found\n"); else { trie_all(found->next[FNAME], path, 0, print_path); printf("\n"); } } int main() { trie root = init_tables(); search_index(root, "what"); search_index(root, "is"); search_index(root, "banana"); search_index(root, "boo"); return 0; }
package org.rosettacode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class InvertedIndex { List<String> stopwords = Arrays.asList("a", "able", "about", "across", "after", "all", "almost", "also", "am", "among", "an", "and", "any", "are", "as", "at", "be", "because", "been", "but", "by", "can", "cannot", "could", "dear", "did", "do", "does", "either", "else", "ever", "every", "for", "from", "get", "got", "had", "has", "have", "he", "her", "hers", "him", "his", "how", "however", "i", "if", "in", "into", "is", "it", "its", "just", "least", "let", "like", "likely", "may", "me", "might", "most", "must", "my", "neither", "no", "nor", "not", "of", "off", "often", "on", "only", "or", "other", "our", "own", "rather", "said", "say", "says", "she", "should", "since", "so", "some", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "tis", "to", "too", "twas", "us", "wants", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "would", "yet", "you", "your"); Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>(); List<String> files = new ArrayList<String>(); public void indexFile(File file) throws IOException { int fileno = files.indexOf(file.getPath()); if (fileno == -1) { files.add(file.getPath()); fileno = files.size() - 1; } int pos = 0; BufferedReader reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader .readLine()) { for (String _word : line.split("\\W+")) { String word = _word.toLowerCase(); pos++; if (stopwords.contains(word)) continue; List<Tuple> idx = index.get(word); if (idx == null) { idx = new LinkedList<Tuple>(); index.put(word, idx); } idx.add(new Tuple(fileno, pos)); } } System.out.println("indexed " + file.getPath() + " " + pos + " words"); } public void search(List<String> words) { for (String _word : words) { Set<String> answer = new HashSet<String>(); String word = _word.toLowerCase(); List<Tuple> idx = index.get(word); if (idx != null) { for (Tuple t : idx) { answer.add(files.get(t.fileno)); } } System.out.print(word); for (String f : answer) { System.out.print(" " + f); } System.out.println(""); } } public static void main(String[] args) { try { InvertedIndex idx = new InvertedIndex(); for (int i = 1; i < args.length; i++) { idx.indexFile(new File(args[i])); } idx.search(Arrays.asList(args[0].split(","))); } catch (Exception e) { e.printStackTrace(); } } private class Tuple { private int fileno; private int position; public Tuple(int fileno, int position) { this.fileno = fileno; this.position = position; } } }
Convert this C snippet to Java and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./"; int chr_idx[256] = {0}; char idx_chr[256] = {0}; #define FNAME 0 typedef struct trie_t *trie, trie_t; struct trie_t { trie next[sizeof(chr_legal)]; int eow; }; trie trie_new() { return calloc(sizeof(trie_t), 1); } #define find_word(r, w) trie_trav(r, w, 1) trie trie_trav(trie root, const char * str, int no_create) { int c; while (root) { if ((c = str[0]) == '\0') { if (!root->eow && no_create) return 0; break; } if (! (c = chr_idx[c]) ) { str++; continue; } if (!root->next[c]) { if (no_create) return 0; root->next[c] = trie_new(); } root = root->next[c]; str++; } return root; } int trie_all(trie root, char path[], int depth, int (*callback)(char *)) { int i; if (root->eow && !callback(path)) return 0; for (i = 1; i < sizeof(chr_legal); i++) { if (!root->next[i]) continue; path[depth] = idx_chr[i]; path[depth + 1] = '\0'; if (!trie_all(root->next[i], path, depth + 1, callback)) return 0; } return 1; } void add_index(trie root, const char *word, const char *fname) { trie x = trie_trav(root, word, 0); x->eow = 1; if (!x->next[FNAME]) x->next[FNAME] = trie_new(); x = trie_trav(x->next[FNAME], fname, 0); x->eow = 1; } int print_path(char *path) { printf(" %s", path); return 1; } const char *files[] = { "f1.txt", "source/f2.txt", "other_file" }; const char *text[][5] ={{ "it", "is", "what", "it", "is" }, { "what", "is", "it", 0 }, { "it", "is", "a", "banana", 0 }}; trie init_tables() { int i, j; trie root = trie_new(); for (i = 0; i < sizeof(chr_legal); i++) { chr_idx[(int)chr_legal[i]] = i + 1; idx_chr[i + 1] = chr_legal[i]; } #define USE_ADVANCED_FILE_HANDLING 0 #if USE_ADVANCED_FILE_HANDLING void read_file(const char * fname) { char cmd[1024]; char word[1024]; sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname); FILE *in = popen(cmd, "r"); while (!feof(in)) { fscanf(in, "%1000s", word); add_index(root, word, fname); } pclose(in); }; read_file("f1.txt"); read_file("source/f2.txt"); read_file("other_file"); #else for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) { if (!text[i][j]) break; add_index(root, text[i][j], files[i]); } } #endif return root; } void search_index(trie root, const char *word) { char path[1024]; printf("Search for \"%s\": ", word); trie found = find_word(root, word); if (!found) printf("not found\n"); else { trie_all(found->next[FNAME], path, 0, print_path); printf("\n"); } } int main() { trie root = init_tables(); search_index(root, "what"); search_index(root, "is"); search_index(root, "banana"); search_index(root, "boo"); return 0; }
package org.rosettacode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class InvertedIndex { List<String> stopwords = Arrays.asList("a", "able", "about", "across", "after", "all", "almost", "also", "am", "among", "an", "and", "any", "are", "as", "at", "be", "because", "been", "but", "by", "can", "cannot", "could", "dear", "did", "do", "does", "either", "else", "ever", "every", "for", "from", "get", "got", "had", "has", "have", "he", "her", "hers", "him", "his", "how", "however", "i", "if", "in", "into", "is", "it", "its", "just", "least", "let", "like", "likely", "may", "me", "might", "most", "must", "my", "neither", "no", "nor", "not", "of", "off", "often", "on", "only", "or", "other", "our", "own", "rather", "said", "say", "says", "she", "should", "since", "so", "some", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "tis", "to", "too", "twas", "us", "wants", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "would", "yet", "you", "your"); Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>(); List<String> files = new ArrayList<String>(); public void indexFile(File file) throws IOException { int fileno = files.indexOf(file.getPath()); if (fileno == -1) { files.add(file.getPath()); fileno = files.size() - 1; } int pos = 0; BufferedReader reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader .readLine()) { for (String _word : line.split("\\W+")) { String word = _word.toLowerCase(); pos++; if (stopwords.contains(word)) continue; List<Tuple> idx = index.get(word); if (idx == null) { idx = new LinkedList<Tuple>(); index.put(word, idx); } idx.add(new Tuple(fileno, pos)); } } System.out.println("indexed " + file.getPath() + " " + pos + " words"); } public void search(List<String> words) { for (String _word : words) { Set<String> answer = new HashSet<String>(); String word = _word.toLowerCase(); List<Tuple> idx = index.get(word); if (idx != null) { for (Tuple t : idx) { answer.add(files.get(t.fileno)); } } System.out.print(word); for (String f : answer) { System.out.print(" " + f); } System.out.println(""); } } public static void main(String[] args) { try { InvertedIndex idx = new InvertedIndex(); for (int i = 1; i < args.length; i++) { idx.indexFile(new File(args[i])); } idx.search(Arrays.asList(args[0].split(","))); } catch (Exception e) { e.printStackTrace(); } } private class Tuple { private int fileno; private int position; public Tuple(int fileno, int position) { this.fileno = fileno; this.position = position; } } }
Translate this program into Java but keep the logic exactly as in C.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Maintain the same structure and functionality when rewriting this code in Java.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdlib.h> #include <stdio.h> #include <gmp.h> void mpz_factors(mpz_t n) { int factors = 0; mpz_t s, m, p; mpz_init(s), mpz_init(m), mpz_init(p); mpz_set_ui(m, 3); mpz_set(p, n); mpz_sqrt(s, p); while (mpz_cmp(m, s) < 0) { if (mpz_divisible_p(p, m)) { gmp_printf("%Zd ", m); mpz_fdiv_q(p, p, m); mpz_sqrt(s, p); factors ++; } mpz_add_ui(m, m, 2); } if (factors == 0) printf("PRIME\n"); else gmp_printf("%Zd\n", p); } int main(int argc, char const *argv[]) { mpz_t fermat; mpz_init_set_ui(fermat, 3); printf("F(0) = 3 -> PRIME\n"); for (unsigned i = 1; i < 10; i ++) { mpz_sub_ui(fermat, fermat, 1); mpz_mul(fermat, fermat, fermat); mpz_add_ui(fermat, fermat, 1); gmp_printf("F(%d) = %Zd -> ", i, fermat); mpz_factors(fermat); } return 0; }
import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class FermatNumbers { public static void main(String[] args) { System.out.println("First 10 Fermat numbers:"); for ( int i = 0 ; i < 10 ; i++ ) { System.out.printf("F[%d] = %s\n", i, fermat(i)); } System.out.printf("%nFirst 12 Fermat numbers factored:%n"); for ( int i = 0 ; i < 13 ; i++ ) { System.out.printf("F[%d] = %s\n", i, getString(getFactors(i, fermat(i)))); } } private static String getString(List<BigInteger> factors) { if ( factors.size() == 1 ) { return factors.get(0) + " (PRIME)"; } return factors.stream().map(v -> v.toString()).map(v -> v.startsWith("-") ? "(C" + v.replace("-", "") + ")" : v).collect(Collectors.joining(" * ")); } private static Map<Integer, String> COMPOSITE = new HashMap<>(); static { COMPOSITE.put(9, "5529"); COMPOSITE.put(10, "6078"); COMPOSITE.put(11, "1037"); COMPOSITE.put(12, "5488"); COMPOSITE.put(13, "2884"); } private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) { List<BigInteger> factors = new ArrayList<>(); BigInteger factor = BigInteger.ONE; while ( true ) { if ( n.isProbablePrime(100) ) { factors.add(n); break; } else { if ( COMPOSITE.containsKey(fermatIndex) ) { String stop = COMPOSITE.get(fermatIndex); if ( n.toString().startsWith(stop) ) { factors.add(new BigInteger("-" + n.toString().length())); break; } } factor = pollardRhoFast(n); if ( factor.compareTo(BigInteger.ZERO) == 0 ) { factors.add(n); break; } else { factors.add(factor); n = n.divide(factor); } } } return factors; } private static final BigInteger TWO = BigInteger.valueOf(2); private static BigInteger fermat(int n) { return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE); } @SuppressWarnings("unused") private static BigInteger pollardRho(BigInteger n) { BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; while ( d.compareTo(BigInteger.ONE) == 0 ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs().gcd(n); } if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoFast(BigInteger n) { long start = System.currentTimeMillis(); BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; int count = 0; BigInteger z = BigInteger.ONE; while ( true ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs(); z = z.multiply(d).mod(n); count++; if ( count == 100 ) { d = z.gcd(n); if ( d.compareTo(BigInteger.ONE) != 0 ) { break; } z = BigInteger.ONE; count = 0; } } long end = System.currentTimeMillis(); System.out.printf(" Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n", n, (end-start), d); if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoG(BigInteger x, BigInteger n) { return x.multiply(x).add(BigInteger.ONE).mod(n); } }
Rewrite the snippet below in Java so it works the same as the original C code.
int main(){ time_t t; int a, b; srand((unsigned)time(&t)); for(;;){ a = rand() % 20; printf("%d\n", a); if(a == 10) break; b = rand() % 20; printf("%d\n", b); } return 0; }
import java.util.Random; Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
Generate a Java translation of this C snippet without changing its computational steps.
int main(){ time_t t; int a, b; srand((unsigned)time(&t)); for(;;){ a = rand() % 20; printf("%d\n", a); if(a == 10) break; b = rand() % 20; printf("%d\n", b); } return 0; }
import java.util.Random; Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include<stdlib.h> #include<stdio.h> int getWater(int* arr,int start,int end,int cutoff){ int i, sum = 0; for(i=start;i<=end;i++) sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0); return sum; } int netWater(int* arr,int size){ int i, j, ref1, ref2, marker, markerSet = 0,sum = 0; if(size<3) return 0; for(i=0;i<size-1;i++){ start:if(i!=size-2 && arr[i]>arr[i+1]){ ref1 = i; for(j=ref1+1;j<size;j++){ if(arr[j]>=arr[ref1]){ ref2 = j; sum += getWater(arr,ref1+1,ref2-1,ref1); i = ref2; goto start; } else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){ marker = j+1; markerSet = 1; } } if(markerSet==1){ sum += getWater(arr,ref1+1,marker-1,marker); i = marker; markerSet = 0; goto start; } } } return sum; } int main(int argC,char* argV[]) { int *arr,i; if(argC==1) printf("Usage : %s <followed by space separated series of integers>"); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<argC;i++) arr[i-1] = atoi(argV[i]); printf("Water collected : %d",netWater(arr,argC-1)); } return 0; }
public class WaterBetweenTowers { public static void main(String[] args) { int i = 1; int[][] tba = new int[][]{ new int[]{1, 5, 3, 7, 2}, new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, new int[]{5, 5, 5, 5}, new int[]{5, 6, 7, 8}, new int[]{8, 7, 7, 6}, new int[]{6, 7, 10, 7, 6} }; for (int[] tea : tba) { int rht, wu = 0, bof; do { for (rht = tea.length - 1; rht >= 0; rht--) { if (tea[rht] > 0) { break; } } if (rht < 0) { break; } bof = 0; for (int col = 0; col <= rht; col++) { if (tea[col] > 0) { tea[col]--; bof += 1; } else if (bof > 0) { wu++; } } if (bof < 2) { break; } } while (true); System.out.printf("Block %d", i++); if (wu == 0) { System.out.print(" does not hold any"); } else { System.out.printf(" holds %d", wu); } System.out.println(" water units."); } } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define TRUE 1 #define FALSE 0 #define TRILLION 1000000000000 typedef unsigned char bool; typedef unsigned long long uint64; void sieve(uint64 limit, uint64 *primes, uint64 *length) { uint64 i, count, p, p2; bool *c = calloc(limit + 1, sizeof(bool)); primes[0] = 2; count = 1; p = 3; for (;;) { p2 = p * p; if (p2 > limit) break; for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE; for (;;) { p += 2; if (!c[p]) break; } } for (i = 3; i <= limit; i += 2) { if (!c[i]) primes[count++] = i; } *length = count; free(c); } void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) { uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to); uint64 *primes = malloc((limit + 1) * sizeof(uint64)); bool add; sieve(limit, primes, &np); for (i = from; i <= to; ++i) { add = TRUE; for (j = 0; j < np; ++j) { p = primes[j]; p2 = p * p; if (p2 > i) break; if (i % p2 == 0) { add = FALSE; break; } } if (add) results[count++] = i; } *len = count; free(primes); } int main() { uint64 i, *sf, len; sf = malloc(1000000 * sizeof(uint64)); printf("Square-free integers from 1 to 145:\n"); squareFree(1, 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 20 == 0) { printf("\n"); } printf("%4lld", sf[i]); } printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145); squareFree(TRILLION, TRILLION + 145, sf, &len); for (i = 0; i < len; ++i) { if (i > 0 && i % 5 == 0) { printf("\n"); } printf("%14lld", sf[i]); } printf("\n\nNumber of square-free integers:\n"); int a[5] = {100, 1000, 10000, 100000, 1000000}; for (i = 0; i < 5; ++i) { squareFree(1, a[i], sf, &len); printf(" from %d to %d = %lld\n", 1, a[i], len); } free(sf); return 0; }
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long p2 = p * p; if (p2 > limit) break; for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true; for (;;) { p += 2; if (!c[(int)p]) break; } } for (long i = 3; i <= limit; i += 2) { if (!c[(int)i]) primes.add(i); } return primes; } private static List<Long> squareFree(long from, long to) { long limit = (long)Math.sqrt((double)to); List<Long> primes = sieve(limit); List<Long> results = new ArrayList<Long>(); outer: for (long i = from; i <= to; i++) { for (long p : primes) { long p2 = p * p; if (p2 > i) break; if (i % p2 == 0) continue outer; } results.add(i); } return results; } private final static long TRILLION = 1000000000000L; public static void main(String[] args) { System.out.println("Square-free integers from 1 to 145:"); List<Long> sf = squareFree(1, 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 20 == 0) { System.out.println(); } System.out.printf("%4d", sf.get(i)); } System.out.print("\n\nSquare-free integers"); System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145); sf = squareFree(TRILLION, TRILLION + 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 5 == 0) System.out.println(); System.out.printf("%14d", sf.get(i)); } System.out.println("\n\nNumber of square-free integers:\n"); long[] tos = {100, 1000, 10000, 100000, 1000000}; for (long to : tos) { System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size()); } } }
Port the provided C code into Java while preserving the original functionality.
#include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #define TRUE 1 #define FALSE 0 #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) double jaro(const char *str1, const char *str2) { int str1_len = strlen(str1); int str2_len = strlen(str2); if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0; int match_distance = (int) max(str1_len, str2_len)/2 - 1; int *str1_matches = calloc(str1_len, sizeof(int)); int *str2_matches = calloc(str2_len, sizeof(int)); double matches = 0.0; double transpositions = 0.0; for (int i = 0; i < str1_len; i++) { int start = max(0, i - match_distance); int end = min(i + match_distance + 1, str2_len); for (int k = start; k < end; k++) { if (str2_matches[k]) continue; if (str1[i] != str2[k]) continue; str1_matches[i] = TRUE; str2_matches[k] = TRUE; matches++; break; } } if (matches == 0) { free(str1_matches); free(str2_matches); return 0.0; } int k = 0; for (int i = 0; i < str1_len; i++) { if (!str1_matches[i]) continue; while (!str2_matches[k]) k++; if (str1[i] != str2[k]) transpositions++; k++; } transpositions /= 2.0; free(str1_matches); free(str2_matches); return ((matches / str1_len) + (matches / str2_len) + ((matches - transpositions) / matches)) / 3.0; } int main() { printf("%f\n", jaro("MARTHA", "MARHTA")); printf("%f\n", jaro("DIXON", "DICKSONX")); printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")); }
public class JaroDistance { public static double jaro(String s, String t) { int s_len = s.length(); int t_len = t.length(); if (s_len == 0 && t_len == 0) return 1; int match_distance = Integer.max(s_len, t_len) / 2 - 1; boolean[] s_matches = new boolean[s_len]; boolean[] t_matches = new boolean[t_len]; int matches = 0; int transpositions = 0; for (int i = 0; i < s_len; i++) { int start = Integer.max(0, i-match_distance); int end = Integer.min(i+match_distance+1, t_len); for (int j = start; j < end; j++) { if (t_matches[j]) continue; if (s.charAt(i) != t.charAt(j)) continue; s_matches[i] = true; t_matches[j] = true; matches++; break; } } if (matches == 0) return 0; int k = 0; for (int i = 0; i < s_len; i++) { if (!s_matches[i]) continue; while (!t_matches[k]) k++; if (s.charAt(i) != t.charAt(k)) transpositions++; k++; } return (((double)matches / s_len) + ((double)matches / t_len) + (((double)matches - transpositions/2.0) / matches)) / 3.0; } public static void main(String[] args) { System.out.println(jaro( "MARTHA", "MARHTA")); System.out.println(jaro( "DIXON", "DICKSONX")); System.out.println(jaro("JELLYFISH", "SMELLYFISH")); } }
Convert this C block to Java, preserving its control flow and logic.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct node_t { int x, y; struct node_t *prev, *next; } node; node *new_node(int x, int y) { node *n = malloc(sizeof(node)); n->x = x; n->y = y; n->next = NULL; n->prev = NULL; return n; } void free_node(node **n) { if (n == NULL) { return; } (*n)->prev = NULL; (*n)->next = NULL; free(*n); *n = NULL; } typedef struct list_t { node *head; node *tail; } list; list make_list() { list lst = { NULL, NULL }; return lst; } void append_node(list *const lst, int x, int y) { if (lst == NULL) { return; } node *n = new_node(x, y); if (lst->head == NULL) { lst->head = n; lst->tail = n; } else { n->prev = lst->tail; lst->tail->next = n; lst->tail = n; } } void remove_node(list *const lst, const node *const n) { if (lst == NULL || n == NULL) { return; } if (n->prev != NULL) { n->prev->next = n->next; if (n->next != NULL) { n->next->prev = n->prev; } else { lst->tail = n->prev; } } else { if (n->next != NULL) { n->next->prev = NULL; lst->head = n->next; } } free_node(&n); } void free_list(list *const lst) { node *ptr; if (lst == NULL) { return; } ptr = lst->head; while (ptr != NULL) { node *nxt = ptr->next; free_node(&ptr); ptr = nxt; } lst->head = NULL; lst->tail = NULL; } void print_list(const list *lst) { node *it; if (lst == NULL) { return; } for (it = lst->head; it != NULL; it = it->next) { int sum = it->x + it->y; int prod = it->x * it->y; printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod); } } void print_count(const list *const lst) { node *it; int c = 0; if (lst == NULL) { return; } for (it = lst->head; it != NULL; it = it->next) { c++; } if (c == 0) { printf("no candidates\n"); } else if (c == 1) { printf("one candidate\n"); } else { printf("%d candidates\n", c); } } void setup(list *const lst) { int x, y; if (lst == NULL) { return; } for (x = 2; x <= 98; x++) { for (y = x + 1; y <= 98; y++) { if (x + y <= 100) { append_node(lst, x, y); } } } } void remove_by_sum(list *const lst, const int sum) { node *it; if (lst == NULL) { return; } it = lst->head; while (it != NULL) { int s = it->x + it->y; if (s == sum) { remove_node(lst, it); it = lst->head; } else { it = it->next; } } } void remove_by_prod(list *const lst, const int prod) { node *it; if (lst == NULL) { return; } it = lst->head; while (it != NULL) { int p = it->x * it->y; if (p == prod) { remove_node(lst, it); it = lst->head; } else { it = it->next; } } } void statement1(list *const lst) { short *unique = calloc(100000, sizeof(short)); node *it, *nxt; for (it = lst->head; it != NULL; it = it->next) { int prod = it->x * it->y; unique[prod]++; } it = lst->head; while (it != NULL) { int prod = it->x * it->y; nxt = it->next; if (unique[prod] == 1) { remove_by_sum(lst, it->x + it->y); it = lst->head; } else { it = nxt; } } free(unique); } void statement2(list *const candidates) { short *unique = calloc(100000, sizeof(short)); node *it, *nxt; for (it = candidates->head; it != NULL; it = it->next) { int prod = it->x * it->y; unique[prod]++; } it = candidates->head; while (it != NULL) { int prod = it->x * it->y; nxt = it->next; if (unique[prod] > 1) { remove_by_prod(candidates, prod); it = candidates->head; } else { it = nxt; } } free(unique); } void statement3(list *const candidates) { short *unique = calloc(100, sizeof(short)); node *it, *nxt; for (it = candidates->head; it != NULL; it = it->next) { int sum = it->x + it->y; unique[sum]++; } it = candidates->head; while (it != NULL) { int sum = it->x + it->y; nxt = it->next; if (unique[sum] > 1) { remove_by_sum(candidates, sum); it = candidates->head; } else { it = nxt; } } free(unique); } int main() { list candidates = make_list(); setup(&candidates); print_count(&candidates); statement1(&candidates); print_count(&candidates); statement2(&candidates); print_count(&candidates); statement3(&candidates); print_count(&candidates); print_list(&candidates); free_list(&candidates); return 0; }
package org.rosettacode; import java.util.ArrayList; import java.util.List; public class SumAndProductPuzzle { private final long beginning; private final int maxSum; private static final int MIN_VALUE = 2; private List<int[]> firstConditionExcludes = new ArrayList<>(); private List<int[]> secondConditionExcludes = new ArrayList<>(); public static void main(String... args){ if (args.length == 0){ new SumAndProductPuzzle(100).run(); new SumAndProductPuzzle(1684).run(); new SumAndProductPuzzle(1685).run(); } else { for (String arg : args){ try{ new SumAndProductPuzzle(Integer.valueOf(arg)).run(); } catch (NumberFormatException e){ System.out.println("Please provide only integer arguments. " + "Provided argument " + arg + " was not an integer. " + "Alternatively, calling the program with no arguments " + "will run the puzzle where maximum sum equals 100, 1684, and 1865."); } } } } public SumAndProductPuzzle(int maxSum){ this.beginning = System.currentTimeMillis(); this.maxSum = maxSum; System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " started at " + String.valueOf(beginning) + "."); } public void run(){ for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){ for (int y = x + 1; y < maxSum - MIN_VALUE; y++){ if (isSumNoGreaterThanMax(x,y) && isSKnowsPCannotKnow(x,y) && isPKnowsNow(x,y) && isSKnowsNow(x,y) ){ System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) + " in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } } } System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } public boolean isSumNoGreaterThanMax(int x, int y){ return x + y <= maxSum; } public boolean isSKnowsPCannotKnow(int x, int y){ if (firstConditionExcludes.contains(new int[] {x, y})){ return false; } for (int[] addends : sumAddends(x, y)){ if ( !(productFactors(addends[0], addends[1]).size() > 1) ) { firstConditionExcludes.add(new int[] {x, y}); return false; } } return true; } public boolean isPKnowsNow(int x, int y){ if (secondConditionExcludes.contains(new int[] {x, y})){ return false; } int countSolutions = 0; for (int[] factors : productFactors(x, y)){ if (isSKnowsPCannotKnow(factors[0], factors[1])){ countSolutions++; } } if (countSolutions == 1){ return true; } else { secondConditionExcludes.add(new int[] {x, y}); return false; } } public boolean isSKnowsNow(int x, int y){ int countSolutions = 0; for (int[] addends : sumAddends(x, y)){ if (isPKnowsNow(addends[0], addends[1])){ countSolutions++; } } return countSolutions == 1; } public List<int[]> sumAddends(int x, int y){ List<int[]> list = new ArrayList<>(); int sum = x + y; for (int addend = MIN_VALUE; addend < sum - addend; addend++){ if (isSumNoGreaterThanMax(addend, sum - addend)){ list.add(new int[]{addend, sum - addend}); } } return list; } public List<int[]> productFactors(int x, int y){ List<int[]> list = new ArrayList<>(); int product = x * y; for (int factor = MIN_VALUE; factor < product / factor; factor++){ if (product % factor == 0){ if (isSumNoGreaterThanMax(factor, product / factor)){ list.add(new int[]{factor, product / factor}); } } } return list; } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { int i; printf("Base %2d:", base); for (i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { int *cnt = calloc(base, sizeof(int)); int i, minTurn, maxTurn, portion; if (NULL == cnt) { printf("Failed to allocate space to determine the spread of turns.\n"); return; } for (i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } minTurn = INT_MAX; maxTurn = INT_MIN; portion = 0; for (i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } free(cnt); } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } } private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) { sum += n % base; n /= base; } sequence.add(sum % base); } return sequence; } }
Convert this C block to Java, preserving its control flow and logic.
#include <sys/types.h> #include <regex.h> #include <stdio.h> typedef struct { const char *s; int len, prec, assoc; } str_tok_t; typedef struct { const char * str; int assoc, prec; regex_t re; } pat_t; enum assoc { A_NONE, A_L, A_R }; pat_t pat_eos = {"", A_NONE, 0}; pat_t pat_ops[] = { {"^\\)", A_NONE, -1}, {"^\\*\\*", A_R, 3}, {"^\\^", A_R, 3}, {"^\\*", A_L, 2}, {"^/", A_L, 2}, {"^\\+", A_L, 1}, {"^-", A_L, 1}, {0} }; pat_t pat_arg[] = { {"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"}, {"^[a-zA-Z_][a-zA-Z_0-9]*"}, {"^\\(", A_L, -1}, {0} }; str_tok_t stack[256]; str_tok_t queue[256]; int l_queue, l_stack; #define qpush(x) queue[l_queue++] = x #define spush(x) stack[l_stack++] = x #define spop() stack[--l_stack] void display(const char *s) { int i; printf("\033[1;1H\033[JText | %s", s); printf("\nStack| "); for (i = 0; i < l_stack; i++) printf("%.*s ", stack[i].len, stack[i].s); printf("\nQueue| "); for (i = 0; i < l_queue; i++) printf("%.*s ", queue[i].len, queue[i].s); puts("\n\n<press enter>"); getchar(); } int prec_booster; #define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;} int init(void) { int i; pat_t *p; for (i = 0, p = pat_ops; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); for (i = 0, p = pat_arg; p[i].str; i++) if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED)) fail("comp", p[i].str); return 1; } pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e) { int i; regmatch_t m; while (*s == ' ') s++; *e = s; if (!*s) return &pat_eos; for (i = 0; p[i].str; i++) { if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL)) continue; t->s = s; *e = s + (t->len = m.rm_eo - m.rm_so); return p + i; } return 0; } int parse(const char *s) { pat_t *p; str_tok_t *t, tok; prec_booster = l_queue = l_stack = 0; display(s); while (*s) { p = match(s, pat_arg, &tok, &s); if (!p || p == &pat_eos) fail("parse arg", s); if (p->prec == -1) { prec_booster += 100; continue; } qpush(tok); display(s); re_op: p = match(s, pat_ops, &tok, &s); if (!p) fail("parse op", s); tok.assoc = p->assoc; tok.prec = p->prec; if (p->prec > 0) tok.prec = p->prec + prec_booster; else if (p->prec == -1) { if (prec_booster < 100) fail("unmatched )", s); tok.prec = prec_booster; } while (l_stack) { t = stack + l_stack - 1; if (!(t->prec == tok.prec && t->assoc == A_L) && t->prec <= tok.prec) break; qpush(spop()); display(s); } if (p->prec == -1) { prec_booster -= 100; goto re_op; } if (!p->prec) { display(s); if (prec_booster) fail("unmatched (", s); return 1; } spush(tok); display(s); } if (p->prec > 0) fail("unexpected eol", s); return 1; } int main() { int i; const char *tests[] = { "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3", "123", "3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14", "(((((((1+2+3**(4 + 5))))))", "a^(b + c/d * .1e5)!", "(1**2)**3", "2 + 2 *", 0 }; if (!init()) return 1; for (i = 0; tests[i]; i++) { printf("Testing string `%s' <enter>\n", tests[i]); getchar(); printf("string `%s': %s\n\n", tests[i], parse(tests[i]) ? "Ok" : "Error"); } return 0; }
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) sb.append(ops.charAt(s.pop())).append(' '); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); } else { sb.append(token).append(' '); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())).append(' '); return sb.toString(); } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <time.h> bool is_prime(unsigned int n) { assert(n < 64); static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0}; return isprime[n]; } void swap(unsigned int* a, size_t i, size_t j) { unsigned int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } bool prime_triangle_row(unsigned int* a, size_t length) { if (length == 2) return is_prime(a[0] + a[1]); for (size_t i = 1; i + 1 < length; i += 2) { if (is_prime(a[0] + a[i])) { swap(a, i, 1); if (prime_triangle_row(a + 1, length - 1)) return true; swap(a, i, 1); } } return false; } int prime_triangle_count(unsigned int* a, size_t length) { int count = 0; if (length == 2) { if (is_prime(a[0] + a[1])) ++count; } else { for (size_t i = 1; i + 1 < length; i += 2) { if (is_prime(a[0] + a[i])) { swap(a, i, 1); count += prime_triangle_count(a + 1, length - 1); swap(a, i, 1); } } } return count; } void print(unsigned int* a, size_t length) { if (length == 0) return; printf("%2u", a[0]); for (size_t i = 1; i < length; ++i) printf(" %2u", a[i]); printf("\n"); } int main() { clock_t start = clock(); for (unsigned int n = 2; n < 21; ++n) { unsigned int a[n]; for (unsigned int i = 0; i < n; ++i) a[i] = i + 1; if (prime_triangle_row(a, n)) print(a, n); } printf("\n"); for (unsigned int n = 2; n < 21; ++n) { unsigned int a[n]; for (unsigned int i = 0; i < n; ++i) a[i] = i + 1; if (n > 2) printf(" "); printf("%d", prime_triangle_count(a, n)); } printf("\n"); clock_t end = clock(); double duration = (end - start + 0.0) / CLOCKS_PER_SEC; printf("\nElapsed time: %f seconds\n", duration); return 0; }
public class PrimeTriangle { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i = 2; i <= 20; ++i) { int[] a = new int[i]; for (int j = 0; j < i; ++j) a[j] = j + 1; if (findRow(a, 0, i)) printRow(a); } System.out.println(); StringBuilder s = new StringBuilder(); for (int i = 2; i <= 20; ++i) { int[] a = new int[i]; for (int j = 0; j < i; ++j) a[j] = j + 1; if (i > 2) s.append(" "); s.append(countRows(a, 0, i)); } System.out.println(s); long finish = System.currentTimeMillis(); System.out.printf("\nElapsed time: %d milliseconds\n", finish - start); } private static void printRow(int[] a) { for (int i = 0; i < a.length; ++i) { if (i != 0) System.out.print(" "); System.out.printf("%2d", a[i]); } System.out.println(); } private static boolean findRow(int[] a, int start, int length) { if (length == 2) return isPrime(a[start] + a[start + 1]); for (int i = 1; i + 1 < length; i += 2) { if (isPrime(a[start] + a[start + i])) { swap(a, start + i, start + 1); if (findRow(a, start + 1, length - 1)) return true; swap(a, start + i, start + 1); } } return false; } private static int countRows(int[] a, int start, int length) { int count = 0; if (length == 2) { if (isPrime(a[start] + a[start + 1])) ++count; } else { for (int i = 1; i + 1 < length; i += 2) { if (isPrime(a[start] + a[start + i])) { swap(a, start + i, start + 1); count += countRows(a, start + 1, length - 1); swap(a, start + i, start + 1); } } } return count; } private static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } private static boolean isPrime(int n) { return ((1L << n) & 0x28208a20a08a28acL) != 0; } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include<math.h> #include<stdio.h> int main () { double inputs[11], check = 400, result; int i; printf ("\nPlease enter 11 numbers :"); for (i = 0; i < 11; i++) { scanf ("%lf", &inputs[i]); } printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"); for (i = 10; i >= 0; i--) { result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3); printf ("\nf(%lf) = "); if (result > check) { printf ("Overflow!"); } else { printf ("%lf", result); } } return 0; }
import java.util.*; import java.io.*; public class TPKA { public static void main(String... args) { double[] input = new double[11]; double userInput = 0.0; Scanner in = new Scanner(System.in); for(int i = 0; i < 11; i++) { System.out.print("Please enter a number: "); String s = in.nextLine(); try { userInput = Double.parseDouble(s); } catch (NumberFormatException e) { System.out.println("You entered invalid input, exiting"); System.exit(1); } input[i] = userInput; } for(int j = 10; j >= 0; j--) { double x = input[j]; double y = f(x); if( y < 400.0) { System.out.printf("f( %.2f ) = %.2f\n", x, y); } else { System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE"); } } } private static double f(double x) { return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3))); } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> char * mid3(int n) { static char buf[32]; int l; sprintf(buf, "%d", n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; } int main(void) { int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, 1234567890}; int i; char *m; for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) { if (!(m = mid3(x[i]))) m = "error"; printf("%d: %s\n", x[i], m); } return 0; }
public class MiddleThreeDigits { public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE}; final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}; for (long n : passing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); for (int n : failing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); } public static <T> String middleThreeDigits(T n) { String s = String.valueOf(n); if (s.charAt(0) == '-') s = s.substring(1); int len = s.length(); if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; int mid = len / 2; return s.substring(mid - 1, mid + 2); } }
Write the same algorithm in Java as shown in this C implementation.
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #define LIMIT 15 int smallPrimes[LIMIT]; static void sieve() { int i = 2, j; int p = 5; smallPrimes[0] = 2; smallPrimes[1] = 3; while (i < LIMIT) { for (j = 0; j < i; j++) { if (smallPrimes[j] * smallPrimes[j] <= p) { if (p % smallPrimes[j] == 0) { p += 2; break; } } else { smallPrimes[i++] = p; p += 2; break; } } } } static bool is_prime(uint64_t n) { uint64_t i; for (i = 0; i < LIMIT; i++) { if (n % smallPrimes[i] == 0) { return n == smallPrimes[i]; } } i = smallPrimes[LIMIT - 1] + 2; for (; i * i <= n; i += 2) { if (n % i == 0) { return false; } } return true; } static uint64_t divisor_count(uint64_t n) { uint64_t count = 1; uint64_t d; while (n % 2 == 0) { n /= 2; count++; } for (d = 3; d * d <= n; d += 2) { uint64_t q = n / d; uint64_t r = n % d; uint64_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { return count *= 2; } return count; } static uint64_t OEISA073916(size_t n) { uint64_t count = 0; uint64_t result = 0; size_t i; if (is_prime(n)) { return (uint64_t)pow(smallPrimes[n - 1], n - 1); } for (i = 1; count < n; i++) { if (n % 2 == 1) { uint64_t root = (uint64_t)sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { size_t n; sieve(); for (n = 1; n <= LIMIT; n++) { if (n == 13) { printf("A073916(%lu) = One more bit needed to represent result.\n", n); } else { printf("A073916(%lu) = %llu\n", n, OEISA073916(n)); } } return 0; }
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class SequenceNthNumberWithExactlyNDivisors { public static void main(String[] args) { int max = 45; smallPrimes(max); for ( int n = 1; n <= max ; n++ ) { System.out.printf("A073916(%d) = %s%n", n, OEISA073916(n)); } } private static List<Integer> smallPrimes = new ArrayList<>(); private static void smallPrimes(int numPrimes) { smallPrimes.add(2); for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) { if ( isPrime(n) ) { smallPrimes.add(n); count++; } } } private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) { return false; } for ( long d = 3 ; d*d <= test ; d += 2 ) { if ( test % d == 0 ) { return false; } } return true; } private static int getDivisorCount(long n) { int count = 1; while ( n % 2 == 0 ) { n /= 2; count += 1; } for ( long d = 3 ; d*d <= n ; d += 2 ) { long q = n / d; long r = n % d; int dc = 0; while ( r == 0 ) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if ( n != 1 ) { count *= 2; } return count; } private static BigInteger OEISA073916(int n) { if ( isPrime(n) ) { return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1); } int count = 0; int result = 0; for ( int i = 1 ; count < n ; i++ ) { if ( n % 2 == 1 ) { int sqrt = (int) Math.sqrt(i); if ( sqrt*sqrt != i ) { continue; } } if ( getDivisorCount(i) == n ) { count++; result = i; } } return BigInteger.valueOf(result); } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <stdio.h> #define MAX 15 int count_divisors(int n) { int i, count = 0; for (i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; printf("The first %d terms of the sequence are:\n", MAX); for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) printf("%d ", seq[i]); printf("\n"); return 0; }
import java.util.Arrays; public class OEIS_A005179 { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; int[] seq = new int[max]; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, n = 0; n < max; ++i) { int k = count_divisors(i); if (k <= max && seq[k - 1] == 0) { seq[k- 1] = i; n++; } } System.out.println(Arrays.toString(seq)); } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include <stdio.h> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { int i, j; for (i = 0; i < 4; i++) { for (j = 1; j < 6; j++) { int n = i * 5 + j; printf("p(%2d) = %2d ", n, pancake(n)); } printf("\n"); } return 0; }
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; } public static void main(String[] args) { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = 5 * i + j; System.out.printf("p(%2d) = %2d ", n, pancake(n)); } System.out.println(); } } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <time.h> #define TRUE 1 #define FALSE 0 typedef int bool; char grid[8][8]; void placeKings() { int r1, r2, c1, c2; for (;;) { r1 = rand() % 8; c1 = rand() % 8; r2 = rand() % 8; c2 = rand() % 8; if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) { grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; return; } } } void placePieces(const char *pieces, bool isPawn) { int n, r, c; int numToPlace = rand() % strlen(pieces); for (n = 0; n < numToPlace; ++n) { do { r = rand() % 8; c = rand() % 8; } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces[n]; } } void toFen() { char fen[80], ch; int r, c, countEmpty = 0, index = 0; for (r = 0; r < 8; ++r) { for (c = 0; c < 8; ++c) { ch = grid[r][c]; printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++] = ch; } } if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++]= '/'; printf("\n"); } strcpy(fen + index, " w - - 0 1"); printf("%s\n", fen); } char *createFen() { placeKings(); placePieces("PPPPPPPP", TRUE); placePieces("pppppppp", TRUE); placePieces("RNBQBNR", FALSE); placePieces("rnbqbnr", FALSE); toFen(); } int main() { srand(time(NULL)); createFen(); return 0; }
import static java.lang.Math.abs; import java.util.Random; public class Fen { static Random rand = new Random(); public static void main(String[] args) { System.out.println(createFen()); } static String createFen() { char[][] grid = new char[8][8]; placeKings(grid); placePieces(grid, "PPPPPPPP", true); placePieces(grid, "pppppppp", true); placePieces(grid, "RNBQBNR", false); placePieces(grid, "rnbqbnr", false); return toFen(grid); } static void placeKings(char[][] grid) { int r1, c1, r2, c2; while (true) { r1 = rand.nextInt(8); c1 = rand.nextInt(8); r2 = rand.nextInt(8); c2 = rand.nextInt(8); if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) break; } grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; } static void placePieces(char[][] grid, String pieces, boolean isPawn) { int numToPlace = rand.nextInt(pieces.length()); for (int n = 0; n < numToPlace; n++) { int r, c; do { r = rand.nextInt(8); c = rand.nextInt(8); } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces.charAt(n); } } static String toFen(char[][] grid) { StringBuilder fen = new StringBuilder(); int countEmpty = 0; for (int r = 0; r < 8; r++) { for (int c = 0; c < 8; c++) { char ch = grid[r][c]; System.out.printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append(ch); } } if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append("/"); System.out.println(); } return fen.append(" w - - 0 1").toString(); } }
Keep all operations the same but rewrite the snippet in Java.
#include <stdio.h> #include <string.h> #include <locale.h> typedef int bool; typedef unsigned long long ull; #define TRUE 1 #define FALSE 0 char as_digit(int d) { return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a'; } void revstr(char *str) { int i, len = strlen(str); char t; for (i = 0; i < len/2; ++i) { t = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = t; } } char* to_base(char s[], ull n, int b) { int i = 0; while (n) { s[i++] = as_digit(n % b); n /= b; } s[i] = '\0'; revstr(s); return s; } ull uabs(ull a, ull b) { return a > b ? a - b : b - a; } bool is_esthetic(ull n, int b) { int i, j; if (!n) return FALSE; i = n % b; n /= b; while (n) { j = n % b; if (uabs(i, j) != 1) return FALSE; n /= b; i = j; } return TRUE; } ull esths[45000]; int le = 0; void dfs(ull n, ull m, ull i) { ull d, i1, i2; if (i >= n && i <= m) esths[le++] = i; if (i == 0 || i > m) return; d = i % 10; i1 = i * 10 + d - 1; i2 = i1 + 2; if (d == 0) { dfs(n, m, i2); } else if (d == 9) { dfs(n, m, i1); } else { dfs(n, m, i1); dfs(n, m, i2); } } void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) { int i; le = 0; for (i = 0; i < 10; ++i) { dfs(n2, m2, i); } printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m); if (all) { for (i = 0; i < le; ++i) { printf("%llu ", esths[i]); if (!(i+1)%per_line) printf("\n"); } } else { for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]); printf("\n............\n"); for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]); } printf("\n\n"); } int main() { ull n; int b, c; char ch[15] = {0}; for (b = 2; b <= 16; ++b) { printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b); for (n = 1, c = 0; c < 6 * b; ++n) { if (is_esthetic(n, b)) { if (++c >= 4 * b) printf("%s ", to_base(ch, n, b)); } } printf("\n\n"); } char *oldLocale = setlocale(LC_NUMERIC, NULL); setlocale(LC_NUMERIC, ""); list_esths(1000, 1010, 9999, 9898, 16, TRUE); list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE); list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE); list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE); list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE); setlocale(LC_NUMERIC, oldLocale); return 0; }
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream; public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); } private static boolean isEsthetic(long n, long b) { if (n == 0) { return false; } var i = n % b; var n2 = n / b; while (n2 > 0) { var j = n2 % b; if (Math.abs(i - j) != 1) { return false; } n2 /= b; i = j; } return true; } private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) { var esths = new ArrayList<Long>(); var dfs = new RecTriConsumer<Long, Long, Long>() { public void accept(Long n, Long m, Long i) { accept(this, n, m, i); } @Override public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) { if (n <= i && i <= m) { esths.add(i); } if (i == 0 || i > m) { return; } var d = i % 10; var i1 = i * 10 + d - 1; var i2 = i1 + 2; if (d == 0) { f.accept(f, n, m, i2); } else if (d == 9) { f.accept(f, n, m, i1); } else { f.accept(f, n, m, i1); f.accept(f, n, m, i2); } } }; LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i)); var le = esths.size(); System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m); if (all) { for (int i = 0; i < esths.size(); i++) { System.out.printf("%d ", esths.get(i)); if ((i + 1) % perLine == 0) { System.out.println(); } } } else { for (int i = 0; i < perLine; i++) { System.out.printf("%d ", esths.get(i)); } System.out.println(); System.out.println("............"); for (int i = le - perLine; i < le; i++) { System.out.printf("%d ", esths.get(i)); } } System.out.println(); System.out.println(); } public static void main(String[] args) { IntStream.rangeClosed(2, 16).forEach(b -> { System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b); var n = 1L; var c = 0L; while (c < 6 * b) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { System.out.printf("%s ", Long.toString(n, b)); } } n++; } System.out.println(); }); System.out.println(); listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true); listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false); listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false); listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false); } }
Generate a Java translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <string.h> typedef struct { char v[16]; } deck; typedef unsigned int uint; uint n, d, best[16]; void tryswaps(deck *a, uint f, uint s) { # define A a->v # define B b.v if (d > best[n]) best[n] = d; while (1) { if ((A[s] == s || (A[s] == -1 && !(f & 1U << s))) && (d + best[s] >= best[n] || A[s] == -1)) break; if (d + best[s] <= best[n]) return; if (!--s) return; } d++; deck b = *a; for (uint i = 1, k = 2; i <= s; k <<= 1, i++) { if (A[i] != i && (A[i] != -1 || (f & k))) continue; for (uint j = B[0] = i; j--;) B[i - j] = A[j]; tryswaps(&b, f | k, s); } d--; } int main(void) { deck x; memset(&x, -1, sizeof(x)); x.v[0] = 0; for (n = 1; n < 13; n++) { tryswaps(&x, 1, n - 1); printf("%2d: %d\n", n, best[n]); } return 0; }
public class Topswops { static final int maxBest = 32; static int[] best; static private void trySwaps(int[] deck, int f, int d, int n) { if (d > best[n]) best[n] = d; for (int i = n - 1; i >= 0; i--) { if (deck[i] == -1 || deck[i] == i) break; if (d + best[i] <= best[n]) return; } int[] deck2 = deck.clone(); for (int i = 1; i < n; i++) { final int k = 1 << i; if (deck2[i] == -1) { if ((f & k) != 0) continue; } else if (deck2[i] != i) continue; deck2[0] = i; for (int j = i - 1; j >= 0; j--) deck2[i - j] = deck[j]; trySwaps(deck2, f | k, d + 1, n); } } static int topswops(int n) { assert(n > 0 && n < maxBest); best[n] = 0; int[] deck0 = new int[n + 1]; for (int i = 1; i < n; i++) deck0[i] = -1; trySwaps(deck0, 1, 0, n); return best[n]; } public static void main(String[] args) { best = new int[maxBest]; for (int i = 1; i < 11; i++) System.out.println(i + ": " + topswops(i)); } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include<string.h> #include<stdlib.h> #include<ctype.h> #include<stdio.h> #define UNITS_LENGTH 13 int main(int argC,char* argV[]) { int i,reference; char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"}; double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6}; if(argC!=3) printf("Usage : %s followed by length as <value> <unit>"); else{ for(i=0;argV[2][i]!=00;i++) argV[2][i] = tolower(argV[2][i]); for(i=0;i<UNITS_LENGTH;i++){ if(strstr(argV[2],units[i])!=NULL){ reference = i; factor = atof(argV[1])*values[i]; break; } } printf("%s %s is equal in length to : \n",argV[1],argV[2]); for(i=0;i<UNITS_LENGTH;i++){ if(i!=reference) printf("\n%lf %s",factor/values[i],units[i]); } } return 0; }
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0, 1066.8, 7467.6}; public static void main(String[] a) { if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) { double inputVal = lookup(a[1]); if (!Double.isNaN(inputVal)) { double magnitude = Double.parseDouble(a[0]); double meters = magnitude * inputVal; System.out.printf("%s %s to: %n%n", a[0], a[1]); for (String k: keys) System.out.printf("%10s: %g%n", k, meters / lookup(k)); return; } } System.out.println("Please provide a number and unit"); } public static double lookup(String key) { for (int i = 0; i < keys.length; i++) if (keys[i].equals(key)) return values[i]; return Double.NaN; } }
Change the programming language of this snippet from C to Java without modifying what it does.
#include<string.h> #include<stdlib.h> #include<ctype.h> #include<stdio.h> #define UNITS_LENGTH 13 int main(int argC,char* argV[]) { int i,reference; char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"}; double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6}; if(argC!=3) printf("Usage : %s followed by length as <value> <unit>"); else{ for(i=0;argV[2][i]!=00;i++) argV[2][i] = tolower(argV[2][i]); for(i=0;i<UNITS_LENGTH;i++){ if(strstr(argV[2],units[i])!=NULL){ reference = i; factor = atof(argV[1])*values[i]; break; } } printf("%s %s is equal in length to : \n",argV[1],argV[2]); for(i=0;i<UNITS_LENGTH;i++){ if(i!=reference) printf("\n%lf %s",factor/values[i],units[i]); } } return 0; }
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0, 1066.8, 7467.6}; public static void main(String[] a) { if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) { double inputVal = lookup(a[1]); if (!Double.isNaN(inputVal)) { double magnitude = Double.parseDouble(a[0]); double meters = magnitude * inputVal; System.out.printf("%s %s to: %n%n", a[0], a[1]); for (String k: keys) System.out.printf("%10s: %g%n", k, meters / lookup(k)); return; } } System.out.println("Please provide a number and unit"); } public static double lookup(String key) { for (int i = 0; i < keys.length; i++) if (keys[i].equals(key)) return values[i]; return Double.NaN; } }