Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <time.h> struct rate_state_s { time_t lastFlush; time_t period; size_t tickCount; }; void tic_rate(struct rate_state_s* pRate) { pRate->tickCount += 1; time_t now = time(NULL); if((now - pRate->lastFlush) >= pRate->period) { size_t tps = 0.0; if(pRate->tickCount > 0) tps = pRate->tickCount / (now - pRate->lastFlush); printf("%u tics per second.\n", tps); pRate->tickCount = 0; pRate->lastFlush = now; } } void something_we_do() { volatile size_t anchor = 0; size_t x = 0; for(x = 0; x < 0xffff; ++x) { anchor = x; } } int main() { time_t start = time(NULL); struct rate_state_s rateWatch; rateWatch.lastFlush = start; rateWatch.tickCount = 0; rateWatch.period = 5; time_t latest = start; for(latest = start; (latest - start) < 20; latest = time(NULL)) { something_we_do(); tic_rate(&rateWatch); } return 0; }
import java.util.function.Consumer; public class RateCounter { public static void main(String[] args) { for (double d : benchmark(10, x -> System.out.print(""), 10)) System.out.println(d); } static double[] benchmark(int n, Consumer<Integer> f, int arg) { double[] timings = new double[n]; for (int i = 0; i < n; i++) { long time = System.nanoTime(); f.accept(arg); timings[i] = System.nanoTime() - time; } return timings; } }
Rewrite the snippet below in Java so it works the same as the original C code.
#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, next = 1; printf("The first %d terms of the sequence are:\n", MAX); for (i = 1; next <= MAX; ++i) { if (next == count_divisors(i)) { printf("%d ", i); next++; } } printf("\n"); return 0; }
public class AntiPrimesPlus { 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; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, next = 1; next <= max; ++i) { if (next == count_divisors(i)) { System.out.printf("%d ", i); next++; } } System.out.println(); } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct{ double x,y; }point; void pythagorasTree(point a,point b,int times){ point c,d,e; c.x = b.x - (a.y - b.y); c.y = b.y - (b.x - a.x); d.x = a.x - (a.y - b.y); d.y = a.y - (b.x - a.x); e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2; e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2; if(times>0){ setcolor(rand()%15 + 1); line(a.x,a.y,b.x,b.y); line(c.x,c.y,b.x,b.y); line(c.x,c.y,d.x,d.y); line(a.x,a.y,d.x,d.y); pythagorasTree(d,e,times-1); pythagorasTree(e,c,times-1); } } int main(){ point a,b; double side; int iter; time_t t; printf("Enter initial side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); scanf("%d",&iter); a.x = 6*side/2 - side/2; a.y = 4*side; b.x = 6*side/2 + side/2; b.y = 4*side; initwindow(6*side,4*side,"Pythagoras Tree ?"); srand((unsigned)time(&t)); pythagorasTree(a,b,iter); getch(); closegraph(); return 0; }
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class PythagorasTree extends JPanel { final int depthLimit = 7; float hue = 0.15f; public PythagorasTree() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2, int depth) { if (depth == depthLimit) return; float dx = x2 - x1; float dy = y1 - y2; float x3 = x2 - dy; float y3 = y2 - dx; float x4 = x1 - dy; float y4 = y1 - dx; float x5 = x4 + 0.5F * (dx - dy); float y5 = y4 - 0.5F * (dx + dy); Path2D square = new Path2D.Float(); square.moveTo(x1, y1); square.lineTo(x2, y2); square.lineTo(x3, y3); square.lineTo(x4, y4); square.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1)); g.fill(square); g.setColor(Color.lightGray); g.draw(square); Path2D triangle = new Path2D.Float(); triangle.moveTo(x3, y3); triangle.lineTo(x4, y4); triangle.lineTo(x5, y5); triangle.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1)); g.fill(triangle); g.setColor(Color.lightGray); g.draw(triangle); drawTree(g, x4, y4, x5, y5, depth + 1); drawTree(g, x5, y5, x3, y3, depth + 1); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); drawTree((Graphics2D) g, 275, 500, 375, 500, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pythagoras Tree"); f.setResizable(false); f.add(new PythagorasTree(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Port the following code from C to Java with equivalent syntax and logic.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct{ double x,y; }point; void pythagorasTree(point a,point b,int times){ point c,d,e; c.x = b.x - (a.y - b.y); c.y = b.y - (b.x - a.x); d.x = a.x - (a.y - b.y); d.y = a.y - (b.x - a.x); e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2; e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2; if(times>0){ setcolor(rand()%15 + 1); line(a.x,a.y,b.x,b.y); line(c.x,c.y,b.x,b.y); line(c.x,c.y,d.x,d.y); line(a.x,a.y,d.x,d.y); pythagorasTree(d,e,times-1); pythagorasTree(e,c,times-1); } } int main(){ point a,b; double side; int iter; time_t t; printf("Enter initial side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); scanf("%d",&iter); a.x = 6*side/2 - side/2; a.y = 4*side; b.x = 6*side/2 + side/2; b.y = 4*side; initwindow(6*side,4*side,"Pythagoras Tree ?"); srand((unsigned)time(&t)); pythagorasTree(a,b,iter); getch(); closegraph(); return 0; }
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class PythagorasTree extends JPanel { final int depthLimit = 7; float hue = 0.15f; public PythagorasTree() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2, int depth) { if (depth == depthLimit) return; float dx = x2 - x1; float dy = y1 - y2; float x3 = x2 - dy; float y3 = y2 - dx; float x4 = x1 - dy; float y4 = y1 - dx; float x5 = x4 + 0.5F * (dx - dy); float y5 = y4 - 0.5F * (dx + dy); Path2D square = new Path2D.Float(); square.moveTo(x1, y1); square.lineTo(x2, y2); square.lineTo(x3, y3); square.lineTo(x4, y4); square.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1)); g.fill(square); g.setColor(Color.lightGray); g.draw(square); Path2D triangle = new Path2D.Float(); triangle.moveTo(x3, y3); triangle.lineTo(x4, y4); triangle.lineTo(x5, y5); triangle.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1)); g.fill(triangle); g.setColor(Color.lightGray); g.draw(triangle); drawTree(g, x4, y4, x5, y5, depth + 1); drawTree(g, x5, y5, x3, y3, depth + 1); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); drawTree((Graphics2D) g, 275, 500, 375, 500, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pythagoras Tree"); f.setResizable(false); f.add(new PythagorasTree(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdio.h> #include <ctype.h> static int owp(int odd) { int ch, ret; ch = getc(stdin); if (!odd) { putc(ch, stdout); if (ch == EOF || ch == '.') return EOF; if (ispunct(ch)) return 0; owp(odd); return 0; } else { if (ispunct(ch)) return ch; ret = owp(odd); putc(ch, stdout); return ret; } } int main(int argc, char **argv) { int ch = 1; while ((ch = owp(!ch)) != EOF) { if (ch) putc(ch, stdout); if (ch == '.') break; } return 0; }
public class OddWord { interface CharHandler { CharHandler handle(char c) throws Exception; } final CharHandler fwd = new CharHandler() { public CharHandler handle(char c) { System.out.print(c); return (Character.isLetter(c) ? fwd : rev); } }; class Reverser extends Thread implements CharHandler { Reverser() { setDaemon(true); start(); } private Character ch; private char recur() throws Exception { notify(); while (ch == null) wait(); char c = ch, ret = c; ch = null; if (Character.isLetter(c)) { ret = recur(); System.out.print(c); } return ret; } public synchronized void run() { try { while (true) { System.out.print(recur()); notify(); } } catch (Exception e) {} } public synchronized CharHandler handle(char c) throws Exception { while (ch != null) wait(); ch = c; notify(); while (ch != null) wait(); return (Character.isLetter(c) ? rev : fwd); } } final CharHandler rev = new Reverser(); public void loop() throws Exception { CharHandler handler = fwd; int c; while ((c = System.in.read()) >= 0) { handler = handler.handle((char) c); } } public static void main(String[] args) throws Exception { new OddWord().loop(); } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <math.h> #include <stdio.h> #include <stdint.h> int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } const static int64_t a1[3] = { 0, 1403580, -810728 }; const static int64_t m1 = (1LL << 32) - 209; const static int64_t a2[3] = { 527612, 0, -1370589 }; const static int64_t m2 = (1LL << 32) - 22853; const static int64_t d = (1LL << 32) - 209 + 1; static int64_t x1[3]; static int64_t x2[3]; void seed(int64_t seed_state) { x1[0] = seed_state; x1[1] = 0; x1[2] = 0; x2[0] = seed_state; x2[1] = 0; x2[2] = 0; } int64_t next_int() { int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); int64_t z = mod(x1i - x2i, m1); x1[2] = x1[1]; x1[1] = x1[0]; x1[0] = x1i; x2[2] = x2[1]; x2[1] = x2[0]; x2[0] = x2i; return z + 1; } double next_float() { return (double)next_int() / d; } int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i; seed(1234567); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("%lld\n", next_int()); printf("\n"); seed(987654321); for (i = 0; i < 100000; i++) { int64_t value = floor(next_float() * 5); counts[value]++; } for (i = 0; i < 5; i++) { printf("%d: %d\n", i, counts[i]); } return 0; }
public class App { private static long mod(long x, long y) { long m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } public static class RNG { private final long[] a1 = {0, 1403580, -810728}; private static final long m1 = (1L << 32) - 209; private long[] x1; private final long[] a2 = {527612, 0, -1370589}; private static final long m2 = (1L << 32) - 22853; private long[] x2; private static final long d = m1 + 1; public void seed(long state) { x1 = new long[]{state, 0, 0}; x2 = new long[]{state, 0, 0}; } public long nextInt() { long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1); long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2); long z = mod(x1i - x2i, m1); x1 = new long[]{x1i, x1[0], x1[1]}; x2 = new long[]{x2i, x2[0], x2[1]}; return z + 1; } public double nextFloat() { return 1.0 * nextInt() / d; } } public static void main(String[] args) { RNG rng = new RNG(); rng.seed(1234567); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; rng.seed(987654321); for (int i = 0; i < 100_000; i++) { int value = (int) Math.floor(rng.nextFloat() * 5.0); counts[value]++; } for (int i = 0; i < counts.length; i++) { System.out.printf("%d: %d%n", i, counts[i]); } } }
Write the same algorithm in Java as shown in this C implementation.
#include <locale.h> #include <stdbool.h> #include <stdio.h> #include <time.h> bool colorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[10] = {}; int digits[8] = {}; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[36] = {}; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } static int count[8]; static bool used[10]; static int largest = 0; void count_colorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; count_colorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (colorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; count_colorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } int main() { setlocale(LC_ALL, ""); clock_t start = clock(); printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (colorful(n)) printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } count_colorful(0, 0, 0); printf("\n\nLargest colorful number: %'d\n", largest); printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { printf("%d  %'d\n", d + 1, count[d]); total += count[d]; } printf("\nTotal: %'d\n", total); clock_t end = clock(); printf("\nElapsed time: %f seconds\n", (end - start + 0.0) / CLOCKS_PER_SEC); return 0; }
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (isColorful(n)) System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } ColorfulNumbers c = new ColorfulNumbers(); System.out.printf("\n\nLargest colorful number: %,d\n", c.largest); System.out.printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { System.out.printf("%d  %,d\n", d + 1, c.count[d]); total += c.count[d]; } System.out.printf("\nTotal: %,d\n", total); } private ColorfulNumbers() { countColorful(0, 0, 0); } public static boolean isColorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[] = new int[10]; int digits[] = new int[8]; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[] = new int[36]; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } private void countColorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; countColorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (isColorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; countColorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } }
Convert this C block to Java, preserving its control flow and logic.
#include <locale.h> #include <stdbool.h> #include <stdio.h> #include <time.h> bool colorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[10] = {}; int digits[8] = {}; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[36] = {}; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } static int count[8]; static bool used[10]; static int largest = 0; void count_colorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; count_colorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (colorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; count_colorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } int main() { setlocale(LC_ALL, ""); clock_t start = clock(); printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (colorful(n)) printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } count_colorful(0, 0, 0); printf("\n\nLargest colorful number: %'d\n", largest); printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { printf("%d  %'d\n", d + 1, count[d]); total += count[d]; } printf("\nTotal: %'d\n", total); clock_t end = clock(); printf("\nElapsed time: %f seconds\n", (end - start + 0.0) / CLOCKS_PER_SEC); return 0; }
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (isColorful(n)) System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } ColorfulNumbers c = new ColorfulNumbers(); System.out.printf("\n\nLargest colorful number: %,d\n", c.largest); System.out.printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { System.out.printf("%d  %,d\n", d + 1, c.count[d]); total += c.count[d]; } System.out.printf("\nTotal: %,d\n", total); } private ColorfulNumbers() { countColorful(0, 0, 0); } public static boolean isColorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[] = new int[10]; int digits[] = new int[8]; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[] = new int[36]; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } private void countColorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; countColorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (isColorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; countColorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } }
Produce a functionally identical Java code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { if( result.source) free((void*)result.source); } WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { WrenLoadModuleResult result = {0}; if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { result.onComplete = loadModuleComplete; char fullName[strlen(name) + 6]; strcpy(fullName, name); strcat(fullName, ".wren"); result.source = readFile(fullName); } return result; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_tasks_without_examples.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.ArrayList; import java.util.regex.Pattern; public class TasksWithoutExamples { private static String readPage(HttpClient client, URI uri) throws IOException, InterruptedException { var request = HttpRequest.newBuilder() .GET() .uri(uri) .timeout(Duration.ofSeconds(5)) .setHeader("accept", "text/html") .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); return response.body(); } private static void process(HttpClient client, String base, String task) { try { var re = Pattern.compile(".*using any language you may know.</div>(.*?)<div id=\"toc\".*", Pattern.DOTALL + Pattern.MULTILINE); var re2 = Pattern.compile("</?[^>]*>"); var page = base + task; String body = readPage(client, new URI(page)); var matcher = re.matcher(body); if (matcher.matches()) { var group = matcher.group(1); var m2 = re2.matcher(group); var text = m2.replaceAll(""); System.out.println(text); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException { var re = Pattern.compile("<li><a href=\"/wiki/(.*?)\"", Pattern.DOTALL + Pattern.MULTILINE); var client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .followRedirects(HttpClient.Redirect.NORMAL) .connectTimeout(Duration.ofSeconds(5)) .build(); var uri = new URI("http", "rosettacode.org", "/wiki/Category:Programming_Tasks", ""); var body = readPage(client, uri); var matcher = re.matcher(body); var tasks = new ArrayList<String>(); while (matcher.find()) { tasks.add(matcher.group(1)); } var base = "http: var limit = 3L; tasks.stream().limit(limit).forEach(task -> process(client, base, task)); } }
Convert this C snippet to Java and keep its semantics consistent.
#include <stdio.h> #include <math.h> #include <stdlib.h> int header[] = {46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1}; int main(int argc, char *argv[]){ float freq, dur; long i, v; if (argc < 3) { printf("Usage:\n"); printf(" csine <frequency> <duration>\n"); exit(1); } freq = atof(argv[1]); dur = atof(argv[2]); for (i = 0; i < 24; i++) putchar(header[i]); for (i = 0; i < dur * 44100; i++) { v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.)); v = v % 65536; putchar(v >> 8); putchar(v % 256); } }
import processing.sound.*; SinOsc sine; size(500,500); sine = new SinOsc(this); sine.freq(500); sine.play(); delay(5000);
Keep all operations the same but rewrite the snippet in Java.
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
package codegenerator; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class CodeGenerator { final static int WORDSIZE = 4; static byte[] code = {}; static Map<String, NodeType> str_to_nodes = new HashMap<>(); static List<String> string_pool = new ArrayList<>(); static List<String> variables = new ArrayList<>(); static int string_count = 0; static int var_count = 0; static Scanner s; static NodeType[] unary_ops = { NodeType.nd_Negate, NodeType.nd_Not }; static NodeType[] operators = { NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub, NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq, NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or }; static enum Mnemonic { NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE), nd_If("If", Mnemonic.NONE), nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE), nd_Assign("Assign", Mnemonic.NONE), nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD), nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE), nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ), nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR); private final String name; private final Mnemonic m; NodeType(String name, Mnemonic m) { this.name = name; this.m = m; } Mnemonic getMnemonic() { return this.m; } @Override public String toString() { return this.name; } } static void appendToCode(int b) { code = Arrays.copyOf(code, code.length + 1); code[code.length - 1] = (byte) b; } static void emit_byte(Mnemonic m) { appendToCode(m.ordinal()); } static void emit_word(int n) { appendToCode(n >> 24); appendToCode(n >> 16); appendToCode(n >> 8); appendToCode(n); } static void emit_word_at(int pos, int n) { code[pos] = (byte) (n >> 24); code[pos + 1] = (byte) (n >> 16); code[pos + 2] = (byte) (n >> 8); code[pos + 3] = (byte) n; } static int get_word(int pos) { int result; result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ; return result; } static int fetch_var_offset(String name) { int n; n = variables.indexOf(name); if (n == -1) { variables.add(name); n = var_count++; } return n; } static int fetch_string_offset(String str) { int n; n = string_pool.indexOf(str); if (n == -1) { string_pool.add(str); n = string_count++; } return n; } static int hole() { int t = code.length; emit_word(0); return t; } static boolean arrayContains(NodeType[] a, NodeType n) { boolean result = false; for (NodeType test: a) { if (test.equals(n)) { result = true; break; } } return result; } static void code_gen(Node x) throws Exception { int n, p1, p2; if (x == null) return; switch (x.nt) { case nd_None: return; case nd_Ident: emit_byte(Mnemonic.FETCH); n = fetch_var_offset(x.value); emit_word(n); break; case nd_Integer: emit_byte(Mnemonic.PUSH); emit_word(Integer.parseInt(x.value)); break; case nd_String: emit_byte(Mnemonic.PUSH); n = fetch_string_offset(x.value); emit_word(n); break; case nd_Assign: n = fetch_var_offset(x.left.value); code_gen(x.right); emit_byte(Mnemonic.STORE); emit_word(n); break; case nd_If: p2 = 0; code_gen(x.left); emit_byte(Mnemonic.JZ); p1 = hole(); code_gen(x.right.left); if (x.right.right != null) { emit_byte(Mnemonic.JMP); p2 = hole(); } emit_word_at(p1, code.length - p1); if (x.right.right != null) { code_gen(x.right.right); emit_word_at(p2, code.length - p2); } break; case nd_While: p1 = code.length; code_gen(x.left); emit_byte(Mnemonic.JZ); p2 = hole(); code_gen(x.right); emit_byte(Mnemonic.JMP); emit_word(p1 - code.length); emit_word_at(p2, code.length - p2); break; case nd_Sequence: code_gen(x.left); code_gen(x.right); break; case nd_Prtc: code_gen(x.left); emit_byte(Mnemonic.PRTC); break; case nd_Prti: code_gen(x.left); emit_byte(Mnemonic.PRTI); break; case nd_Prts: code_gen(x.left); emit_byte(Mnemonic.PRTS); break; default: if (arrayContains(operators, x.nt)) { code_gen(x.left); code_gen(x.right); emit_byte(x.nt.getMnemonic()); } else if (arrayContains(unary_ops, x.nt)) { code_gen(x.left); emit_byte(x.nt.getMnemonic()); } else { throw new Exception("Error in code generator! Found " + x.nt + ", expecting operator."); } } } static void list_code() throws Exception { int pc = 0, x; Mnemonic op; System.out.println("Datasize: " + var_count + " Strings: " + string_count); for (String s: string_pool) { System.out.println(s); } while (pc < code.length) { System.out.printf("%4d ", pc); op = Mnemonic.values()[code[pc++]]; switch (op) { case FETCH: x = get_word(pc); System.out.printf("fetch [%d]", x); pc += WORDSIZE; break; case STORE: x = get_word(pc); System.out.printf("store [%d]", x); pc += WORDSIZE; break; case PUSH: x = get_word(pc); System.out.printf("push %d", x); pc += WORDSIZE; break; case ADD: case SUB: case MUL: case DIV: case MOD: case LT: case GT: case LE: case GE: case EQ: case NE: case AND: case OR: case NEG: case NOT: case PRTC: case PRTI: case PRTS: case HALT: System.out.print(op.toString().toLowerCase()); break; case JMP: x = get_word(pc); System.out.printf("jmp (%d) %d", x, pc + x); pc += WORDSIZE; break; case JZ: x = get_word(pc); System.out.printf("jz (%d) %d", x, pc + x); pc += WORDSIZE; break; default: throw new Exception("Unknown opcode " + code[pc] + "@" + (pc - 1)); } System.out.println(); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); code_gen(n); emit_byte(Mnemonic.HALT); list_code(); } catch (Exception e) { System.out.println("Ex: "+e); } } } }
Transform the following C implementation into Java, maintaining the same output and logic.
count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }
package codegenerator; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class CodeGenerator { final static int WORDSIZE = 4; static byte[] code = {}; static Map<String, NodeType> str_to_nodes = new HashMap<>(); static List<String> string_pool = new ArrayList<>(); static List<String> variables = new ArrayList<>(); static int string_count = 0; static int var_count = 0; static Scanner s; static NodeType[] unary_ops = { NodeType.nd_Negate, NodeType.nd_Not }; static NodeType[] operators = { NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub, NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq, NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or }; static enum Mnemonic { NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE), nd_If("If", Mnemonic.NONE), nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE), nd_Assign("Assign", Mnemonic.NONE), nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD), nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE), nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ), nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR); private final String name; private final Mnemonic m; NodeType(String name, Mnemonic m) { this.name = name; this.m = m; } Mnemonic getMnemonic() { return this.m; } @Override public String toString() { return this.name; } } static void appendToCode(int b) { code = Arrays.copyOf(code, code.length + 1); code[code.length - 1] = (byte) b; } static void emit_byte(Mnemonic m) { appendToCode(m.ordinal()); } static void emit_word(int n) { appendToCode(n >> 24); appendToCode(n >> 16); appendToCode(n >> 8); appendToCode(n); } static void emit_word_at(int pos, int n) { code[pos] = (byte) (n >> 24); code[pos + 1] = (byte) (n >> 16); code[pos + 2] = (byte) (n >> 8); code[pos + 3] = (byte) n; } static int get_word(int pos) { int result; result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ; return result; } static int fetch_var_offset(String name) { int n; n = variables.indexOf(name); if (n == -1) { variables.add(name); n = var_count++; } return n; } static int fetch_string_offset(String str) { int n; n = string_pool.indexOf(str); if (n == -1) { string_pool.add(str); n = string_count++; } return n; } static int hole() { int t = code.length; emit_word(0); return t; } static boolean arrayContains(NodeType[] a, NodeType n) { boolean result = false; for (NodeType test: a) { if (test.equals(n)) { result = true; break; } } return result; } static void code_gen(Node x) throws Exception { int n, p1, p2; if (x == null) return; switch (x.nt) { case nd_None: return; case nd_Ident: emit_byte(Mnemonic.FETCH); n = fetch_var_offset(x.value); emit_word(n); break; case nd_Integer: emit_byte(Mnemonic.PUSH); emit_word(Integer.parseInt(x.value)); break; case nd_String: emit_byte(Mnemonic.PUSH); n = fetch_string_offset(x.value); emit_word(n); break; case nd_Assign: n = fetch_var_offset(x.left.value); code_gen(x.right); emit_byte(Mnemonic.STORE); emit_word(n); break; case nd_If: p2 = 0; code_gen(x.left); emit_byte(Mnemonic.JZ); p1 = hole(); code_gen(x.right.left); if (x.right.right != null) { emit_byte(Mnemonic.JMP); p2 = hole(); } emit_word_at(p1, code.length - p1); if (x.right.right != null) { code_gen(x.right.right); emit_word_at(p2, code.length - p2); } break; case nd_While: p1 = code.length; code_gen(x.left); emit_byte(Mnemonic.JZ); p2 = hole(); code_gen(x.right); emit_byte(Mnemonic.JMP); emit_word(p1 - code.length); emit_word_at(p2, code.length - p2); break; case nd_Sequence: code_gen(x.left); code_gen(x.right); break; case nd_Prtc: code_gen(x.left); emit_byte(Mnemonic.PRTC); break; case nd_Prti: code_gen(x.left); emit_byte(Mnemonic.PRTI); break; case nd_Prts: code_gen(x.left); emit_byte(Mnemonic.PRTS); break; default: if (arrayContains(operators, x.nt)) { code_gen(x.left); code_gen(x.right); emit_byte(x.nt.getMnemonic()); } else if (arrayContains(unary_ops, x.nt)) { code_gen(x.left); emit_byte(x.nt.getMnemonic()); } else { throw new Exception("Error in code generator! Found " + x.nt + ", expecting operator."); } } } static void list_code() throws Exception { int pc = 0, x; Mnemonic op; System.out.println("Datasize: " + var_count + " Strings: " + string_count); for (String s: string_pool) { System.out.println(s); } while (pc < code.length) { System.out.printf("%4d ", pc); op = Mnemonic.values()[code[pc++]]; switch (op) { case FETCH: x = get_word(pc); System.out.printf("fetch [%d]", x); pc += WORDSIZE; break; case STORE: x = get_word(pc); System.out.printf("store [%d]", x); pc += WORDSIZE; break; case PUSH: x = get_word(pc); System.out.printf("push %d", x); pc += WORDSIZE; break; case ADD: case SUB: case MUL: case DIV: case MOD: case LT: case GT: case LE: case GE: case EQ: case NE: case AND: case OR: case NEG: case NOT: case PRTC: case PRTI: case PRTS: case HALT: System.out.print(op.toString().toLowerCase()); break; case JMP: x = get_word(pc); System.out.printf("jmp (%d) %d", x, pc + x); pc += WORDSIZE; break; case JZ: x = get_word(pc); System.out.printf("jz (%d) %d", x, pc + x); pc += WORDSIZE; break; default: throw new Exception("Unknown opcode " + code[pc] + "@" + (pc - 1)); } System.out.println(); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); code_gen(n); emit_byte(Mnemonic.HALT); list_code(); } catch (Exception e) { System.out.println("Ex: "+e); } } } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
k=2; i=1; j=2; while(k<nn); k++; sb[k]=sb[k-i]+sb[k-j]; k++; sb[k]=sb[k-j]; i++; j++; }
import java.math.BigInteger; import java.util.LinkedList; public class SternBrocot { static LinkedList<Integer> sequence = new LinkedList<Integer>(){{ add(1); add(1); }}; private static void genSeq(int n){ for(int conIdx = 1; sequence.size() < n; conIdx++){ int consider = sequence.get(conIdx); int pre = sequence.get(conIdx - 1); sequence.add(consider + pre); sequence.add(consider); } } public static void main(String[] args){ genSeq(1200); System.out.println("The first 15 elements are: " + sequence.subList(0, 15)); for(int i = 1; i <= 10; i++){ System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1)); } System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1)); boolean failure = false; for(int i = 0; i < 999; i++){ failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE); } System.out.println("All GCDs are" + (failure ? " not" : "") + " 1"); } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> typedef struct{ double value; double delta; }imprecise; #define SQR(x) ((x) * (x)) imprecise imprecise_add(imprecise a, imprecise b) { imprecise ret; ret.value = a.value + b.value; ret.delta = sqrt(SQR(a.delta) + SQR(b.delta)); return ret; } imprecise imprecise_mul(imprecise a, imprecise b) { imprecise ret; ret.value = a.value * b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)); return ret; } imprecise imprecise_div(imprecise a, imprecise b) { imprecise ret; ret.value = a.value / b.value; ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value); return ret; } imprecise imprecise_pow(imprecise a, double c) { imprecise ret; ret.value = pow(a.value, c); ret.delta = fabs(ret.value * c * a.delta / a.value); return ret; } char* printImprecise(imprecise val) { char principal[30],error[30],*string,sign[2]; sign[0] = 241; sign[1] = 00; sprintf(principal,"%f",val.value); sprintf(error,"%f",val.delta); string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char)); strcpy(string,principal); strcat(string,sign); strcat(string,error); return string; } int main(void) { imprecise x1 = {100, 1.1}; imprecise y1 = {50, 1.2}; imprecise x2 = {-200, 2.2}; imprecise y2 = {-100, 2.3}; imprecise d; d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5); printf("Distance, d, between the following points :"); printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1)); printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2)); printf("\nis d = %s", printImprecise(d)); return 0; }
public class Approx { private double value; private double error; public Approx(){this.value = this.error = 0;} public Approx(Approx b){ this.value = b.value; this.error = b.error; } public Approx(double value, double error){ this.value = value; this.error = error; } public Approx add(Approx b){ value+= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx add(double b){ value+= b; return this; } public Approx sub(Approx b){ value-= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx sub(double b){ value-= b; return this; } public Approx mult(Approx b){ double oldVal = value; value*= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx mult(double b){ value*= b; error = Math.abs(b * error); return this; } public Approx div(Approx b){ double oldVal = value; value/= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx div(double b){ value/= b; error = Math.abs(b * error); return this; } public Approx pow(double b){ double oldVal = value; value = Math.pow(value, b); error = Math.abs(value * b * (error / oldVal)); return this; } @Override public String toString(){return value+"±"+error;} public static void main(String[] args){ Approx x1 = new Approx(100, 1.1); Approx y1 = new Approx(50, 1.2); Approx x2 = new Approx(200, 2.2); Approx y2 = new Approx(100, 2.3); x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5); System.out.println(x1); } }
Produce a functionally identical Java code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> static char code[128] = { 0 }; void add_code(const char *s, int c) { while (*s) { code[(int)*s] = code[0x20 ^ (int)*s] = c; s++; } } void init() { static const char *cls[] = { "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0}; int i; for (i = 0; cls[i]; i++) add_code(cls[i], i - 1); } const char* soundex(const char *s) { static char out[5]; int c, prev, i; out[0] = out[4] = 0; if (!s || !*s) return out; out[0] = *s++; prev = code[(int)out[0]]; for (i = 1; *s && i < 4; s++) { if ((c = code[(int)*s]) == prev) continue; if (c == -1) prev = 0; else if (c > 0) { out[i++] = c + '0'; prev = c; } } while (i < 4) out[i++] = '0'; return out; } int main() { int i; const char *sdx, *names[][2] = { {"Soundex", "S532"}, {"Example", "E251"}, {"Sownteks", "S532"}, {"Ekzampul", "E251"}, {"Euler", "E460"}, {"Gauss", "G200"}, {"Hilbert", "H416"}, {"Knuth", "K530"}, {"Lloyd", "L300"}, {"Lukasiewicz", "L222"}, {"Ellery", "E460"}, {"Ghosh", "G200"}, {"Heilbronn", "H416"}, {"Kant", "K530"}, {"Ladd", "L300"}, {"Lissajous", "L222"}, {"Wheaton", "W350"}, {"Burroughs", "B620"}, {"Burrows", "B620"}, {"O'Hara", "O600"}, {"Washington", "W252"}, {"Lee", "L000"}, {"Gutierrez", "G362"}, {"Pfister", "P236"}, {"Jackson", "J250"}, {"Tymczak", "T522"}, {"VanDeusen", "V532"}, {"Ashcraft", "A261"}, {0, 0} }; init(); puts(" Test name Code Got\n----------------------"); for (i = 0; names[i][0]; i++) { sdx = soundex(names[i][0]); printf("%11s %s %s ", names[i][0], names[i][1], sdx); printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok"); } return 0; }
public static void main(String[] args){ System.out.println(soundex("Soundex")); System.out.println(soundex("Example")); System.out.println(soundex("Sownteks")); System.out.println(soundex("Ekzampul")); } private static String getCode(char c){ switch(c){ case 'B': case 'F': case 'P': case 'V': return "1"; case 'C': case 'G': case 'J': case 'K': case 'Q': case 'S': case 'X': case 'Z': return "2"; case 'D': case 'T': return "3"; case 'L': return "4"; case 'M': case 'N': return "5"; case 'R': return "6"; default: return ""; } } public static String soundex(String s){ String code, previous, soundex; code = s.toUpperCase().charAt(0) + ""; previous = getCode(s.toUpperCase().charAt(0)); for(int i = 1;i < s.length();i++){ String current = getCode(s.toUpperCase().charAt(i)); if(current.length() > 0 && !current.equals(previous)){ code = code + current; } previous = current; } soundex = (code + "0000").substring(0, 4); return soundex; }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> typedef unsigned int uint; typedef unsigned long long tree; #define B(x) (1ULL<<(x)) tree *list = 0; uint cap = 0, len = 0; uint offset[32] = {0, 1, 0}; void append(tree t) { if (len == cap) { cap = cap ? cap*2 : 2; list = realloc(list, cap*sizeof(tree)); } list[len++] = 1 | t<<1; } void show(tree t, uint len) { for (; len--; t >>= 1) putchar(t&1 ? '(' : ')'); } void listtrees(uint n) { uint i; for (i = offset[n]; i < offset[n+1]; i++) { show(list[i], n*2); putchar('\n'); } } void assemble(uint n, tree t, uint sl, uint pos, uint rem) { if (!rem) { append(t); return; } if (sl > rem) pos = offset[sl = rem]; else if (pos >= offset[sl + 1]) { if (!--sl) return; pos = offset[sl]; } assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl); assemble(n, t, sl, pos + 1, rem); } void mktrees(uint n) { if (offset[n + 1]) return; if (n) mktrees(n - 1); assemble(n, 0, n-1, offset[n-1], n-1); offset[n+1] = len; } int main(int c, char**v) { int n; if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5; append(0); mktrees((uint)n); fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]); listtrees((uint)n); return 0; }
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET.add(1); } else { OFFSET.add(0); } } } private static void append(long t) { TREE_LIST.add(1 | (t << 1)); } private static void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { System.out.print('('); } else { System.out.print(')'); } t = t >> 1; } } private static void listTrees(int n) { for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) { show(TREE_LIST.get(i), n * 2); System.out.println(); } } private static void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } var pp = pos; var ss = sl; if (sl > rem) { ss = rem; pp = OFFSET.get(ss); } else if (pp >= OFFSET.get(ss + 1)) { ss--; if (ss == 0) { return; } pp = OFFSET.get(ss); } assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } private static void makeTrees(int n) { if (OFFSET.get(n + 1) != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1); OFFSET.set(n + 1, TREE_LIST.size()); } private static void test(int n) { if (n < 1 || n > 12) { throw new IllegalArgumentException("Argument must be between 1 and 12"); } append(0); makeTrees(n); System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n)); listTrees(n); } public static void main(String[] args) { test(5); } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> typedef unsigned int uint; typedef unsigned long long tree; #define B(x) (1ULL<<(x)) tree *list = 0; uint cap = 0, len = 0; uint offset[32] = {0, 1, 0}; void append(tree t) { if (len == cap) { cap = cap ? cap*2 : 2; list = realloc(list, cap*sizeof(tree)); } list[len++] = 1 | t<<1; } void show(tree t, uint len) { for (; len--; t >>= 1) putchar(t&1 ? '(' : ')'); } void listtrees(uint n) { uint i; for (i = offset[n]; i < offset[n+1]; i++) { show(list[i], n*2); putchar('\n'); } } void assemble(uint n, tree t, uint sl, uint pos, uint rem) { if (!rem) { append(t); return; } if (sl > rem) pos = offset[sl = rem]; else if (pos >= offset[sl + 1]) { if (!--sl) return; pos = offset[sl]; } assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl); assemble(n, t, sl, pos + 1, rem); } void mktrees(uint n) { if (offset[n + 1]) return; if (n) mktrees(n - 1); assemble(n, 0, n-1, offset[n-1], n-1); offset[n+1] = len; } int main(int c, char**v) { int n; if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5; append(0); mktrees((uint)n); fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]); listtrees((uint)n); return 0; }
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET.add(1); } else { OFFSET.add(0); } } } private static void append(long t) { TREE_LIST.add(1 | (t << 1)); } private static void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { System.out.print('('); } else { System.out.print(')'); } t = t >> 1; } } private static void listTrees(int n) { for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) { show(TREE_LIST.get(i), n * 2); System.out.println(); } } private static void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } var pp = pos; var ss = sl; if (sl > rem) { ss = rem; pp = OFFSET.get(ss); } else if (pp >= OFFSET.get(ss + 1)) { ss--; if (ss == 0) { return; } pp = OFFSET.get(ss); } assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } private static void makeTrees(int n) { if (OFFSET.get(n + 1) != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1); OFFSET.set(n + 1, TREE_LIST.size()); } private static void test(int n) { if (n < 1 || n > 12) { throw new IllegalArgumentException("Argument must be between 1 and 12"); } append(0); makeTrees(n); System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n)); listTrees(n); } public static void main(String[] args) { test(5); } }
Maintain the same structure and functionality when rewriting this code in Java.
int add(int a, int b) { return a + b; }
public class Doc{ private String field; public int method(long num) throws BadException{ } }
Translate this program into Java but keep the logic exactly as in C.
#include <stdio.h> #include <tgmath.h> #define VERBOSE 0 #define for3 for(int i = 0; i < 3; i++) typedef complex double vec; typedef struct { vec c; double r; } circ; #define re(x) creal(x) #define im(x) cimag(x) #define cp(x) re(x), im(x) #define CPLX "(%6.3f,%6.3f)" #define CPLX3 CPLX" "CPLX" "CPLX double cross(vec a, vec b) { return re(a) * im(b) - im(a) * re(b); } double abs2(vec a) { return a * conj(a); } int apollonius_in(circ aa[], int ss[], int flip, int divert) { vec n[3], x[3], t[3], a, b, center; int s[3], iter = 0, res = 0; double diff = 1, diff_old = -1, axb, d, r; for3 { s[i] = ss[i] ? 1 : -1; x[i] = aa[i].c; } while (diff > 1e-20) { a = x[0] - x[2], b = x[1] - x[2]; diff = 0; axb = -cross(a, b); d = sqrt(abs2(a) * abs2(b) * abs2(a - b)); if (VERBOSE) { const char *z = 1 + "-0+"; printf("%c%c%c|%c%c|", z[s[0]], z[s[1]], z[s[2]], z[flip], z[divert]); printf(CPLX3, cp(x[0]), cp(x[1]), cp(x[2])); } r = fabs(d / (2 * axb)); center = (abs2(a)*b - abs2(b)*a) / (2 * axb) * I + x[2]; if (!axb && flip != -1 && !divert) { if (!d) { printf("Given conditions confused me.\n"); return 0; } if (VERBOSE) puts("\n[divert]"); divert = 1; res = apollonius_in(aa, ss, -1, 1); } for3 n[i] = axb ? aa[i].c - center : a * I * flip; for3 t[i] = aa[i].c + n[i] / cabs(n[i]) * aa[i].r * s[i]; for3 diff += abs2(t[i] - x[i]), x[i] = t[i]; if (VERBOSE) printf(" %g\n", diff); if (diff >= diff_old && diff_old >= 0) if (iter++ > 20) return res; diff_old = diff; } printf("found: "); if (axb) printf("circle "CPLX", r = %f\n", cp(center), r); else printf("line "CPLX3"\n", cp(x[0]), cp(x[1]), cp(x[2])); return res + 1; } int apollonius(circ aa[]) { int s[3], i, sum = 0; for (i = 0; i < 8; i++) { s[0] = i & 1, s[1] = i & 2, s[2] = i & 4; if (s[0] && !aa[0].r) continue; if (s[1] && !aa[1].r) continue; if (s[2] && !aa[2].r) continue; sum += apollonius_in(aa, s, 1, 0); } return sum; } int main() { circ a[3] = {{0, 1}, {4, 1}, {2 + 4 * I, 1}}; circ b[3] = {{-3, 2}, {0, 1}, {3, 2}}; circ c[3] = {{-2, 1}, {0, 1}, {2 * I, 1}}; puts("set 1"); apollonius(a); puts("set 2"); apollonius(b); puts("set 3"); apollonius(c); }
public class Circle { public double[] center; public double radius; public Circle(double[] center, double radius) { this.center = center; this.radius = radius; } public String toString() { return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1], radius); } } public class ApolloniusSolver { public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1, int s2, int s3) { float x1 = c1.center[0]; float y1 = c1.center[1]; float r1 = c1.radius; float x2 = c2.center[0]; float y2 = c2.center[1]; float r2 = c2.radius; float x3 = c3.center[0]; float y3 = c3.center[1]; float r3 = c3.radius; float v11 = 2*x2 - 2*x1; float v12 = 2*y2 - 2*y1; float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2; float v14 = 2*s2*r2 - 2*s1*r1; float v21 = 2*x3 - 2*x2; float v22 = 2*y3 - 2*y2; float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3; float v24 = 2*s3*r3 - 2*s2*r2; float w12 = v12/v11; float w13 = v13/v11; float w14 = v14/v11; float w22 = v22/v21-w12; float w23 = v23/v21-w13; float w24 = v24/v21-w14; float P = -w23/w22; float Q = w24/w22; float M = -w12*P-w13; float N = w14 - w12*Q; float a = N*N + Q*Q - 1; float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1; float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1; float D = b*b-4*a*c; float rs = (-b-Math.sqrt(D))/(2*a); float xs = M + N * rs; float ys = P + Q * rs; return new Circle(new double[]{xs,ys}, rs); } public static void main(final String[] args) { Circle c1 = new Circle(new double[]{0,0}, 1); Circle c2 = new Circle(new double[]{4,0}, 1); Circle c3 = new Circle(new double[]{2,4}, 2); System.out.println(solveApollonius(c1,c2,c3,1,1,1)); System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1)); } }
Write the same code in Java as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node_t { char *elem; int length; struct node_t *next; } node; node *make_node(char *s) { node *t = malloc(sizeof(node)); t->elem = s; t->length = strlen(s); t->next = NULL; return t; } void append_node(node *head, node *elem) { while (head->next != NULL) { head = head->next; } head->next = elem; } void print_node(node *n) { putc('[', stdout); while (n != NULL) { printf("`%s` ", n->elem); n = n->next; } putc(']', stdout); } char *lcs(node *list) { int minLen = INT_MAX; int i; char *res; node *ptr; if (list == NULL) { return ""; } if (list->next == NULL) { return list->elem; } for (ptr = list; ptr != NULL; ptr = ptr->next) { minLen = min(minLen, ptr->length); } if (minLen == 0) { return ""; } res = ""; for (i = 1; i < minLen; i++) { char *suffix = &list->elem[list->length - i]; for (ptr = list->next; ptr != NULL; ptr = ptr->next) { char *e = &ptr->elem[ptr->length - i]; if (strcmp(suffix, e) != 0) { return res; } } res = suffix; } return res; } void test(node *n) { print_node(n); printf(" -> `%s`\n", lcs(n)); } void case1() { node *n = make_node("baabababc"); append_node(n, make_node("baabc")); append_node(n, make_node("bbbabc")); test(n); } void case2() { node *n = make_node("baabababc"); append_node(n, make_node("baabc")); append_node(n, make_node("bbbazc")); test(n); } void case3() { node *n = make_node("Sunday"); append_node(n, make_node("Monday")); append_node(n, make_node("Tuesday")); append_node(n, make_node("Wednesday")); append_node(n, make_node("Thursday")); append_node(n, make_node("Friday")); append_node(n, make_node("Saturday")); test(n); } void case4() { node *n = make_node("longest"); append_node(n, make_node("common")); append_node(n, make_node("suffix")); test(n); } void case5() { node *n = make_node("suffix"); test(n); } void case6() { node *n = make_node(""); test(n); } int main() { case1(); case2(); case3(); case4(); case5(); case6(); return 0; }
import java.util.List; public class App { private static String lcs(List<String> a) { var le = a.size(); if (le == 0) { return ""; } if (le == 1) { return a.get(0); } var le0 = a.get(0).length(); var minLen = le0; for (int i = 1; i < le; i++) { if (a.get(i).length() < minLen) { minLen = a.get(i).length(); } } if (minLen == 0) { return ""; } var res = ""; var a1 = a.subList(1, a.size()); for (int i = 1; i < minLen; i++) { var suffix = a.get(0).substring(le0 - i); for (String e : a1) { if (!e.endsWith(suffix)) { return res; } } res = suffix; } return ""; } public static void main(String[] args) { var tests = List.of( List.of("baabababc", "baabc", "bbbabc"), List.of("baabababc", "baabc", "bbbazc"), List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), List.of("longest", "common", "suffix"), List.of("suffix"), List.of("") ); for (List<String> test : tests) { System.out.printf("%s -> `%s`\n", test, lcs(test)); } } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> int main(int argc, char const *argv[]) { for (char c = 0x41; c < 0x5b; c ++) putchar(c); putchar('\n'); for (char c = 0x61; c < 0x7b; c ++) putchar(c); putchar('\n'); return 0; }
import java.util.stream.IntStream; public class Letters { public static void main(String[] args) throws Exception { System.out.print("Upper case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isUpperCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); System.out.print("Lower case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isLowerCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); } }
Keep all operations the same but rewrite the snippet in Java.
#include<stdlib.h> #include<stdio.h> typedef struct{ int rows,cols; int** dataSet; }matrix; matrix readMatrix(char* dataFile){ FILE* fp = fopen(dataFile,"r"); matrix rosetta; int i,j; fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols); rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*)); for(i=0;i<rosetta.rows;i++){ rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int)); for(j=0;j<rosetta.cols;j++) fscanf(fp,"%d",&rosetta.dataSet[i][j]); } fclose(fp); return rosetta; } void printMatrix(matrix rosetta){ int i,j; for(i=0;i<rosetta.rows;i++){ printf("\n"); for(j=0;j<rosetta.cols;j++) printf("%3d",rosetta.dataSet[i][j]); } } int findSum(matrix rosetta){ int i,j,sum = 0; for(i=1;i<rosetta.rows;i++){ for(j=0;j<i;j++){ sum += rosetta.dataSet[i][j]; } } return sum; } int main(int argC,char* argV[]) { if(argC!=2) return printf("Usage : %s <filename>",argV[0]); matrix data = readMatrix(argV[1]); printf("\n\nMatrix is : \n\n"); printMatrix(data); printf("\n\nSum below main diagonal : %d",findSum(data)); return 0; }
public static void main(String[] args) { int[][] matrix = {{1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}}; int sum = 0; for (int row = 1; row < matrix.length; row++) { for (int col = 0; col < row; col++) { sum += matrix[row][col]; } } System.out.println(sum); }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <time.h> void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } typedef struct node_tag { int item; struct node_tag* prev; struct node_tag* next; } node_t; void list_initialize(node_t* list) { list->prev = list; list->next = list; } void list_destroy(node_t* list) { node_t* n = list->next; while (n != list) { node_t* tmp = n->next; free(n); n = tmp; } } void list_append_node(node_t* list, node_t* node) { node_t* prev = list->prev; prev->next = node; list->prev = node; node->prev = prev; node->next = list; } void list_append_item(node_t* list, int item) { node_t* node = xmalloc(sizeof(node_t)); node->item = item; list_append_node(list, node); } void list_print(node_t* list) { printf("["); node_t* n = list->next; if (n != list) { printf("%d", n->item); n = n->next; } for (; n != list; n = n->next) printf(", %d", n->item); printf("]\n"); } void tree_insert(node_t** p, node_t* n) { while (*p != NULL) { if (n->item < (*p)->item) p = &(*p)->prev; else p = &(*p)->next; } *p = n; } void tree_to_list(node_t* list, node_t* node) { if (node == NULL) return; node_t* prev = node->prev; node_t* next = node->next; tree_to_list(list, prev); list_append_node(list, node); tree_to_list(list, next); } void tree_sort(node_t* list) { node_t* n = list->next; if (n == list) return; node_t* root = NULL; while (n != list) { node_t* next = n->next; n->next = n->prev = NULL; tree_insert(&root, n); n = next; } list_initialize(list); tree_to_list(list, root); } int main() { srand(time(0)); node_t list; list_initialize(&list); for (int i = 0; i < 16; ++i) list_append_item(&list, rand() % 100); printf("before sort: "); list_print(&list); tree_sort(&list); printf(" after sort: "); list_print(&list); list_destroy(&list); return 0; }
import java.util.*; public class TreeSortTest { public static void main(String[] args) { test1(); System.out.println(); test2(); } private static void test1() { LinkedList<Integer> list = new LinkedList<>(); Random r = new Random(); for (int i = 0; i < 16; ++i) list.add(Integer.valueOf(r.nextInt(100))); System.out.println("before sort: " + list); list.treeSort(); System.out.println(" after sort: " + list); } private static void test2() { LinkedList<String> list = new LinkedList<>(); String[] strings = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; for (String str : strings) list.add(str); System.out.println("before sort: " + list); list.treeSort(); System.out.println(" after sort: " + list); } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <time.h> void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } typedef struct node_tag { int item; struct node_tag* prev; struct node_tag* next; } node_t; void list_initialize(node_t* list) { list->prev = list; list->next = list; } void list_destroy(node_t* list) { node_t* n = list->next; while (n != list) { node_t* tmp = n->next; free(n); n = tmp; } } void list_append_node(node_t* list, node_t* node) { node_t* prev = list->prev; prev->next = node; list->prev = node; node->prev = prev; node->next = list; } void list_append_item(node_t* list, int item) { node_t* node = xmalloc(sizeof(node_t)); node->item = item; list_append_node(list, node); } void list_print(node_t* list) { printf("["); node_t* n = list->next; if (n != list) { printf("%d", n->item); n = n->next; } for (; n != list; n = n->next) printf(", %d", n->item); printf("]\n"); } void tree_insert(node_t** p, node_t* n) { while (*p != NULL) { if (n->item < (*p)->item) p = &(*p)->prev; else p = &(*p)->next; } *p = n; } void tree_to_list(node_t* list, node_t* node) { if (node == NULL) return; node_t* prev = node->prev; node_t* next = node->next; tree_to_list(list, prev); list_append_node(list, node); tree_to_list(list, next); } void tree_sort(node_t* list) { node_t* n = list->next; if (n == list) return; node_t* root = NULL; while (n != list) { node_t* next = n->next; n->next = n->prev = NULL; tree_insert(&root, n); n = next; } list_initialize(list); tree_to_list(list, root); } int main() { srand(time(0)); node_t list; list_initialize(&list); for (int i = 0; i < 16; ++i) list_append_item(&list, rand() % 100); printf("before sort: "); list_print(&list); tree_sort(&list); printf(" after sort: "); list_print(&list); list_destroy(&list); return 0; }
import java.util.*; public class TreeSortTest { public static void main(String[] args) { test1(); System.out.println(); test2(); } private static void test1() { LinkedList<Integer> list = new LinkedList<>(); Random r = new Random(); for (int i = 0; i < 16; ++i) list.add(Integer.valueOf(r.nextInt(100))); System.out.println("before sort: " + list); list.treeSort(); System.out.println(" after sort: " + list); } private static void test2() { LinkedList<String> list = new LinkedList<>(); String[] strings = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; for (String str : strings) list.add(str); System.out.println("before sort: " + list); list.treeSort(); System.out.println(" after sort: " + list); } }
Write a version of this C function in Java with identical behavior.
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, NULL); if (buf) { fwprintf(stderr, L"%ls: %ls", message, buf); LocalFree(buf); } else { fwprintf(stderr, L"%ls: unknown error 0x%x\n", message, error); } } int dotruncate(wchar_t *fn, LARGE_INTEGER fp) { HANDLE fh; fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { oops(fn); return 1; } if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 || SetEndOfFile(fh) == 0) { oops(fn); CloseHandle(fh); return 1; } CloseHandle(fh); return 0; } int main() { LARGE_INTEGER fp; int argc; wchar_t **argv, *fn, junk[2]; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { oops(L"CommandLineToArgvW"); return 1; } if (argc != 3) { fwprintf(stderr, L"usage: %ls filename length\n", argv[0]); return 1; } fn = argv[1]; if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) { fwprintf(stderr, L"%ls: not a number\n", argv[2]); return 1; } return dotruncate(fn, fp); }
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); long newSize = Long.parseLong(args[1]); outChan.truncate(newSize); outChan.close(); } }
Change the programming language of this snippet from C to Java without modifying what it does.
#include <windows.h> #include <stdio.h> #include <wchar.h> void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, NULL); if (buf) { fwprintf(stderr, L"%ls: %ls", message, buf); LocalFree(buf); } else { fwprintf(stderr, L"%ls: unknown error 0x%x\n", message, error); } } int dotruncate(wchar_t *fn, LARGE_INTEGER fp) { HANDLE fh; fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { oops(fn); return 1; } if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 || SetEndOfFile(fh) == 0) { oops(fn); CloseHandle(fh); return 1; } CloseHandle(fh); return 0; } int main() { LARGE_INTEGER fp; int argc; wchar_t **argv, *fn, junk[2]; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { oops(L"CommandLineToArgvW"); return 1; } if (argc != 3) { fwprintf(stderr, L"usage: %ls filename length\n", argv[0]); return 1; } fn = argv[1]; if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) { fwprintf(stderr, L"%ls: not a number\n", argv[2]); return 1; } return dotruncate(fn, fp); }
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); long newSize = Long.parseLong(args[1]); outChan.truncate(newSize); outChan.close(); } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdio.h> #include <math.h> typedef struct { double m; double fm; double simp; } triple; triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = f(m); double simp = fabs(b - a) / 6 * (fa + 4*fm + fb); triple t = {m, fm, simp}; return t; } double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) { triple lt = _quad_simpsons_mem(f, a, fa, m, fm); triple rt = _quad_simpsons_mem(f, m, fm, b, fb); double delta = lt.simp + rt.simp - whole; if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15; return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm); } double quad_asr(double (*f)(double), double a, double b, double eps) { double fa = f(a); double fb = f(b); triple t = _quad_simpsons_mem(f, a, fa, b, fb); return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm); } int main(){ double a = 0.0, b = 1.0; double sinx = quad_asr(sin, a, b, 1e-09); printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx); return 0; }
import java.util.function.Function; public class NumericalIntegrationAdaptiveSimpsons { public static void main(String[] args) { Function<Double,Double> f = x -> sin(x); System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount); functionCount = 0; System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount); } private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) { double fa = function.apply(a); double fb = function.apply(b); Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb); return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx); } private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) { Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm); Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb); double delta = left.s + right.s - whole; if ( Math.abs(delta) <= 15*error ) { return left.s + right.s + delta / 15; } return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) + quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx); } private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = function.apply(m); return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb)); } private static class Triple { double x, fx, s; private Triple(double m, double fm, double s) { this.x = m; this.fx = fm; this.s = s; } } private static int functionCount = 0; private static double sin(double x) { functionCount++; return Math.sin(x); } }
Convert this C block to Java, preserving its control flow and logic.
#include <stdio.h> #include <math.h> typedef struct { double m; double fm; double simp; } triple; triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = f(m); double simp = fabs(b - a) / 6 * (fa + 4*fm + fb); triple t = {m, fm, simp}; return t; } double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) { triple lt = _quad_simpsons_mem(f, a, fa, m, fm); triple rt = _quad_simpsons_mem(f, m, fm, b, fb); double delta = lt.simp + rt.simp - whole; if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15; return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm); } double quad_asr(double (*f)(double), double a, double b, double eps) { double fa = f(a); double fb = f(b); triple t = _quad_simpsons_mem(f, a, fa, b, fb); return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm); } int main(){ double a = 0.0, b = 1.0; double sinx = quad_asr(sin, a, b, 1e-09); printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx); return 0; }
import java.util.function.Function; public class NumericalIntegrationAdaptiveSimpsons { public static void main(String[] args) { Function<Double,Double> f = x -> sin(x); System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount); functionCount = 0; System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount); } private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) { double fa = function.apply(a); double fb = function.apply(b); Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb); return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx); } private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) { Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm); Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb); double delta = left.s + right.s - whole; if ( Math.abs(delta) <= 15*error ) { return left.s + right.s + delta / 15; } return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) + quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx); } private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = function.apply(m); return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb)); } private static class Triple { double x, fx, s; private Triple(double m, double fm, double s) { this.x = m; this.fx = fm; this.s = s; } } private static int functionCount = 0; private static double sin(double x) { functionCount++; return Math.sin(x); } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen("fasta.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); int state = 0; while ((read = getline(&line, &len, fp)) != -1) { if (line[read - 1] == '\n') line[read - 1] = 0; if (line[0] == '>') { if (state == 1) printf("\n"); printf("%s: ", line+1); state = 1; } else { printf("%s", line); } } printf("\n"); fclose(fp); if (line) free(line); exit(EXIT_SUCCESS); }
import java.io.*; import java.util.Scanner; public class ReadFastaFile { public static void main(String[] args) throws FileNotFoundException { boolean first = true; try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.charAt(0) == '>') { if (first) first = false; else System.out.println(); System.out.printf("%s: ", line.substring(1)); } else { System.out.print(line); } } } System.out.println(); } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' '); do { putchar('0' + (n%base)), n /= base; } while(n); printf("(%lld)", base); } void show(xint n) { printf("%llu", n); print(n, 2); print(n, 3); putchar('\n'); } xint min(xint a, xint b) { return a < b ? a : b; } xint max(xint a, xint b) { return a > b ? a : b; } int main(void) { xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n; int cnt; show(0); cnt = 1; lo = 0; hi = pow2 = pow3 = 1; while (1) { for (i = lo; i < hi; i++) { n = (i * 3 + 1) * pow3 + reverse3(i); if (!is_palin2(n)) continue; show(n); if (++cnt >= 7) return 0; } if (i == pow3) pow3 *= 3; else pow2 *= 4; while (1) { while (pow2 <= pow3) pow2 *= 4; lo2 = (pow2 / pow3 - 1) / 3; hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1; lo3 = pow3 / 3; hi3 = pow3; if (lo2 >= hi3) pow3 *= 3; else if (lo3 >= hi2) pow2 *= 4; else { lo = max(lo2, lo3); hi = min(hi2, hi3); break; } } } return 0; }
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' '); do { putchar('0' + (n%base)), n /= base; } while(n); printf("(%lld)", base); } void show(xint n) { printf("%llu", n); print(n, 2); print(n, 3); putchar('\n'); } xint min(xint a, xint b) { return a < b ? a : b; } xint max(xint a, xint b) { return a > b ? a : b; } int main(void) { xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n; int cnt; show(0); cnt = 1; lo = 0; hi = pow2 = pow3 = 1; while (1) { for (i = lo; i < hi; i++) { n = (i * 3 + 1) * pow3 + reverse3(i); if (!is_palin2(n)) continue; show(n); if (++cnt >= 7) return 0; } if (i == pow3) pow3 *= 3; else pow2 *= 4; while (1) { while (pow2 <= pow3) pow2 *= 4; lo2 = (pow2 / pow3 - 1) / 3; hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1; lo3 = pow3 / 3; hi3 = pow3; if (lo2 >= hi3) pow3 *= 3; else if (lo3 >= hi2) pow2 *= 4; else { lo = max(lo2, lo3); hi = min(hi2, hi3); break; } } } return 0; }
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' '); do { putchar('0' + (n%base)), n /= base; } while(n); printf("(%lld)", base); } void show(xint n) { printf("%llu", n); print(n, 2); print(n, 3); putchar('\n'); } xint min(xint a, xint b) { return a < b ? a : b; } xint max(xint a, xint b) { return a > b ? a : b; } int main(void) { xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n; int cnt; show(0); cnt = 1; lo = 0; hi = pow2 = pow3 = 1; while (1) { for (i = lo; i < hi; i++) { n = (i * 3 + 1) * pow3 + reverse3(i); if (!is_palin2(n)) continue; show(n); if (++cnt >= 7) return 0; } if (i == pow3) pow3 *= 3; else pow2 *= 4; while (1) { while (pow2 <= pow3) pow2 *= 4; lo2 = (pow2 / pow3 - 1) / 3; hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1; lo3 = pow3 / 3; hi3 = pow3; if (lo2 >= hi3) pow3 *= 3; else if (lo3 >= hi2) pow2 *= 4; else { lo = max(lo2, lo3); hi = min(hi2, hi3); break; } } } return 0; }
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Translate this program into Java but keep the logic exactly as in C.
'--- added a flush to exit cleanly PRAGMA LDFLAGS `pkg-config --cflags --libs x11` PRAGMA INCLUDE <X11/Xlib.h> PRAGMA INCLUDE <X11/Xutil.h> OPTION PARSE FALSE '---XLIB is so ugly ALIAS XNextEvent TO EVENT ALIAS XOpenDisplay TO DISPLAY ALIAS DefaultScreen TO SCREEN ALIAS XCreateSimpleWindow TO CREATE ALIAS XCloseDisplay TO CLOSE_DISPLAY ALIAS XSelectInput TO EVENT_TYPE ALIAS XMapWindow TO MAP_EVENT ALIAS XFillRectangle TO FILL_RECTANGLE ALIAS XDrawString TO DRAW_STRING ALIAS XFlush TO FLUSH '---pointer to X Display structure DECLARE d TYPE Display* '---pointer to the newly created window 'DECLARE w TYPE WINDOW '---pointer to the XEvent DECLARE e TYPE XEvent DECLARE msg TYPE char* '--- number of screen to place the window on DECLARE s TYPE int msg = "Hello, World!" d = DISPLAY(NULL) IF d == NULL THEN EPRINT "Cannot open display" FORMAT "%s%s\n" END END IF s = SCREEN(d) w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s)) EVENT_TYPE(d, w, ExposureMask | KeyPressMask) MAP_EVENT(d, w) WHILE (1) EVENT(d, &e) IF e.type == Expose THEN FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10) DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg)) END IF IF e.type == KeyPress THEN BREAK END IF WEND FLUSH(d) CLOSE_DISPLAY(d)
import javax.swing.JFrame; import javax.swing.SwingUtilities; public class WindowExample { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { createAndShow(); } }; SwingUtilities.invokeLater(runnable); } static void createAndShow() { JFrame frame = new JFrame("Hello World"); frame.setSize(640,480); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Change the following C code into Java without altering its purpose.
#include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(int argc, char **argv) { typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State; typedef struct statechange { const int in; const State out; } statechange; #define MAXINPUTS 3 typedef struct FSM { const State state; void (*Action)(void); const statechange table[MAXINPUTS]; } FSM; char str[10]; void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); } void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); } void Refund(void) { fprintf(stderr, "Please collect refund.\n"); } void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); } void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); } void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); } const FSM fsm[] = { { READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }}, { WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }}, { REFUND, &Refund, {{ -1, READY} }}, { DISPENSE, &Dispense, {{ -1, COLLECT} }}, { COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }}, { QUIT, &Quit, {{ -1, QUIT} }}, }; int each; State state = READY; for (;;) { fsm[state].Action(); each = 0; while (!( ((fsm[state].table[each].in == -1) || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++; state = fsm[state].table[each].out; } return 0; }
import java.util.*; public class FiniteStateMachine { private enum State { Ready(true, "Deposit", "Quit"), Waiting(true, "Select", "Refund"), Dispensing(true, "Remove"), Refunding(false, "Refunding"), Exiting(false, "Quiting"); State(boolean exp, String... in) { inputs = Arrays.asList(in); explicit = exp; } State nextState(String input, State current) { if (inputs.contains(input)) { return map.getOrDefault(input, current); } return current; } final List<String> inputs; final static Map<String, State> map = new HashMap<>(); final boolean explicit; static { map.put("Deposit", State.Waiting); map.put("Quit", State.Exiting); map.put("Select", State.Dispensing); map.put("Refund", State.Refunding); map.put("Remove", State.Ready); map.put("Refunding", State.Ready); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); State state = State.Ready; while (state != State.Exiting) { System.out.println(state.inputs); if (state.explicit){ System.out.print("> "); state = state.nextState(sc.nextLine().trim(), state); } else { state = state.nextState(state.inputs.get(0), state); } } } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include<graphics.h> void vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec) { int color = 1,i,x = winWidth/2, y = winHeight/2; while(!kbhit()){ setcolor(color++); for(i=num;i>0;i--){ rectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth); delay(msec); } if(color>MAXCOLORS){ color = 1; } } } int main() { initwindow(1000,1000,"Vibrating Rectangles..."); vibratingRectangles(1000,1000,30,15,20,500); closegraph(); return 0; }
int counter = 100; void setup(){ size(1000,1000); } void draw(){ for(int i=0;i<20;i++){ fill(counter - 5*i); rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i); } counter++; if(counter > 255) counter = 100; delay(100); }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> struct fp2 { int64_t x, y; }; uint64_t randULong(uint64_t min, uint64_t max) { uint64_t t = (uint64_t)rand(); return min + t % (max - min); } uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) { uint64_t x = 0, y = a % modulus; while (b > 0) { if ((b & 1) == 1) { x = (x + y) % modulus; } y = (y << 1) % modulus; b = b >> 1; } return x; } uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) { uint64_t x = 1; while (power > 0) { if ((power & 1) == 1) { x = mul_mod(x, b, modulus); } b = mul_mod(b, b, modulus); power = power >> 1; } return x; } bool isPrime(uint64_t n, int64_t k) { uint64_t a, x, n_one = n - 1, d = n_one; uint32_t s = 0; uint32_t r; if (n < 2) { return false; } if (n > 9223372036854775808ull) { printf("The number is too big, program will end.\n"); exit(1); } if ((n % 2) == 0) { return n == 2; } while ((d & 1) == 0) { d = d >> 1; s = s + 1; } while (k > 0) { k = k - 1; a = randULong(2, n); x = pow_mod(a, d, n); if (x == 1 || x == n_one) { continue; } for (r = 1; r < s; r++) { x = pow_mod(x, 2, n); if (x == 1) return false; if (x == n_one) goto continue_while; } if (x != n_one) { return false; } continue_while: {} } return true; } int64_t legendre_symbol(int64_t a, int64_t p) { int64_t x = pow_mod(a, (p - 1) / 2, p); if ((p - 1) == x) { return x - p; } else { return x; } } struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) { struct fp2 answer; uint64_t tmp1, tmp2; tmp1 = mul_mod(a.x, b.x, p); tmp2 = mul_mod(a.y, b.y, p); tmp2 = mul_mod(tmp2, w2, p); answer.x = (tmp1 + tmp2) % p; tmp1 = mul_mod(a.x, b.y, p); tmp2 = mul_mod(a.y, b.x, p); answer.y = (tmp1 + tmp2) % p; return answer; } struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) { return fp2mul(a, a, p, w2); } struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) { struct fp2 ret; if (n == 0) { ret.x = 1; ret.y = 0; return ret; } if (n == 1) { return a; } if ((n & 1) == 0) { return fp2square(fp2pow(a, n / 2, p, w2), p, w2); } else { return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2); } } void test(int64_t n, int64_t p) { int64_t a, w2; int64_t x1, x2; struct fp2 answer; printf("Find solution for n = %lld and p = %lld\n", n, p); if (p == 2 || !isPrime(p, 15)) { printf("No solution, p is not an odd prime.\n\n"); return; } if (legendre_symbol(n, p) != 1) { printf(" %lld is not a square in F%lld\n\n", n, p); return; } while (true) { do { a = randULong(2, p); w2 = a * a - n; } while (legendre_symbol(w2, p) != -1); answer.x = a; answer.y = 1; answer = fp2pow(answer, (p + 1) / 2, p, w2); if (answer.y != 0) { continue; } x1 = answer.x; x2 = p - x1; if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) { printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2); return; } } } int main() { srand((size_t)time(0)); test(10, 13); test(56, 101); test(8218, 10007); test(8219, 10007); test(331575, 1000003); test(665165880, 1000000007); return 0; }
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Generate an equivalent Java version of this C code.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> struct fp2 { int64_t x, y; }; uint64_t randULong(uint64_t min, uint64_t max) { uint64_t t = (uint64_t)rand(); return min + t % (max - min); } uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) { uint64_t x = 0, y = a % modulus; while (b > 0) { if ((b & 1) == 1) { x = (x + y) % modulus; } y = (y << 1) % modulus; b = b >> 1; } return x; } uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) { uint64_t x = 1; while (power > 0) { if ((power & 1) == 1) { x = mul_mod(x, b, modulus); } b = mul_mod(b, b, modulus); power = power >> 1; } return x; } bool isPrime(uint64_t n, int64_t k) { uint64_t a, x, n_one = n - 1, d = n_one; uint32_t s = 0; uint32_t r; if (n < 2) { return false; } if (n > 9223372036854775808ull) { printf("The number is too big, program will end.\n"); exit(1); } if ((n % 2) == 0) { return n == 2; } while ((d & 1) == 0) { d = d >> 1; s = s + 1; } while (k > 0) { k = k - 1; a = randULong(2, n); x = pow_mod(a, d, n); if (x == 1 || x == n_one) { continue; } for (r = 1; r < s; r++) { x = pow_mod(x, 2, n); if (x == 1) return false; if (x == n_one) goto continue_while; } if (x != n_one) { return false; } continue_while: {} } return true; } int64_t legendre_symbol(int64_t a, int64_t p) { int64_t x = pow_mod(a, (p - 1) / 2, p); if ((p - 1) == x) { return x - p; } else { return x; } } struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) { struct fp2 answer; uint64_t tmp1, tmp2; tmp1 = mul_mod(a.x, b.x, p); tmp2 = mul_mod(a.y, b.y, p); tmp2 = mul_mod(tmp2, w2, p); answer.x = (tmp1 + tmp2) % p; tmp1 = mul_mod(a.x, b.y, p); tmp2 = mul_mod(a.y, b.x, p); answer.y = (tmp1 + tmp2) % p; return answer; } struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) { return fp2mul(a, a, p, w2); } struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) { struct fp2 ret; if (n == 0) { ret.x = 1; ret.y = 0; return ret; } if (n == 1) { return a; } if ((n & 1) == 0) { return fp2square(fp2pow(a, n / 2, p, w2), p, w2); } else { return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2); } } void test(int64_t n, int64_t p) { int64_t a, w2; int64_t x1, x2; struct fp2 answer; printf("Find solution for n = %lld and p = %lld\n", n, p); if (p == 2 || !isPrime(p, 15)) { printf("No solution, p is not an odd prime.\n\n"); return; } if (legendre_symbol(n, p) != 1) { printf(" %lld is not a square in F%lld\n\n", n, p); return; } while (true) { do { a = randULong(2, p); w2 = a * a - n; } while (legendre_symbol(w2, p) != -1); answer.x = a; answer.y = 1; answer = fp2pow(answer, (p + 1) / 2, p, w2); if (answer.y != 0) { continue; } x1 = answer.x; x2 = p - x1; if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) { printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2); return; } } } int main() { srand((size_t)time(0)); test(10, 13); test(56, 101); test(8218, 10007); test(8219, 10007); test(331575, 1000003); test(665165880, 1000000007); return 0; }
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Change the programming language of this snippet from C to Java without modifying what it does.
#include <math.h> #include <stdint.h> #include <stdio.h> const uint64_t N = 6364136223846793005; static uint64_t state = 0x853c49e6748fea9b; static uint64_t inc = 0xda3e39cb94b95bdb; uint32_t pcg32_int() { uint64_t old = state; state = old * N + inc; uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27); uint32_t rot = old >> 59; return (shifted >> rot) | (shifted << ((~rot + 1) & 31)); } double pcg32_float() { return ((double)pcg32_int()) / (1LL << 32); } void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) { state = 0; inc = (seed_sequence << 1) | 1; pcg32_int(); state = state + seed_state; pcg32_int(); } int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i; pcg32_seed(42, 54); printf("%u\n", pcg32_int()); printf("%u\n", pcg32_int()); printf("%u\n", pcg32_int()); printf("%u\n", pcg32_int()); printf("%u\n", pcg32_int()); printf("\n"); pcg32_seed(987654321, 1); for (i = 0; i < 100000; i++) { int j = (int)floor(pcg32_float() * 5.0); counts[j]++; } printf("The counts for 100,000 repetitions are:\n"); for (i = 0; i < 5; i++) { printf(" %d : %d\n", i, counts[i]); } return 0; }
public class PCG32 { private static final long N = 6364136223846793005L; private long state = 0x853c49e6748fea9bL; private long inc = 0xda3e39cb94b95bdbL; public void seed(long seedState, long seedSequence) { state = 0; inc = (seedSequence << 1) | 1; nextInt(); state = state + seedState; nextInt(); } public int nextInt() { long old = state; state = old * N + inc; int shifted = (int) (((old >>> 18) ^ old) >>> 27); int rot = (int) (old >>> 59); return (shifted >>> rot) | (shifted << ((~rot + 1) & 31)); } public double nextFloat() { var u = Integer.toUnsignedLong(nextInt()); return (double) u / (1L << 32); } public static void main(String[] args) { var r = new PCG32(); r.seed(42, 54); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; r.seed(987654321, 1); for (int i = 0; i < 100_000; i++) { int j = (int) Math.floor(r.nextFloat() * 5.0); counts[j]++; } System.out.println("The counts for 100,000 repetitions are:"); for (int i = 0; i < counts.length; i++) { System.out.printf(" %d : %d\n", i, counts[i]); } } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> double PI; typedef double complex cplx; void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2); for (int i = 0; i < n; i += 2 * step) { cplx t = cexp(-I * PI * i / n) * out[i + step]; buf[i / 2] = out[i] + t; buf[(i + n)/2] = out[i] - t; } } } void fft(cplx buf[], int n) { cplx out[n]; for (int i = 0; i < n; i++) out[i] = buf[i]; _fft(buf, out, n, 1); } cplx *pad_two(double g[], int len, int *ns) { int n = 1; if (*ns) n = *ns; else while (n < len) n *= 2; cplx *buf = calloc(sizeof(cplx), n); for (int i = 0; i < len; i++) buf[i] = g[i]; *ns = n; return buf; } void deconv(double g[], int lg, double f[], int lf, double out[]) { int ns = 0; cplx *g2 = pad_two(g, lg, &ns); cplx *f2 = pad_two(f, lf, &ns); fft(g2, ns); fft(f2, ns); cplx h[ns]; for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i]; fft(h, ns); for (int i = 0; i >= lf - lg; i--) out[-i] = h[(i + ns) % ns]/32; free(g2); free(f2); } int main() { PI = atan2(1,1) * 4; double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7}; double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 }; double h[] = { -8,-9,-3,-1,-6,7 }; int lg = sizeof(g)/sizeof(double); int lf = sizeof(f)/sizeof(double); int lh = sizeof(h)/sizeof(double); double h2[lh]; double f2[lf]; printf("f[] data is : "); for (int i = 0; i < lf; i++) printf(" %g", f[i]); printf("\n"); printf("deconv(g, h): "); deconv(g, lg, h, lh, f2); for (int i = 0; i < lf; i++) printf(" %g", f2[i]); printf("\n"); printf("h[] data is : "); for (int i = 0; i < lh; i++) printf(" %g", h[i]); printf("\n"); printf("deconv(g, f): "); deconv(g, lg, f, lf, h2); for (int i = 0; i < lh; i++) printf(" %g", h2[i]); printf("\n"); }
import java.util.Arrays; public class Deconvolution1D { public static int[] deconv(int[] g, int[] f) { int[] h = new int[g.length - f.length + 1]; for (int n = 0; n < h.length; n++) { h[n] = g[n]; int lower = Math.max(n - f.length + 1, 0); for (int i = lower; i < n; i++) h[n] -= h[i] * f[n - i]; h[n] /= f[0]; } return h; } public static void main(String[] args) { int[] h = { -8, -9, -3, -1, -6, 7 }; int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 }; int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7 }; StringBuilder sb = new StringBuilder(); sb.append("h = " + Arrays.toString(h) + "\n"); sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n"); sb.append("f = " + Arrays.toString(f) + "\n"); sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n"); System.out.println(sb.toString()); } }
Translate the given C code snippet into Java without altering its behavior.
#include <iostream> #include <iomanip> #include <string> std::string NYSIIS( std::string const& str ) { std::string s, out; s.reserve( str.length() ); for( auto const c : str ) { if( c >= 'a' && c <= 'z' ) s += c - ('a' - 'A'); else if( c >= 'A' && c <= 'Z' ) s += c; } auto replace = []( char const * const from, char const* to, char* const dst ) -> bool { auto const n = strlen( from ); if( strncmp( from, dst, n ) == 0 ) { strncpy( dst, to, n ); return true; } return false; }; auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool { auto const n = strlen( *from ); for( ; *from; ++from ) if( strncmp( *from, dst, n ) == 0 ) { memcpy( dst, to, n ); return true; } return false; }; auto isVowel = []( char const c ) -> bool { return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; }; size_t n = s.length(); replace( "MAC", "MCC", &s[0] ); replace( "KN", "NN", &s[0] ); replace( "K", "C", &s[0] ); char const* const prefix[] = { "PH", "PF", 0 }; multiReplace( prefix, "FF", &s[0] ); replace( "SCH", "SSS", &s[0] ); char const* const suffix1[] = { "EE", "IE", 0 }; char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 }; if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] )) { s.pop_back(); --n; } out += s[0]; char* vowels[] = { "A", "E", "I", "O", "U", 0 }; for( unsigned i = 1; i < n; ++i ) { char* const c = &s[i]; if( !replace( "EV", "AV", c ) ) multiReplace( vowels, "A", c ); replace( "Q", "G", c ); replace( "Z", "S", c ); replace( "M", "N", c ); if( !replace( "KN", "NN", c )) replace( "K", "C", c ); replace( "SCH", "SSS", c ); replace( "PH", "FF", c ); if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] ))) *c = s[i - 1]; if( *c == 'W' && isVowel( s[i - 1] )) *c = 'A'; if( out.back() != *c ) out += *c; } if( out.back() == 'S' || out.back() == 'A' ) out.pop_back(); n = out.length() - 2; if( out[n] == 'A' && out[n + 1] == 'Y' ) out = out.substr( 0, n ) + "Y"; return out; } int main() { static char const * const names[][2] = { { "Bishop", "BASAP" }, { "Carlson", "CARLSAN" }, { "Carr", "CAR" }, { "Chapman", "CAPNAN" }, { "Franklin", "FRANCLAN" }, { "Greene", "GRAN" }, { "Harper", "HARPAR" }, { "Jacobs", "JACAB" }, { "Larson", "LARSAN" }, { "Lawrence", "LARANC" }, { "Lawson", "LASAN" }, { "Louis, XVI", "LASXV" }, { "Lynch", "LYNC" }, { "Mackenzie", "MCANSY" }, { "Matthews", "MATA" }, { "McCormack", "MCARNAC" }, { "McDaniel", "MCDANAL" }, { "McDonald", "MCDANALD" }, { "Mclaughlin", "MCLAGLAN" }, { "Morrison", "MARASAN" }, { "O'Banion", "OBANAN" }, { "O'Brien", "OBRAN" }, { "Richards", "RACARD" }, { "Silva", "SALV" }, { "Watkins", "WATCAN" }, { "Wheeler", "WALAR" }, { "Willis", "WALA" }, { "brown, sr", "BRANSR" }, { "browne, III", "BRAN" }, { "browne, IV", "BRANAV" }, { "knight", "NAGT" }, { "mitchell", "MATCAL" }, { "o'daniel", "ODANAL" } }; for( auto const& name : names ) { auto const code = NYSIIS( name[0] ); std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code; if( code == std::string( name[1] )) std::cout << " ok"; else std::cout << " ERROR: " << name[1] << " expected"; std::cout << std::endl; } return 0; }
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}}; final static String Vowels = "AEIOU"; public static void main(String[] args) { stream(args).parallel().map(n -> transcode(n)).forEach(out::println); } static String transcode(String s) { int len = s.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z') sb.append((char) (c - 32)); else if (c >= 'A' && c <= 'Z') sb.append(c); } replace(sb, 0, first); replace(sb, sb.length() - 2, last); len = sb.length(); sb.append(" "); for (int i = 1; i < len; i++) { char prev = sb.charAt(i - 1); char curr = sb.charAt(i); char next = sb.charAt(i + 1); if (curr == 'E' && next == 'V') sb.replace(i, i + 2, "AF"); else if (isVowel(curr)) sb.setCharAt(i, 'A'); else if (curr == 'Q') sb.setCharAt(i, 'G'); else if (curr == 'Z') sb.setCharAt(i, 'S'); else if (curr == 'M') sb.setCharAt(i, 'N'); else if (curr == 'K' && next == 'N') sb.setCharAt(i, 'N'); else if (curr == 'K') sb.setCharAt(i, 'C'); else if (sb.indexOf("SCH", i) == i) sb.replace(i, i + 3, "SSS"); else if (curr == 'P' && next == 'H') sb.replace(i, i + 2, "FF"); else if (curr == 'H' && (!isVowel(prev) || !isVowel(next))) sb.setCharAt(i, prev); else if (curr == 'W' && isVowel(prev)) sb.setCharAt(i, prev); if (sb.charAt(i) == prev) { sb.deleteCharAt(i--); len--; } } sb.setLength(sb.length() - 1); int lastPos = sb.length() - 1; if (lastPos > 1) { if (sb.lastIndexOf("AY") == lastPos - 1) sb.delete(lastPos - 1, lastPos + 1).append("Y"); else if (sb.charAt(lastPos) == 'S') sb.setLength(lastPos); else if (sb.charAt(lastPos) == 'A') sb.setLength(lastPos); } if (sb.length() > 6) sb.insert(6, '[').append(']'); return String.format("%s -> %s", s, sb); } private static void replace(StringBuilder sb, int start, String[][] maps) { if (start >= 0) for (String[] map : maps) { if (sb.indexOf(map[0]) == start) { sb.replace(start, start + map[0].length(), map[1]); break; } } } private static boolean isVowel(char c) { return Vowels.indexOf(c) != -1; } }
Change the programming language of this snippet from C to Java without modifying what it does.
#include <iostream> #include <iomanip> #include <string> std::string NYSIIS( std::string const& str ) { std::string s, out; s.reserve( str.length() ); for( auto const c : str ) { if( c >= 'a' && c <= 'z' ) s += c - ('a' - 'A'); else if( c >= 'A' && c <= 'Z' ) s += c; } auto replace = []( char const * const from, char const* to, char* const dst ) -> bool { auto const n = strlen( from ); if( strncmp( from, dst, n ) == 0 ) { strncpy( dst, to, n ); return true; } return false; }; auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool { auto const n = strlen( *from ); for( ; *from; ++from ) if( strncmp( *from, dst, n ) == 0 ) { memcpy( dst, to, n ); return true; } return false; }; auto isVowel = []( char const c ) -> bool { return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; }; size_t n = s.length(); replace( "MAC", "MCC", &s[0] ); replace( "KN", "NN", &s[0] ); replace( "K", "C", &s[0] ); char const* const prefix[] = { "PH", "PF", 0 }; multiReplace( prefix, "FF", &s[0] ); replace( "SCH", "SSS", &s[0] ); char const* const suffix1[] = { "EE", "IE", 0 }; char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 }; if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] )) { s.pop_back(); --n; } out += s[0]; char* vowels[] = { "A", "E", "I", "O", "U", 0 }; for( unsigned i = 1; i < n; ++i ) { char* const c = &s[i]; if( !replace( "EV", "AV", c ) ) multiReplace( vowels, "A", c ); replace( "Q", "G", c ); replace( "Z", "S", c ); replace( "M", "N", c ); if( !replace( "KN", "NN", c )) replace( "K", "C", c ); replace( "SCH", "SSS", c ); replace( "PH", "FF", c ); if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] ))) *c = s[i - 1]; if( *c == 'W' && isVowel( s[i - 1] )) *c = 'A'; if( out.back() != *c ) out += *c; } if( out.back() == 'S' || out.back() == 'A' ) out.pop_back(); n = out.length() - 2; if( out[n] == 'A' && out[n + 1] == 'Y' ) out = out.substr( 0, n ) + "Y"; return out; } int main() { static char const * const names[][2] = { { "Bishop", "BASAP" }, { "Carlson", "CARLSAN" }, { "Carr", "CAR" }, { "Chapman", "CAPNAN" }, { "Franklin", "FRANCLAN" }, { "Greene", "GRAN" }, { "Harper", "HARPAR" }, { "Jacobs", "JACAB" }, { "Larson", "LARSAN" }, { "Lawrence", "LARANC" }, { "Lawson", "LASAN" }, { "Louis, XVI", "LASXV" }, { "Lynch", "LYNC" }, { "Mackenzie", "MCANSY" }, { "Matthews", "MATA" }, { "McCormack", "MCARNAC" }, { "McDaniel", "MCDANAL" }, { "McDonald", "MCDANALD" }, { "Mclaughlin", "MCLAGLAN" }, { "Morrison", "MARASAN" }, { "O'Banion", "OBANAN" }, { "O'Brien", "OBRAN" }, { "Richards", "RACARD" }, { "Silva", "SALV" }, { "Watkins", "WATCAN" }, { "Wheeler", "WALAR" }, { "Willis", "WALA" }, { "brown, sr", "BRANSR" }, { "browne, III", "BRAN" }, { "browne, IV", "BRANAV" }, { "knight", "NAGT" }, { "mitchell", "MATCAL" }, { "o'daniel", "ODANAL" } }; for( auto const& name : names ) { auto const code = NYSIIS( name[0] ); std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code; if( code == std::string( name[1] )) std::cout << " ok"; else std::cout << " ERROR: " << name[1] << " expected"; std::cout << std::endl; } return 0; }
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}}; final static String Vowels = "AEIOU"; public static void main(String[] args) { stream(args).parallel().map(n -> transcode(n)).forEach(out::println); } static String transcode(String s) { int len = s.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z') sb.append((char) (c - 32)); else if (c >= 'A' && c <= 'Z') sb.append(c); } replace(sb, 0, first); replace(sb, sb.length() - 2, last); len = sb.length(); sb.append(" "); for (int i = 1; i < len; i++) { char prev = sb.charAt(i - 1); char curr = sb.charAt(i); char next = sb.charAt(i + 1); if (curr == 'E' && next == 'V') sb.replace(i, i + 2, "AF"); else if (isVowel(curr)) sb.setCharAt(i, 'A'); else if (curr == 'Q') sb.setCharAt(i, 'G'); else if (curr == 'Z') sb.setCharAt(i, 'S'); else if (curr == 'M') sb.setCharAt(i, 'N'); else if (curr == 'K' && next == 'N') sb.setCharAt(i, 'N'); else if (curr == 'K') sb.setCharAt(i, 'C'); else if (sb.indexOf("SCH", i) == i) sb.replace(i, i + 3, "SSS"); else if (curr == 'P' && next == 'H') sb.replace(i, i + 2, "FF"); else if (curr == 'H' && (!isVowel(prev) || !isVowel(next))) sb.setCharAt(i, prev); else if (curr == 'W' && isVowel(prev)) sb.setCharAt(i, prev); if (sb.charAt(i) == prev) { sb.deleteCharAt(i--); len--; } } sb.setLength(sb.length() - 1); int lastPos = sb.length() - 1; if (lastPos > 1) { if (sb.lastIndexOf("AY") == lastPos - 1) sb.delete(lastPos - 1, lastPos + 1).append("Y"); else if (sb.charAt(lastPos) == 'S') sb.setLength(lastPos); else if (sb.charAt(lastPos) == 'A') sb.setLength(lastPos); } if (sb.length() > 6) sb.insert(6, '[').append(']'); return String.format("%s -> %s", s, sb); } private static void replace(StringBuilder sb, int start, String[][] maps) { if (start >= 0) for (String[] map : maps) { if (sb.indexOf(map[0]) == start) { sb.replace(start, start + map[0].length(), map[1]); break; } } } private static boolean isVowel(char c) { return Vowels.indexOf(c) != -1; } }
Produce a functionally identical Java code for the snippet given in C.
#include <iostream> #include <iomanip> #include <string> std::string NYSIIS( std::string const& str ) { std::string s, out; s.reserve( str.length() ); for( auto const c : str ) { if( c >= 'a' && c <= 'z' ) s += c - ('a' - 'A'); else if( c >= 'A' && c <= 'Z' ) s += c; } auto replace = []( char const * const from, char const* to, char* const dst ) -> bool { auto const n = strlen( from ); if( strncmp( from, dst, n ) == 0 ) { strncpy( dst, to, n ); return true; } return false; }; auto multiReplace = []( char const* const* from, char const* to, char* const dst ) -> bool { auto const n = strlen( *from ); for( ; *from; ++from ) if( strncmp( *from, dst, n ) == 0 ) { memcpy( dst, to, n ); return true; } return false; }; auto isVowel = []( char const c ) -> bool { return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; }; size_t n = s.length(); replace( "MAC", "MCC", &s[0] ); replace( "KN", "NN", &s[0] ); replace( "K", "C", &s[0] ); char const* const prefix[] = { "PH", "PF", 0 }; multiReplace( prefix, "FF", &s[0] ); replace( "SCH", "SSS", &s[0] ); char const* const suffix1[] = { "EE", "IE", 0 }; char const* const suffix2[] = { "DT", "RT", "RD", "NT", "ND", 0 }; if( multiReplace( suffix1, "Y", &s[n - 2] ) || multiReplace( suffix2, "D", &s[n - 2] )) { s.pop_back(); --n; } out += s[0]; char* vowels[] = { "A", "E", "I", "O", "U", 0 }; for( unsigned i = 1; i < n; ++i ) { char* const c = &s[i]; if( !replace( "EV", "AV", c ) ) multiReplace( vowels, "A", c ); replace( "Q", "G", c ); replace( "Z", "S", c ); replace( "M", "N", c ); if( !replace( "KN", "NN", c )) replace( "K", "C", c ); replace( "SCH", "SSS", c ); replace( "PH", "FF", c ); if( *c == 'H' && (!isVowel( s[i - 1] ) || i + 1 >= n || !isVowel( s[i + 1] ))) *c = s[i - 1]; if( *c == 'W' && isVowel( s[i - 1] )) *c = 'A'; if( out.back() != *c ) out += *c; } if( out.back() == 'S' || out.back() == 'A' ) out.pop_back(); n = out.length() - 2; if( out[n] == 'A' && out[n + 1] == 'Y' ) out = out.substr( 0, n ) + "Y"; return out; } int main() { static char const * const names[][2] = { { "Bishop", "BASAP" }, { "Carlson", "CARLSAN" }, { "Carr", "CAR" }, { "Chapman", "CAPNAN" }, { "Franklin", "FRANCLAN" }, { "Greene", "GRAN" }, { "Harper", "HARPAR" }, { "Jacobs", "JACAB" }, { "Larson", "LARSAN" }, { "Lawrence", "LARANC" }, { "Lawson", "LASAN" }, { "Louis, XVI", "LASXV" }, { "Lynch", "LYNC" }, { "Mackenzie", "MCANSY" }, { "Matthews", "MATA" }, { "McCormack", "MCARNAC" }, { "McDaniel", "MCDANAL" }, { "McDonald", "MCDANALD" }, { "Mclaughlin", "MCLAGLAN" }, { "Morrison", "MARASAN" }, { "O'Banion", "OBANAN" }, { "O'Brien", "OBRAN" }, { "Richards", "RACARD" }, { "Silva", "SALV" }, { "Watkins", "WATCAN" }, { "Wheeler", "WALAR" }, { "Willis", "WALA" }, { "brown, sr", "BRANSR" }, { "browne, III", "BRAN" }, { "browne, IV", "BRANAV" }, { "knight", "NAGT" }, { "mitchell", "MATCAL" }, { "o'daniel", "ODANAL" } }; for( auto const& name : names ) { auto const code = NYSIIS( name[0] ); std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << code; if( code == std::string( name[1] )) std::cout << " ok"; else std::cout << " ERROR: " << name[1] << " expected"; std::cout << std::endl; } return 0; }
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}}; final static String Vowels = "AEIOU"; public static void main(String[] args) { stream(args).parallel().map(n -> transcode(n)).forEach(out::println); } static String transcode(String s) { int len = s.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z') sb.append((char) (c - 32)); else if (c >= 'A' && c <= 'Z') sb.append(c); } replace(sb, 0, first); replace(sb, sb.length() - 2, last); len = sb.length(); sb.append(" "); for (int i = 1; i < len; i++) { char prev = sb.charAt(i - 1); char curr = sb.charAt(i); char next = sb.charAt(i + 1); if (curr == 'E' && next == 'V') sb.replace(i, i + 2, "AF"); else if (isVowel(curr)) sb.setCharAt(i, 'A'); else if (curr == 'Q') sb.setCharAt(i, 'G'); else if (curr == 'Z') sb.setCharAt(i, 'S'); else if (curr == 'M') sb.setCharAt(i, 'N'); else if (curr == 'K' && next == 'N') sb.setCharAt(i, 'N'); else if (curr == 'K') sb.setCharAt(i, 'C'); else if (sb.indexOf("SCH", i) == i) sb.replace(i, i + 3, "SSS"); else if (curr == 'P' && next == 'H') sb.replace(i, i + 2, "FF"); else if (curr == 'H' && (!isVowel(prev) || !isVowel(next))) sb.setCharAt(i, prev); else if (curr == 'W' && isVowel(prev)) sb.setCharAt(i, prev); if (sb.charAt(i) == prev) { sb.deleteCharAt(i--); len--; } } sb.setLength(sb.length() - 1); int lastPos = sb.length() - 1; if (lastPos > 1) { if (sb.lastIndexOf("AY") == lastPos - 1) sb.delete(lastPos - 1, lastPos + 1).append("Y"); else if (sb.charAt(lastPos) == 'S') sb.setLength(lastPos); else if (sb.charAt(lastPos) == 'A') sb.setLength(lastPos); } if (sb.length() > 6) sb.insert(6, '[').append(']'); return String.format("%s -> %s", s, sb); } private static void replace(StringBuilder sb, int start, String[][] maps) { if (start >= 0) for (String[] map : maps) { if (sb.indexOf(map[0]) == start) { sb.replace(start, start + map[0].length(), map[1]); break; } } } private static boolean isVowel(char c) { return Vowels.indexOf(c) != -1; } }
Port the provided C code into Java while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <math.h> int power (int base, int exponent) { int result = 1; for (int i = 1; i <= exponent; i++) { result *= base; } return result; } int is_disarium (int num) { int n = num; int sum = 0; int len = n <= 9 ? 1 : floor(log10(n)) + 1; while (n > 0) { sum += power(n % 10, len); n /= 10; len--; } return num == sum; } int main() { int count = 0; int i = 0; while (count < 19) { if (is_disarium(i)) { printf("%d ", i); count++; } i++; } printf("%s\n", "\n"); }
import java.lang.Math; public class DisariumNumbers { public static boolean is_disarium(int num) { int n = num; int len = Integer.toString(n).length(); int sum = 0; int i = 1; while (n > 0) { sum += Math.pow(n % 10, len - i + 1); n /= 10; i ++; } return sum == num; } public static void main(String[] args) { int i = 0; int count = 0; while (count <= 18) { if (is_disarium(i)) { System.out.printf("%d ", i); count++; } i++; } System.out.printf("%s", "\n"); } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <math.h> int power (int base, int exponent) { int result = 1; for (int i = 1; i <= exponent; i++) { result *= base; } return result; } int is_disarium (int num) { int n = num; int sum = 0; int len = n <= 9 ? 1 : floor(log10(n)) + 1; while (n > 0) { sum += power(n % 10, len); n /= 10; len--; } return num == sum; } int main() { int count = 0; int i = 0; while (count < 19) { if (is_disarium(i)) { printf("%d ", i); count++; } i++; } printf("%s\n", "\n"); }
import java.lang.Math; public class DisariumNumbers { public static boolean is_disarium(int num) { int n = num; int len = Integer.toString(n).length(); int sum = 0; int i = 1; while (n > 0) { sum += Math.pow(n % 10, len - i + 1); n /= 10; i ++; } return sum == num; } public static void main(String[] args) { int i = 0; int count = 0; while (count <= 18) { if (is_disarium(i)) { System.out.printf("%d ", i); count++; } i++; } System.out.printf("%s", "\n"); } }
Maintain the same structure and functionality when rewriting this code in Java.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<time.h> #define pi M_PI int main(){ time_t t; double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0; int i,iter,choice,numSides; printf("Enter number of sides : "); scanf("%d",&numSides); printf("Enter polygon side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); scanf("%d",&iter); initwindow(windowSide,windowSide,"Polygon Chaos"); vertices = (double**)malloc(numSides*sizeof(double*)); for(i=0;i<numSides;i++){ vertices[i] = (double*)malloc(2 * sizeof(double)); vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides); vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides); sumX+= vertices[i][0]; sumY+= vertices[i][1]; putpixel(vertices[i][0],vertices[i][1],15); } srand((unsigned)time(&t)); seedX = sumX/numSides; seedY = sumY/numSides; putpixel(seedX,seedY,15); for(i=0;i<iter;i++){ choice = rand()%numSides; seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1); seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1); putpixel(seedX,seedY,15); } free(vertices); getch(); closegraph(); return 0; }
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees072) * 2); final int margin = 20; int limit = 0; Random r = new Random(); public SierpinskiPentagon() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(3000, (ActionEvent e) -> { limit++; if (limit >= 5) limit = 0; repaint(); }).start(); } void drawPentagon(Graphics2D g, double x, double y, double side, int depth) { double angle = 3 * degrees072; if (depth == 0) { Path2D p = new Path2D.Double(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { x = x + cos(angle) * side; y = y - sin(angle) * side; p.lineTo(x, y); angle += degrees072; } g.setColor(RandomHue.next()); g.fill(p); } else { side *= scaleFactor; double distance = side + side * cos(degrees072) * 2; for (int i = 0; i < 5; i++) { x = x + cos(angle) * distance; y = y - sin(angle) * distance; drawPentagon(g, x, y, side, depth - 1); angle += degrees072; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int w = getWidth(); double radius = w / 2 - 2 * margin; double side = radius * sin(PI / 5) * 2; drawPentagon(g, w / 2, 3 * margin, side, limit); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Sierpinski Pentagon"); f.setResizable(true); f.add(new SierpinskiPentagon(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } } class RandomHue { final static double goldenRatioConjugate = (sqrt(5) - 1) / 2; private static double hue = Math.random(); static Color next() { hue = (hue + goldenRatioConjugate) % 1; return Color.getHSBColor((float) hue, 1, 1); } }
Write the same code in Java as shown below in C.
typedef unsigned int histogram_t; typedef histogram_t *histogram; #define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] ) histogram get_histogram(grayimage im); luminance histogram_median(histogram h);
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public enum ImageProcessing { ; public static void main(String[] args) throws IOException { BufferedImage img = ImageIO.read(new File("example.png")); BufferedImage bwimg = toBlackAndWhite(img); ImageIO.write(bwimg, "png", new File("example-bw.png")); } private static int luminance(int rgb) { int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF; return (r + b + g) / 3; } private static BufferedImage toBlackAndWhite(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); int[] histo = computeHistogram(img); int median = getMedian(width * height, histo); BufferedImage bwimg = new BufferedImage(width, height, img.getType()); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000); } } return bwimg; } private static int[] computeHistogram(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); int[] histo = new int[256]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { histo[luminance(img.getRGB(x, y))]++; } } return histo; } private static int getMedian(int total, int[] histo) { int median = 0; int sum = 0; for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) { sum += histo[i]; median++; } return median; } }
Generate a Java translation of this C snippet without changing its computational steps.
HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);
import java.util.concurrent.Semaphore; public class VolatileClass{ public Semaphore mutex = new Semaphore(1); public void needsToBeSynched(){ } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <signal.h> #include <time.h> #include <sys/time.h> struct timeval start, last; inline int64_t tv_to_u(struct timeval s) { return s.tv_sec * 1000000 + s.tv_usec; } inline struct timeval u_to_tv(int64_t x) { struct timeval s; s.tv_sec = x / 1000000; s.tv_usec = x % 1000000; return s; } void draw(int dir, int64_t period, int64_t cur, int64_t next) { int len = 40 * (next - cur) / period; int s, i; if (len > 20) len = 40 - len; s = 20 + (dir ? len : -len); printf("\033[H"); for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-'); } void beat(int delay) { struct timeval tv = start; int dir = 0; int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay; int64_t draw_interval = 20000; printf("\033[H\033[J"); while (1) { gettimeofday(&tv, 0); slp = next - tv_to_u(tv) - corr; usleep(slp); gettimeofday(&tv, 0); putchar(7); fflush(stdout); printf("\033[5;1Hdrift: %d compensate: %d (usec) ", (int)d, (int)corr); dir = !dir; cur = tv_to_u(tv); d = cur - next; corr = (corr + d) / 2; next += delay; while (cur + d + draw_interval < next) { usleep(draw_interval); gettimeofday(&tv, 0); cur = tv_to_u(tv); draw(dir, delay, cur, next); fflush(stdout); } } } int main(int c, char**v) { int bpm; if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60; if (bpm > 600) { fprintf(stderr, "frequency %d too high\n", bpm); exit(1); } gettimeofday(&start, 0); last = start; beat(60 * 1000000 / bpm); return 0; }
class Metronome{ double bpm; int measure, counter; public Metronome(double bpm, int measure){ this.bpm = bpm; this.measure = measure; } public void start(){ while(true){ try { Thread.sleep((long)(1000*(60.0/bpm))); }catch(InterruptedException e) { e.printStackTrace(); } counter++; if (counter%measure==0){ System.out.println("TICK"); }else{ System.out.println("TOCK"); } } } } public class test { public static void main(String[] args) { Metronome metronome1 = new Metronome(120,4); metronome1.start(); } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define LIMIT 100 typedef int bool; int compareInts(const void *a, const void *b) { int aa = *(int *)a; int bb = *(int *)b; return aa - bb; } bool contains(int a[], int b, size_t len) { int i; for (i = 0; i < len; ++i) { if (a[i] == b) return TRUE; } return FALSE; } int gcd(int a, int b) { while (a != b) { if (a > b) a -= b; else b -= a; } return a; } bool areSame(int s[], int t[], size_t len) { int i; qsort(s, len, sizeof(int), compareInts); qsort(t, len, sizeof(int), compareInts); for (i = 0; i < len; ++i) { if (s[i] != t[i]) return FALSE; } return TRUE; } int main() { int s, n, i; int starts[5] = {2, 5, 7, 9, 10}; int ekg[5][LIMIT]; for (s = 0; s < 5; ++s) { ekg[s][0] = 1; ekg[s][1] = starts[s]; for (n = 2; n < LIMIT; ++n) { for (i = 2; ; ++i) { if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) { ekg[s][n] = i; break; } } } printf("EKG(%2d): [", starts[s]); for (i = 0; i < 30; ++i) printf("%d ", ekg[s][i]); printf("\b]\n"); } for (i = 2; i < LIMIT; ++i) { if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) { printf("\nEKG(5) and EKG(7) converge at term %d\n", i + 1); return 0; } } printf("\nEKG5(5) and EKG(7) do not converge within %d terms\n", LIMIT); return 0; }
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class EKGSequenceConvergence { public static void main(String[] args) { System.out.println("Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10]."); for ( int i : new int[] {2, 5, 7, 9, 10} ) { System.out.printf("EKG[%d] = %s%n", i, ekg(i, 10)); } System.out.println("Calculate and show here at which term EKG[5] and EKG[7] converge."); List<Integer> ekg5 = ekg(5, 100); List<Integer> ekg7 = ekg(7, 100); for ( int i = 1 ; i < ekg5.size() ; i++ ) { if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) { System.out.printf("EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n", 5, i+1, 7, i+1, ekg5.get(i)); break; } } } private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) { List<Integer> list1 = new ArrayList<>(seq1.subList(0, n)); Collections.sort(list1); List<Integer> list2 = new ArrayList<>(seq2.subList(0, n)); Collections.sort(list2); for ( int i = 0 ; i < n ; i++ ) { if ( list1.get(i) != list2.get(i) ) { return false; } } return true; } private static List<Integer> ekg(int two, int maxN) { List<Integer> result = new ArrayList<>(); result.add(1); result.add(two); Map<Integer,Integer> seen = new HashMap<>(); seen.put(1, 1); seen.put(two, 1); int minUnseen = two == 2 ? 3 : 2; int prev = two; for ( int n = 3 ; n <= maxN ; n++ ) { int test = minUnseen - 1; while ( true ) { test++; if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) { result.add(test); seen.put(test, n); prev = test; if ( minUnseen == test ) { do { minUnseen++; } while ( seen.containsKey(minUnseen) ); } break; } } } return result; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
#include <stdio.h> #include <string.h> int repstr(char *str) { if (!str) return 0; size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; } return 0; } int main(void) { char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" }; size_t strslen = sizeof(strs) / sizeof(strs[0]); size_t i; for (i = 0; i < strslen; ++i) { int n = repstr(strs[i]); if (n) printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]); else printf("\"%s\" = not a rep-string\n", strs[i]); } return 0; }
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s : %s%n", s, repString(s)); } static String repString(String s) { int len = s.length(); outer: for (int part = len / 2; part > 0; part--) { int tail = len % part; if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail))) continue; for (int j = 0; j < len / part - 1; j++) { int a = j * part; int b = (j + 1) * part; int c = (j + 2) * part; if (!s.substring(a, b).equals(s.substring(b, c))) continue outer; } return s.substring(0, part); } return "none"; } }
Change the following C code into Java without altering its purpose.
#include <stdio.h> #include <unistd.h> int main() { int i; printf("\033[?1049h\033[H"); printf("Alternate screen buffer\n"); for (i = 5; i; i--) { printf("\rgoing back in %d...", i); fflush(stdout); sleep(1); } printf("\033[?1049l"); return 0; }
public class PreserveScreen { public static void main(String[] args) throws InterruptedException { System.out.print("\033[?1049h\033[H"); System.out.println("Alternate screen buffer\n"); for (int i = 5; i > 0; i--) { String s = (i > 1) ? "s" : ""; System.out.printf("\rgoing back in %d second%s...", i, s); Thread.sleep(1000); } System.out.print("\033[?1049l"); } }
Convert this C block to Java, preserving its control flow and logic.
char ch = 'z';
char a = 'a'; String b = "abc"; char doubleQuote = '"'; char singleQuote = '\''; String singleQuotes = "''"; String doubleQuotes = "\"\"";
Maintain the same structure and functionality when rewriting this code in Java.
char ch = 'z';
char a = 'a'; String b = "abc"; char doubleQuote = '"'; char singleQuote = '\''; String singleQuotes = "''"; String doubleQuotes = "\"\"";
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 32 typedef struct string_tag { size_t length; char str[MAX_WORD_SIZE]; } string_t; void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int hamming_distance(const string_t* str1, const string_t* str2) { size_t len1 = str1->length; size_t len2 = str2->length; if (len1 != len2) return 0; int count = 0; const char* s1 = str1->str; const char* s2 = str2->str; for (size_t i = 0; i < len1; ++i) { if (s1[i] != s2[i]) ++count; if (count == 2) break; } return count; } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; FILE* in = fopen(filename, "r"); if (!in) { perror(filename); return EXIT_FAILURE; } char line[MAX_WORD_SIZE]; size_t size = 0, capacity = 1024; string_t* dictionary = xmalloc(sizeof(string_t) * capacity); while (fgets(line, sizeof(line), in)) { if (size == capacity) { capacity *= 2; dictionary = xrealloc(dictionary, sizeof(string_t) * capacity); } size_t len = strlen(line) - 1; if (len > 11) { string_t* str = &dictionary[size]; str->length = len; memcpy(str->str, line, len); str->str[len] = '\0'; ++size; } } fclose(in); printf("Changeable words in %s:\n", filename); int n = 1; for (size_t i = 0; i < size; ++i) { const string_t* str1 = &dictionary[i]; for (size_t j = 0; j < size; ++j) { const string_t* str2 = &dictionary[j]; if (i != j && hamming_distance(str1, str2) == 1) printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str); } } free(dictionary); return EXIT_SUCCESS; }
import java.io.*; import java.util.*; public class ChangeableWords { public static void main(String[] args) { try { final String fileName = "unixdict.txt"; List<String> dictionary = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { if (line.length() > 11) dictionary.add(line); } } System.out.printf("Changeable words in %s:\n", fileName); int n = 1; for (String word1 : dictionary) { for (String word2 : dictionary) { if (word1 != word2 && hammingDistance(word1, word2) == 1) System.out.printf("%2d: %-14s -> %s\n", n++, word1, word2); } } } catch (Exception e) { e.printStackTtexture(); } } private static int hammingDistance(String str1, String str2) { int len1 = str1.length(); int len2 = str2.length(); if (len1 != len2) return 0; int count = 0; for (int i = 0; i < len1; ++i) { if (str1.charAt(i) != str2.charAt(i)) ++count; if (count == 2) break; } return count; } }
Please provide an equivalent version of this C code in Java.
#include<windows.h> #include<unistd.h> #include<stdio.h> const char g_szClassName[] = "weirdWindow"; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd[3]; MSG Msg; int i,x=0,y=0; char str[3][100]; int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.", "If you can see two blank windows just behind this message box, you are in luck.", "Let's get started....", "Yes, you will be seeing a lot of me :)", "Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)", "Let's compare the windows for equality.", "Now let's hide Window 1.", "Now let's see Window 1 again.", "Let's close Window 2, bye, bye, Number 2 !", "Let's minimize Window 1.", "Now let's maximize Window 1.", "And finally we come to the fun part, watch Window 1 move !", "Let's double Window 1 in size for all the good work.", "That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"}; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } for(i=0;i<2;i++){ sprintf(str[i],"Window Number %d",i+1); hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL); if(hwnd[i] == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd[i], nCmdShow); UpdateWindow(hwnd[i]); } for(i=0;i<6;i++){ MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); } if(hwnd[0]==hwnd[1]) MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); else MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_HIDE); MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_SHOW); MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[1], SW_HIDE); MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MINIMIZE); MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MAXIMIZE); MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_RESTORE); while(x!=maxX/2||y!=maxY/2){ if(x<maxX/2) x++; if(y<maxY/2) y++; MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0); sleep(10); } MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MoveWindow(hwnd[0],0,0,maxX, maxY,0); MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class WindowController extends JFrame { public static void main( final String[] args ) { EventQueue.invokeLater( () -> new WindowController() ); } private JComboBox<ControlledWindow> list; private class ControlButton extends JButton { private ControlButton( final String name ) { super( new AbstractAction( name ) { public void actionPerformed( final ActionEvent e ) { try { WindowController.class.getMethod( "do" + name ) .invoke ( WindowController.this ); } catch ( final Exception x ) { x.printStackTrace(); } } } ); } } public WindowController() { super( "Controller" ); final JPanel main = new JPanel(); final JPanel controls = new JPanel(); setLocationByPlatform( true ); setResizable( false ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout( 3, 3 ) ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH ); main.add( list = new JComboBox<>() ); add( main, BorderLayout.CENTER ); controls.setLayout( new GridLayout( 0, 1, 3, 3 ) ); controls.add( new ControlButton( "Add" ) ); controls.add( new ControlButton( "Hide" ) ); controls.add( new ControlButton( "Show" ) ); controls.add( new ControlButton( "Close" ) ); controls.add( new ControlButton( "Maximise" ) ); controls.add( new ControlButton( "Minimise" ) ); controls.add( new ControlButton( "Move" ) ); controls.add( new ControlButton( "Resize" ) ); add( controls, BorderLayout.EAST ); pack(); setVisible( true ); } private static class ControlledWindow extends JFrame { private int num; public ControlledWindow( final int num ) { super( Integer.toString( num ) ); this.num = num; setLocationByPlatform( true ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); add( new JLabel( "I am window " + num + ". Use the controller to control me." ) ); pack(); setVisible( true ); } public String toString() { return "Window " + num; } } public void doAdd() { list.addItem( new ControlledWindow( list.getItemCount () + 1 ) ); pack(); } public void doHide() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( false ); } public void doShow() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( true ); } public void doClose() { final JFrame window = getWindow(); if ( null == window ) { return; } window.dispose(); } public void doMinimise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setState( Frame.ICONIFIED ); } public void doMaximise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setExtendedState( Frame.MAXIMIZED_BOTH ); } public void doMove() { final JFrame window = getWindow(); if ( null == window ) { return; } final int hPos = getInt( "Horizontal position?" ); if ( -1 == hPos ) { return; } final int vPos = getInt( "Vertical position?" ); if ( -1 == vPos ) { return; } window.setLocation ( hPos, vPos ); } public void doResize() { final JFrame window = getWindow(); if ( null == window ) { return; } final int width = getInt( "Width?" ); if ( -1 == width ) { return; } final int height = getInt( "Height?" ); if ( -1 == height ) { return; } window.setBounds ( window.getX(), window.getY(), width, height ); } private JFrame getWindow() { final JFrame window = ( JFrame ) list.getSelectedItem(); if ( null == window ) { JOptionPane.showMessageDialog( this, "Add a window first" ); } return window; } private int getInt(final String prompt) { final String s = JOptionPane.showInputDialog( prompt ); if ( null == s ) { return -1; } try { return Integer.parseInt( s ); } catch ( final NumberFormatException x ) { JOptionPane.showMessageDialog( this, "Not a number" ); return -1; } } }
Maintain the same structure and functionality when rewriting this code in Java.
#include<windows.h> #include<unistd.h> #include<stdio.h> const char g_szClassName[] = "weirdWindow"; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd[3]; MSG Msg; int i,x=0,y=0; char str[3][100]; int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); char messages[15][180] = {"Welcome to the Rosettacode Window C implementation.", "If you can see two blank windows just behind this message box, you are in luck.", "Let's get started....", "Yes, you will be seeing a lot of me :)", "Now to get started with the tasks, the windows here are stored in an array of type HWND, the array is called hwnd (yes, I know it's very innovative.)", "Let's compare the windows for equality.", "Now let's hide Window 1.", "Now let's see Window 1 again.", "Let's close Window 2, bye, bye, Number 2 !", "Let's minimize Window 1.", "Now let's maximize Window 1.", "And finally we come to the fun part, watch Window 1 move !", "Let's double Window 1 in size for all the good work.", "That's all folks ! (You still have to close that window, that was not part of the contract, sue me :D )"}; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } for(i=0;i<2;i++){ sprintf(str[i],"Window Number %d",i+1); hwnd[i] = CreateWindow(g_szClassName,str[i],WS_OVERLAPPEDWINDOW,i*maxX/2 , 0, maxX/2-10, maxY/2-10,NULL, NULL, hInstance, NULL); if(hwnd[i] == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!",MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd[i], nCmdShow); UpdateWindow(hwnd[i]); } for(i=0;i<6;i++){ MessageBox(NULL, messages[i], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); } if(hwnd[0]==hwnd[1]) MessageBox(NULL, "Window 1 and 2 are equal.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); else MessageBox(NULL, "Nope, they are not.", "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MessageBox(NULL, messages[6], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_HIDE); MessageBox(NULL, messages[7], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_SHOW); MessageBox(NULL, messages[8], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[1], SW_HIDE); MessageBox(NULL, messages[9], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MINIMIZE); MessageBox(NULL, messages[10], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_MAXIMIZE); MessageBox(NULL, messages[11], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); ShowWindow(hwnd[0], SW_RESTORE); while(x!=maxX/2||y!=maxY/2){ if(x<maxX/2) x++; if(y<maxY/2) y++; MoveWindow(hwnd[0],x,y,maxX/2-10, maxY/2-10,0); sleep(10); } MessageBox(NULL, messages[12], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); MoveWindow(hwnd[0],0,0,maxX, maxY,0); MessageBox(NULL, messages[13], "Info",MB_APPLMODAL| MB_ICONINFORMATION | MB_OK); while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Frame; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; public class WindowController extends JFrame { public static void main( final String[] args ) { EventQueue.invokeLater( () -> new WindowController() ); } private JComboBox<ControlledWindow> list; private class ControlButton extends JButton { private ControlButton( final String name ) { super( new AbstractAction( name ) { public void actionPerformed( final ActionEvent e ) { try { WindowController.class.getMethod( "do" + name ) .invoke ( WindowController.this ); } catch ( final Exception x ) { x.printStackTrace(); } } } ); } } public WindowController() { super( "Controller" ); final JPanel main = new JPanel(); final JPanel controls = new JPanel(); setLocationByPlatform( true ); setResizable( false ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout( 3, 3 ) ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); add( new JLabel( "Add windows and control them." ), BorderLayout.NORTH ); main.add( list = new JComboBox<>() ); add( main, BorderLayout.CENTER ); controls.setLayout( new GridLayout( 0, 1, 3, 3 ) ); controls.add( new ControlButton( "Add" ) ); controls.add( new ControlButton( "Hide" ) ); controls.add( new ControlButton( "Show" ) ); controls.add( new ControlButton( "Close" ) ); controls.add( new ControlButton( "Maximise" ) ); controls.add( new ControlButton( "Minimise" ) ); controls.add( new ControlButton( "Move" ) ); controls.add( new ControlButton( "Resize" ) ); add( controls, BorderLayout.EAST ); pack(); setVisible( true ); } private static class ControlledWindow extends JFrame { private int num; public ControlledWindow( final int num ) { super( Integer.toString( num ) ); this.num = num; setLocationByPlatform( true ); getRootPane().setBorder( new EmptyBorder( 3, 3, 3, 3 ) ); setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); add( new JLabel( "I am window " + num + ". Use the controller to control me." ) ); pack(); setVisible( true ); } public String toString() { return "Window " + num; } } public void doAdd() { list.addItem( new ControlledWindow( list.getItemCount () + 1 ) ); pack(); } public void doHide() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( false ); } public void doShow() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setVisible( true ); } public void doClose() { final JFrame window = getWindow(); if ( null == window ) { return; } window.dispose(); } public void doMinimise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setState( Frame.ICONIFIED ); } public void doMaximise() { final JFrame window = getWindow(); if ( null == window ) { return; } window.setExtendedState( Frame.MAXIMIZED_BOTH ); } public void doMove() { final JFrame window = getWindow(); if ( null == window ) { return; } final int hPos = getInt( "Horizontal position?" ); if ( -1 == hPos ) { return; } final int vPos = getInt( "Vertical position?" ); if ( -1 == vPos ) { return; } window.setLocation ( hPos, vPos ); } public void doResize() { final JFrame window = getWindow(); if ( null == window ) { return; } final int width = getInt( "Width?" ); if ( -1 == width ) { return; } final int height = getInt( "Height?" ); if ( -1 == height ) { return; } window.setBounds ( window.getX(), window.getY(), width, height ); } private JFrame getWindow() { final JFrame window = ( JFrame ) list.getSelectedItem(); if ( null == window ) { JOptionPane.showMessageDialog( this, "Add a window first" ); } return window; } private int getInt(final String prompt) { final String s = JOptionPane.showInputDialog( prompt ); if ( null == s ) { return -1; } try { return Integer.parseInt( s ); } catch ( final NumberFormatException x ) { JOptionPane.showMessageDialog( this, "Not a number" ); return -1; } } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdbool.h> bool isPrime(int n) { int d; if (n < 2) return false; if (!(n%2)) return n == 2; if (!(n%3)) return n == 3; d = 5; while (d*d <= n) { if (!(n%d)) return false; d += 2; if (!(n%d)) return false; d += 4; } return true; } int main() { int i, lastSpecial = 3, lastGap = 1; printf("Special primes under 1,050:\n"); printf("Prime1 Prime2 Gap\n"); printf("%6d %6d %3d\n", 2, 3, lastGap); for (i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } }
class SpecialPrimes { 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; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; d += 4; } return true; } public static void main(String[] args) { System.out.println("Special primes under 1,050:"); System.out.println("Prime1 Prime2 Gap"); int lastSpecial = 3; int lastGap = 1; System.out.printf("%6d %6d %3d\n", 2, 3, lastGap); for (int i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } } }
Write a version of this C function in Java with identical behavior.
#include <stdio.h> #include <stdbool.h> bool isPrime(int n) { int d; if (n < 2) return false; if (!(n%2)) return n == 2; if (!(n%3)) return n == 3; d = 5; while (d*d <= n) { if (!(n%d)) return false; d += 2; if (!(n%d)) return false; d += 4; } return true; } int main() { int i, lastSpecial = 3, lastGap = 1; printf("Special primes under 1,050:\n"); printf("Prime1 Prime2 Gap\n"); printf("%6d %6d %3d\n", 2, 3, lastGap); for (i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } }
class SpecialPrimes { 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; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; d += 4; } return true; } public static void main(String[] args) { System.out.println("Special primes under 1,050:"); System.out.println("Prime1 Prime2 Gap"); int lastSpecial = 3; int lastGap = 1; System.out.printf("%6d %6d %3d\n", 2, 3, lastGap); for (int i = 5; i < 1050; i += 2) { if (isPrime(i) && (i-lastSpecial) > lastGap) { lastGap = i - lastSpecial; System.out.printf("%6d %6d %3d\n", lastSpecial, i, lastGap); lastSpecial = i; } } } }
Write the same code in Java as shown below in C.
#include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #define MAX(x,y) ((x) > (y) ? (x) : (y)) #define MIN(x,y) ((x) < (y) ? (x) : (y)) size_t base20(unsigned int n, uint8_t *out) { uint8_t *start = out; do {*out++ = n % 20;} while (n /= 20); size_t length = out - start; while (out > start) { uint8_t x = *--out; *out = *start; *start++ = x; } return length; } void make_digit(int n, char *place, size_t line_length) { static const char *parts[] = {" "," . "," .. ","... ","....","----"}; int i; for (i=4; i>0; i--, n -= 5) memcpy(place + i*line_length, parts[MAX(0, MIN(5, n))], 4); if (n == -20) place[4 * line_length + 1] = '@'; } char *mayan(unsigned int n) { if (n == 0) return NULL; uint8_t digits[15]; size_t n_digits = base20(n, digits); size_t line_length = n_digits*5 + 2; char *str = malloc(line_length * 6 + 1); if (str == NULL) return NULL; str[line_length * 6] = 0; char *ptr; unsigned int i; for (ptr=str, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "+----", 5); memcpy(ptr-5, "+\n", 2); memcpy(str+5*line_length, str, line_length); for (ptr=str+line_length, i=0; i<line_length; i+=5, ptr+=5) memcpy(ptr, "| ", 5); memcpy(ptr-5, "|\n", 2); memcpy(str+2*line_length, str+line_length, line_length); memcpy(str+3*line_length, str+line_length, 2*line_length); for (i=0; i<n_digits; i++) make_digit(digits[i], str+1+5*i, line_length); return str; } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: mayan <number>\n"); return 1; } int i = atoi(argv[1]); if (i <= 0) { fprintf(stderr, "number must be positive\n"); return 1; } char *m = mayan(i); printf("%s",m); free(m); return 0; }
import java.math.BigInteger; public class MayanNumerals { public static void main(String[] args) { for ( long base10 : new long[] {4005, 8017, 326205, 886205, 1000000000, 1081439556L, 26960840421L, 503491211079L }) { displayMyan(BigInteger.valueOf(base10)); System.out.printf("%n"); } } private static char[] digits = "0123456789ABCDEFGHJK".toCharArray(); private static BigInteger TWENTY = BigInteger.valueOf(20); private static void displayMyan(BigInteger numBase10) { System.out.printf("As base 10: %s%n", numBase10); String numBase20 = ""; while ( numBase10.compareTo(BigInteger.ZERO) > 0 ) { numBase20 = digits[numBase10.mod(TWENTY).intValue()] + numBase20; numBase10 = numBase10.divide(TWENTY); } System.out.printf("As base 20: %s%nAs Mayan:%n", numBase20); displayMyanLine1(numBase20); displayMyanLine2(numBase20); displayMyanLine3(numBase20); displayMyanLine4(numBase20); displayMyanLine5(numBase20); displayMyanLine6(numBase20); } private static char boxUL = Character.toChars(9556)[0]; private static char boxTeeUp = Character.toChars(9574)[0]; private static char boxUR = Character.toChars(9559)[0]; private static char boxHorz = Character.toChars(9552)[0]; private static char boxVert = Character.toChars(9553)[0]; private static char theta = Character.toChars(952)[0]; private static char boxLL = Character.toChars(9562)[0]; private static char boxLR = Character.toChars(9565)[0]; private static char boxTeeLow = Character.toChars(9577)[0]; private static char bullet = Character.toChars(8729)[0]; private static char dash = Character.toChars(9472)[0]; private static void displayMyanLine1(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxUL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeUp : boxUR); } System.out.println(sb.toString()); } private static String getBullet(int count) { StringBuilder sb = new StringBuilder(); switch ( count ) { case 1: sb.append(" " + bullet + " "); break; case 2: sb.append(" " + bullet + bullet + " "); break; case 3: sb.append("" + bullet + bullet + bullet + " "); break; case 4: sb.append("" + bullet + bullet + bullet + bullet); break; default: throw new IllegalArgumentException("Must be 1-4: " + count); } return sb.toString(); } private static void displayMyanLine2(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'G': sb.append(getBullet(1)); break; case 'H': sb.append(getBullet(2)); break; case 'J': sb.append(getBullet(3)); break; case 'K': sb.append(getBullet(4)); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static String DASH = getDash(); private static String getDash() { StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < 4 ; i++ ) { sb.append(dash); } return sb.toString(); } private static void displayMyanLine3(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case 'B': sb.append(getBullet(1)); break; case 'C': sb.append(getBullet(2)); break; case 'D': sb.append(getBullet(3)); break; case 'E': sb.append(getBullet(4)); break; case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine4(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '6': sb.append(getBullet(1)); break; case '7': sb.append(getBullet(2)); break; case '8': sb.append(getBullet(3)); break; case '9': sb.append(getBullet(4)); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine5(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxVert); } switch ( chars[i] ) { case '0': sb.append(" " + theta + " "); break; case '1': sb.append(getBullet(1)); break; case '2': sb.append(getBullet(2)); break; case '3': sb.append(getBullet(3)); break; case '4': sb.append(getBullet(4)); break; case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'J': case 'K': sb.append(DASH); break; default : sb.append(" "); } sb.append(boxVert); } System.out.println(sb.toString()); } private static void displayMyanLine6(String base20) { char[] chars = base20.toCharArray(); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < chars.length ; i++ ) { if ( i == 0 ) { sb.append(boxLL); } for ( int j = 0 ; j < 4 ; j++ ) { sb.append(boxHorz); } sb.append(i < chars.length-1 ? boxTeeLow : boxLR); } System.out.println(sb.toString()); } }
Port the following code from C to Java with equivalent syntax and logic.
#include <stdio.h> int a[17][17], idx[4]; int find_group(int type, int min_n, int max_n, int depth) { int i, n; if (depth == 4) { printf("totally %sconnected group:", type ? "" : "un"); for (i = 0; i < 4; i++) printf(" %d", idx[i]); putchar('\n'); return 1; } for (i = min_n; i < max_n; i++) { for (n = 0; n < depth; n++) if (a[idx[n]][i] != type) break; if (n == depth) { idx[n] = i; if (find_group(type, 1, max_n, depth + 1)) return 1; } } return 0; } int main() { int i, j, k; const char *mark = "01-"; for (i = 0; i < 17; i++) a[i][i] = 2; for (k = 1; k <= 8; k <<= 1) { for (i = 0; i < 17; i++) { j = (i + k) % 17; a[i][j] = a[j][i] = 1; } } for (i = 0; i < 17; i++) { for (j = 0; j < 17; j++) printf("%c ", mark[a[i][j]]); putchar('\n'); } for (i = 0; i < 17; i++) { idx[0] = i; if (find_group(1, i+1, 17, 1) || find_group(0, i+1, 17, 1)) { puts("no good"); return 0; } } puts("all good"); return 0; }
import java.util.Arrays; import java.util.stream.IntStream; public class RamseysTheorem { static char[][] createMatrix() { String r = "-" + Integer.toBinaryString(53643); int len = r.length(); return IntStream.range(0, len) .mapToObj(i -> r.substring(len - i) + r.substring(0, len - i)) .map(String::toCharArray) .toArray(char[][]::new); } static String ramseyCheck(char[][] mat) { int len = mat.length; char[] connectivity = "------".toCharArray(); for (int a = 0; a < len; a++) { for (int b = 0; b < len; b++) { if (a == b) continue; connectivity[0] = mat[a][b]; for (int c = 0; c < len; c++) { if (a == c || b == c) continue; connectivity[1] = mat[a][c]; connectivity[2] = mat[b][c]; for (int d = 0; d < len; d++) { if (a == d || b == d || c == d) continue; connectivity[3] = mat[a][d]; connectivity[4] = mat[b][d]; connectivity[5] = mat[c][d]; String conn = new String(connectivity); if (conn.indexOf('0') == -1) return String.format("Fail, found wholly connected: " + "%d %d %d %d", a, b, c, d); else if (conn.indexOf('1') == -1) return String.format("Fail, found wholly unconnected: " + "%d %d %d %d", a, b, c, d); } } } } return "Satisfies Ramsey condition."; } public static void main(String[] a) { char[][] mat = createMatrix(); for (char[] s : mat) System.out.println(Arrays.toString(s)); System.out.println(ramseyCheck(mat)); } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include<windows.h> #include<stdio.h> int main() { printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN)); return 0; }
import java.awt.*; import javax.swing.JFrame; public class Test extends JFrame { public static void main(String[] args) { new Test(); } Test() { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); System.out.println("Physical screen size: " + screenSize); Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration()); System.out.println("Insets: " + insets); screenSize.width -= (insets.left + insets.right); screenSize.height -= (insets.top + insets.bottom); System.out.println("Max available: " + screenSize); } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdint.h> #include <stdio.h> #include <glib.h> typedef struct named_number_tag { const char* name; uint64_t number; } named_number; const named_number named_numbers[] = { { "hundred", 100 }, { "thousand", 1000 }, { "million", 1000000 }, { "billion", 1000000000 }, { "trillion", 1000000000000 }, { "quadrillion", 1000000000000000ULL }, { "quintillion", 1000000000000000000ULL } }; const named_number* get_named_number(uint64_t n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_number); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } size_t append_number_name(GString* str, uint64_t n) { static const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; static const char* tens[] = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; size_t len = str->len; if (n < 20) { g_string_append(str, small[n]); } else if (n < 100) { g_string_append(str, tens[n/10 - 2]); if (n % 10 != 0) { g_string_append_c(str, '-'); g_string_append(str, small[n % 10]); } } else { const named_number* num = get_named_number(n); uint64_t p = num->number; append_number_name(str, n/p); g_string_append_c(str, ' '); g_string_append(str, num->name); if (n % p != 0) { g_string_append_c(str, ' '); append_number_name(str, n % p); } } return str->len - len; } GString* magic(uint64_t n) { GString* str = g_string_new(NULL); for (unsigned int i = 0; ; ++i) { size_t count = append_number_name(str, n); if (i == 0) str->str[0] = g_ascii_toupper(str->str[0]); if (n == 4) { g_string_append(str, " is magic."); break; } g_string_append(str, " is "); append_number_name(str, count); g_string_append(str, ", "); n = count; } return str; } void test_magic(uint64_t n) { GString* str = magic(n); printf("%s\n", str->str); g_string_free(str, TRUE); } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { String magic = fourIsMagic(n); System.out.printf("%d = %s%n", n, toSentence(magic)); } } private static final String toSentence(String s) { return s.substring(0,1).toUpperCase() + s.substring(1) + "."; } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String fourIsMagic(long n) { if ( n == 4 ) { return numToString(n) + " is magic"; } String result = numToString(n); return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length()); } private static final String numToString(long n) { if ( n < 0 ) { return "negative " + numToString(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : ""); } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdio.h> int findNumOfDec(double x) { char buffer[128]; int pos, num; sprintf(buffer, "%.14f", x); pos = 0; num = 0; while (buffer[pos] != 0 && buffer[pos] != '.') { pos++; } if (buffer[pos] != 0) { pos++; while (buffer[pos] != 0) { pos++; } pos--; while (buffer[pos] == '0') { pos--; } while (buffer[pos] != '.') { num++; pos--; } } return num; } void test(double x) { int num = findNumOfDec(x); printf("%f has %d decimals\n", x, num); } int main() { test(12.0); test(12.345); test(12.345555555555); test(12.3450); test(12.34555555555555555555); test(1.2345e+54); return 0; }
public static int findNumOfDec(double x){ String str = String.valueOf(x); if(str.endsWith(".0")) return 0; else return (str.substring(str.indexOf('.')).length() - 1); }
Rewrite the snippet below in Java so it works the same as the original C code.
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
enum Fruits{ APPLE, BANANA, CHERRY }
Transform the following C implementation into Java, maintaining the same output and logic.
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
enum Fruits{ APPLE, BANANA, CHERRY }
Generate a Java translation of this C snippet without changing its computational steps.
#include <stdio.h> #define MAX_N 33 #define BRANCH 4 typedef unsigned long long xint; #define FMT "llu" xint rooted[MAX_N] = {1, 1, 0}; xint unrooted[MAX_N] = {1, 1, 0}; xint choose(xint m, xint k) { xint i, r; if (k == 1) return m; for (r = m, i = 1; i < k; i++) r = r * (m + i) / (i + 1); return r; } void tree(xint br, xint n, xint cnt, xint sum, xint l) { xint b, c, m, s; for (b = br + 1; b <= BRANCH; b++) { s = sum + (b - br) * n; if (s >= MAX_N) return; c = choose(rooted[n], b - br) * cnt; if (l * 2 < s) unrooted[s] += c; if (b == BRANCH) return; rooted[s] += c; for (m = n; --m; ) tree(b, m, c, s, l); } } void bicenter(int s) { if (s & 1) return; unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; } int main() { xint n; for (n = 1; n < MAX_N; n++) { tree(0, n, 1, 1, n); bicenter(n); printf("%"FMT": %"FMT"\n", n, unrooted[n]); } return 0; }
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d: %s%n", n, unrooted[n]); } } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <stdio.h> #define MAX_N 33 #define BRANCH 4 typedef unsigned long long xint; #define FMT "llu" xint rooted[MAX_N] = {1, 1, 0}; xint unrooted[MAX_N] = {1, 1, 0}; xint choose(xint m, xint k) { xint i, r; if (k == 1) return m; for (r = m, i = 1; i < k; i++) r = r * (m + i) / (i + 1); return r; } void tree(xint br, xint n, xint cnt, xint sum, xint l) { xint b, c, m, s; for (b = br + 1; b <= BRANCH; b++) { s = sum + (b - br) * n; if (s >= MAX_N) return; c = choose(rooted[n], b - br) * cnt; if (l * 2 < s) unrooted[s] += c; if (b == BRANCH) return; rooted[s] += c; for (m = n; --m; ) tree(b, m, c, s, l); } } void bicenter(int s) { if (s & 1) return; unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; } int main() { xint n; for (n = 1; n < MAX_N; n++) { tree(0, n, 1, 1, n); bicenter(n); printf("%"FMT": %"FMT"\n", n, unrooted[n]); } return 0; }
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d: %s%n", n, unrooted[n]); } } }
Port the provided C code into Java while preserving the original functionality.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Convert this C block to Java, preserving its control flow and logic.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class Pentagram extends JPanel { final double degrees144 = Math.toRadians(144); public Pentagram() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawPentagram(Graphics2D g, int len, int x, int y, Color fill, Color stroke) { double angle = 0; Path2D p = new Path2D.Float(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { int x2 = x + (int) (Math.cos(angle) * len); int y2 = y + (int) (Math.sin(-angle) * len); p.lineTo(x2, y2); x = x2; y = y2; angle -= degrees144; } p.closePath(); g.setColor(fill); g.fill(p); g.setColor(stroke); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0)); drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pentagram"); f.setResizable(false); f.add(new Pentagram(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <string.h> #include <memory.h> static unsigned int _parseDecimal ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' ) { nVal *= 10; nVal += chNow - '0'; ++*pchCursor; } return nVal; } static unsigned int _parseHex ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor & 0x5f, (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || (chNow >= 'A' && chNow <= 'F') ) { unsigned char nybbleValue; chNow -= 0x10; nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow ); nVal <<= 4; nVal += nybbleValue; ++*pchCursor; } return nVal; } int ParseIPv4OrIPv6 ( const char** ppszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { unsigned char* abyAddrLocal; unsigned char abyDummyAddr[16]; const char* pchColon = strchr ( *ppszText, ':' ); const char* pchDot = strchr ( *ppszText, '.' ); const char* pchOpenBracket = strchr ( *ppszText, '[' ); const char* pchCloseBracket = NULL; int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot || ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) ); if ( bIsIPv6local ) { pchCloseBracket = strchr ( *ppszText, ']' ); if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket || pchCloseBracket < pchOpenBracket ) ) return 0; } else { if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) ) return 0; } if ( NULL != pbIsIPv6 ) *pbIsIPv6 = bIsIPv6local; abyAddrLocal = abyAddr; if ( NULL == abyAddrLocal ) abyAddrLocal = abyDummyAddr; if ( ! bIsIPv6local ) { unsigned char* pbyAddrCursor = abyAddrLocal; unsigned int nVal; const char* pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; if ( ':' == **ppszText && NULL != pnPort ) { unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } else { unsigned char* pbyAddrCursor; unsigned char* pbyZerosLoc; int bIPv4Detected; int nIdx; if ( NULL != pchOpenBracket ) *ppszText = pchOpenBracket + 1; pbyAddrCursor = abyAddrLocal; pbyZerosLoc = NULL; bIPv4Detected = 0; for ( nIdx = 0; nIdx < 8; ++nIdx ) { const char* pszTextBefore = *ppszText; unsigned nVal =_parseHex ( ppszText ); if ( pszTextBefore == *ppszText ) { if ( NULL != pbyZerosLoc ) { if ( pbyZerosLoc == pbyAddrCursor ) { --nIdx; break; } return 0; } if ( ':' != **ppszText ) return 0; if ( 0 == nIdx ) { ++(*ppszText); if ( ':' != **ppszText ) return 0; } pbyZerosLoc = pbyAddrCursor; ++(*ppszText); } else { if ( '.' == **ppszText ) { const char* pszTextlocal = pszTextBefore; unsigned char abyAddrlocal[16]; int bIsIPv6local; int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local ); *ppszText = pszTextlocal; if ( ! bParseResultlocal || bIsIPv6local ) return 0; *(pbyAddrCursor++) = abyAddrlocal[0]; *(pbyAddrCursor++) = abyAddrlocal[1]; *(pbyAddrCursor++) = abyAddrlocal[2]; *(pbyAddrCursor++) = abyAddrlocal[3]; ++nIdx; bIPv4Detected = 1; break; } if ( nVal > 65535 ) return 0; *(pbyAddrCursor++) = nVal >> 8; *(pbyAddrCursor++) = nVal & 0xff; if ( ':' == **ppszText ) { ++(*ppszText); } else { break; } } } if ( NULL != pbyZerosLoc ) { int nHead = (int)( pbyZerosLoc - abyAddrLocal ); int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); int nZeros = 16 - nTail - nHead; memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); memset ( pbyZerosLoc, 0, nZeros ); } if ( bIPv4Detected ) { static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff }; if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) ) return 0; } if ( NULL != pchOpenBracket ) { if ( ']' != **ppszText ) return 0; ++(*ppszText); } if ( ':' == **ppszText && NULL != pnPort ) { const char* pszTextBefore; unsigned int nVal; unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } } int ParseIPv4OrIPv6_2 ( const char* pszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { const char* pszTextLocal = pszText; return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6); }
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"}; System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port"); for ( String ip : tests ) { try { String [] parsed = parseIP(ip); System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]); } catch (IllegalArgumentException e) { System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage()); } } } private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$"); private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$"); private static String ipv6Pattern; static { ipv6Pattern = "^\\[{0,1}"; for ( int i = 1 ; i <= 7 ; i ++ ) { ipv6Pattern += "([0-9a-f]+):"; } ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$"; } private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern); private static String[] parseIP(String ip) { String hex = ""; String port = ""; Matcher ipv4Matcher = IPV4_PAT.matcher(ip); if ( ipv4Matcher.matches() ) { for ( int i = 1 ; i <= 4 ; i++ ) { hex += toHex4(ipv4Matcher.group(i)); } if ( ipv4Matcher.group(5) != null ) { port = ipv4Matcher.group(5); } return new String[] {hex, port}; } Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip); if ( ipv6DoubleColonMatcher.matches() ) { String p1 = ipv6DoubleColonMatcher.group(1); if ( p1.isEmpty() ) { p1 = "0"; } String p2 = ipv6DoubleColonMatcher.group(2); if ( p2.isEmpty() ) { p2 = "0"; } ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2; if ( ipv6DoubleColonMatcher.group(3) != null ) { ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3); } } Matcher ipv6Matcher = IPV6_PAT.matcher(ip); if ( ipv6Matcher.matches() ) { for ( int i = 1 ; i <= 8 ; i++ ) { hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0"); } if ( ipv6Matcher.group(9) != null ) { port = ipv6Matcher.group(9); } return new String[] {hex, port}; } throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip); } private static int numCount(String s) { return s.split(":").length; } private static String getZero(int count) { StringBuilder sb = new StringBuilder(); sb.append(":"); while ( count > 0 ) { sb.append("0:"); count--; } return sb.toString(); } private static String toHex4(String s) { int val = Integer.parseInt(s); if ( val < 0 || val > 255 ) { throw new IllegalArgumentException("ERROR 101: Invalid value : " + s); } return String.format("%2s", Integer.toHexString(val)).replace(" ", "0"); } private static String toHex6(String s) { int val = Integer.parseInt(s, 16); if ( val < 0 || val > 65536 ) { throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s); } return s; } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; double value; double weight; double volume; } item_t; item_t items[] = { {"panacea", 3000.0, 0.3, 0.025}, {"ichor", 1800.0, 0.2, 0.015}, {"gold", 2500.0, 2.0, 0.002}, }; int n = sizeof (items) / sizeof (item_t); int *count; int *best; double best_value; void knapsack (int i, double value, double weight, double volume) { int j, m1, m2, m; if (i == n) { if (value > best_value) { best_value = value; for (j = 0; j < n; j++) { best[j] = count[j]; } } return; } m1 = weight / items[i].weight; m2 = volume / items[i].volume; m = m1 < m2 ? m1 : m2; for (count[i] = m; count[i] >= 0; count[i]--) { knapsack( i + 1, value + count[i] * items[i].value, weight - count[i] * items[i].weight, volume - count[i] * items[i].volume ); } } int main () { count = malloc(n * sizeof (int)); best = malloc(n * sizeof (int)); best_value = 0; knapsack(0, 0.0, 25.0, 0.25); int i; for (i = 0; i < n; i++) { printf("%d %s\n", best[i], items[i].name); } printf("best value: %.0f\n", best_value); free(count); free(best); return 0; }
package hu.pj.alg; import hu.pj.obj.Item; import java.text.*; public class UnboundedKnapsack { protected Item [] items = { new Item("panacea", 3000, 0.3, 0.025), new Item("ichor" , 1800, 0.2, 0.015), new Item("gold" , 2500, 2.0, 0.002) }; protected final int n = items.length; protected Item sack = new Item("sack" , 0, 25.0, 0.250); protected Item best = new Item("best" , 0, 0.0, 0.000); protected int [] maxIt = new int [n]; protected int [] iIt = new int [n]; protected int [] bestAm = new int [n]; public UnboundedKnapsack() { for (int i = 0; i < n; i++) { maxIt [i] = Math.min( (int)(sack.getWeight() / items[i].getWeight()), (int)(sack.getVolume() / items[i].getVolume()) ); } calcWithRecursion(0); NumberFormat nf = NumberFormat.getInstance(); System.out.println("Maximum value achievable is: " + best.getValue()); System.out.print("This is achieved by carrying (one solution): "); for (int i = 0; i < n; i++) { System.out.print(bestAm[i] + " " + items[i].getName() + ", "); } System.out.println(); System.out.println("The weight to carry is: " + nf.format(best.getWeight()) + " and the volume used is: " + nf.format(best.getVolume()) ); } public void calcWithRecursion(int item) { for (int i = 0; i <= maxIt[item]; i++) { iIt[item] = i; if (item < n-1) { calcWithRecursion(item+1); } else { int currVal = 0; double currWei = 0.0; double currVol = 0.0; for (int j = 0; j < n; j++) { currVal += iIt[j] * items[j].getValue(); currWei += iIt[j] * items[j].getWeight(); currVol += iIt[j] * items[j].getVolume(); } if (currVal > best.getValue() && currWei <= sack.getWeight() && currVol <= sack.getVolume() ) { best.setValue (currVal); best.setWeight(currWei); best.setVolume(currVol); for (int j = 0; j < n; j++) bestAm[j] = iIt[j]; } } } } public static void main(String[] args) { new UnboundedKnapsack(); } }
Generate an equivalent Java version of this C code.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> char text_char(char c) { switch (c) { case 'a': case 'b': case 'c': return '2'; case 'd': case 'e': case 'f': return '3'; case 'g': case 'h': case 'i': return '4'; case 'j': case 'k': case 'l': return '5'; case 'm': case 'n': case 'o': return '6'; case 'p': case 'q': case 'r': case 's': return '7'; case 't': case 'u': case 'v': return '8'; case 'w': case 'x': case 'y': case 'z': return '9'; default: return 0; } } bool text_string(const GString* word, GString* text) { g_string_set_size(text, word->len); for (size_t i = 0; i < word->len; ++i) { char c = text_char(g_ascii_tolower(word->str[i])); if (c == 0) return false; text->str[i] = c; } return true; } typedef struct textonym_tag { const char* text; size_t length; GPtrArray* words; } textonym_t; int compare_by_text_length(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->length > t2->length) return -1; if (t1->length < t2->length) return 1; return strcmp(t1->text, t2->text); } int compare_by_word_count(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->words->len > t2->words->len) return -1; if (t1->words->len < t2->words->len) return 1; return strcmp(t1->text, t2->text); } void print_words(GPtrArray* words) { for (guint i = 0, n = words->len; i < n; ++i) { if (i > 0) printf(", "); printf("%s", g_ptr_array_index(words, i)); } printf("\n"); } void print_top_words(GArray* textonyms, guint top) { for (guint i = 0; i < top; ++i) { const textonym_t* t = &g_array_index(textonyms, textonym_t, i); printf("%s = ", t->text); print_words(t->words); } } void free_strings(gpointer ptr) { g_ptr_array_free(ptr, TRUE); } bool find_textonyms(const char* filename, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(filename, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return false; } GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, free_strings); GString* word = g_string_sized_new(64); GString* text = g_string_sized_new(64); guint count = 0; gsize term_pos; while (g_io_channel_read_line_string(channel, word, &term_pos, &error) == G_IO_STATUS_NORMAL) { g_string_truncate(word, term_pos); if (!text_string(word, text)) continue; GPtrArray* words = g_hash_table_lookup(ht, text->str); if (words == NULL) { words = g_ptr_array_new_full(1, g_free); g_hash_table_insert(ht, g_strdup(text->str), words); } g_ptr_array_add(words, g_strdup(word->str)); ++count; } g_io_channel_unref(channel); g_string_free(word, TRUE); g_string_free(text, TRUE); if (error != NULL) { g_propagate_error(error_ptr, error); g_hash_table_destroy(ht); return false; } GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t)); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, ht); while (g_hash_table_iter_next(&iter, &key, &value)) { GPtrArray* v = value; if (v->len > 1) { textonym_t textonym; textonym.text = key; textonym.length = strlen(key); textonym.words = v; g_array_append_val(words, textonym); } } printf("There are %u words in '%s' which can be represented by the digit key mapping.\n", count, filename); guint size = g_hash_table_size(ht); printf("They require %u digit combinations to represent them.\n", size); guint textonyms = words->len; printf("%u digit combinations represent Textonyms.\n", textonyms); guint top = 5; if (textonyms < top) top = textonyms; printf("\nTop %u by number of words:\n", top); g_array_sort(words, compare_by_word_count); print_top_words(words, top); printf("\nTop %u by length:\n", top); g_array_sort(words, compare_by_text_length); print_top_words(words, top); g_array_free(words, TRUE); g_hash_table_destroy(ht); return true; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s word-list\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; if (!find_textonyms(argv[1], &error)) { if (error != NULL) { fprintf(stderr, "%s: %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } return EXIT_SUCCESS; }
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static final Map<Character, Character> mapping; private int total, elements, textonyms, max_found; private String filename, mappingResult; private Vector<String> max_strings; private Map<String, Vector<String>> values; static { mapping = new HashMap<Character, Character>(); mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2'); mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3'); mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4'); mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5'); mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6'); mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7'); mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8'); mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9'); } public RTextonyms(String filename) { this.filename = filename; this.total = this.elements = this.textonyms = this.max_found = 0; this.values = new HashMap<String, Vector<String>>(); this.max_strings = new Vector<String>(); return; } public void add(String line) { String mapping = ""; total++; if (!get_mapping(line)) { return; } mapping = mappingResult; if (values.get(mapping) == null) { values.put(mapping, new Vector<String>()); } int num_strings; num_strings = values.get(mapping).size(); textonyms += num_strings == 1 ? 1 : 0; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.add(mapping); max_found = num_strings; } else if (num_strings == max_found) { max_strings.add(mapping); } values.get(mapping).add(line); return; } public void results() { System.out.printf("Read %,d words from %s%n%n", total, filename); System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements, filename); System.out.printf("They require %,d digit combinations to represent them.%n", values.size()); System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms); System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1); for (String key : max_strings) { System.out.printf("%16s maps to: %s%n", key, values.get(key).toString()); } System.out.println(); return; } public void match(String key) { Vector<String> match; match = values.get(key); if (match == null) { System.out.printf("Key %s not found%n", key); } else { System.out.printf("Key %s matches: %s%n", key, match.toString()); } return; } private boolean get_mapping(String line) { mappingResult = line; StringBuilder mappingBuilder = new StringBuilder(); for (char cc : line.toCharArray()) { if (Character.isAlphabetic(cc)) { mappingBuilder.append(mapping.get(Character.toUpperCase(cc))); } else if (Character.isDigit(cc)) { mappingBuilder.append(cc); } else { return false; } } mappingResult = mappingBuilder.toString(); return true; } public static void main(String[] args) { String filename; if (args.length > 0) { filename = args[0]; } else { filename = "./unixdict.txt"; } RTextonyms tc; tc = new RTextonyms(filename); Path fp = Paths.get(filename); try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) { while (fs.hasNextLine()) { tc.add(fs.nextLine()); } } catch (IOException ex) { ex.printStackTrace(); } List<String> numbers = Arrays.asList( "001", "228", "27484247", "7244967473642", "." ); tc.results(); for (String number : numbers) { if (number.equals(".")) { System.out.println(); } else { tc.match(number); } } return; } }
Maintain the same structure and functionality when rewriting this code in Java.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(file, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return NULL; } GPtrArray* dict = g_ptr_array_new_full(1024, g_free); GString* line = g_string_sized_new(64); gsize term_pos; while (g_io_channel_read_line_string(channel, line, &term_pos, &error) == G_IO_STATUS_NORMAL) { char* word = g_strdup(line->str); word[term_pos] = '\0'; g_ptr_array_add(dict, word); } g_string_free(line, TRUE); g_io_channel_unref(channel); if (error != NULL) { g_propagate_error(error_ptr, error); g_ptr_array_free(dict, TRUE); return NULL; } g_ptr_array_sort(dict, string_compare); return dict; } void rotate(char* str, size_t len) { char c = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = c; } char* dictionary_search(const GPtrArray* dictionary, const char* word) { char** result = bsearch(&word, dictionary->pdata, dictionary->len, sizeof(char*), string_compare); return result != NULL ? *result : NULL; } void find_teacup_words(GPtrArray* dictionary) { GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal); GPtrArray* teacup_words = g_ptr_array_new(); GString* temp = g_string_sized_new(8); for (size_t i = 0, n = dictionary->len; i < n; ++i) { char* word = g_ptr_array_index(dictionary, i); size_t len = strlen(word); if (len < 3 || g_hash_table_contains(found, word)) continue; g_ptr_array_set_size(teacup_words, 0); g_string_assign(temp, word); bool is_teacup_word = true; for (size_t i = 0; i < len - 1; ++i) { rotate(temp->str, len); char* w = dictionary_search(dictionary, temp->str); if (w == NULL) { is_teacup_word = false; break; } if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL)) g_ptr_array_add(teacup_words, w); } if (is_teacup_word && teacup_words->len > 0) { printf("%s", word); g_hash_table_add(found, word); for (size_t i = 0; i < teacup_words->len; ++i) { char* teacup_word = g_ptr_array_index(teacup_words, i); printf(" %s", teacup_word); g_hash_table_add(found, teacup_word); } printf("\n"); } } g_string_free(temp, TRUE); g_ptr_array_free(teacup_words, TRUE); g_hash_table_destroy(found); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s dictionary\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; GPtrArray* dictionary = load_dictionary(argv[1], &error); if (dictionary == NULL) { if (error != NULL) { fprintf(stderr, "Cannot load dictionary file '%s': %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } find_teacup_words(dictionary); g_ptr_array_free(dictionary, TRUE); return EXIT_SUCCESS; }
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static Set<String> loadDictionary(String fileName) throws IOException { Set<String> words = new TreeSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String word; while ((word = reader.readLine()) != null) words.add(word); return words; } } private static void findTeacupWords(Set<String> words) { List<String> teacupWords = new ArrayList<>(); Set<String> found = new HashSet<>(); for (String word : words) { int len = word.length(); if (len < 3 || found.contains(word)) continue; teacupWords.clear(); teacupWords.add(word); char[] chars = word.toCharArray(); for (int i = 0; i < len - 1; ++i) { String rotated = new String(rotate(chars)); if (rotated.equals(word) || !words.contains(rotated)) break; teacupWords.add(rotated); } if (teacupWords.size() == len) { found.addAll(teacupWords); System.out.print(word); for (int i = 1; i < len; ++i) System.out.print(" " + teacupWords.get(i)); System.out.println(); } } } private static char[] rotate(char[] ch) { char c = ch[0]; System.arraycopy(ch, 1, ch, 0, ch.length - 1); ch[ch.length - 1] = c; return ch; } }
Generate an equivalent Java version of this C code.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> int string_compare(gconstpointer p1, gconstpointer p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } GPtrArray* load_dictionary(const char* file, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(file, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return NULL; } GPtrArray* dict = g_ptr_array_new_full(1024, g_free); GString* line = g_string_sized_new(64); gsize term_pos; while (g_io_channel_read_line_string(channel, line, &term_pos, &error) == G_IO_STATUS_NORMAL) { char* word = g_strdup(line->str); word[term_pos] = '\0'; g_ptr_array_add(dict, word); } g_string_free(line, TRUE); g_io_channel_unref(channel); if (error != NULL) { g_propagate_error(error_ptr, error); g_ptr_array_free(dict, TRUE); return NULL; } g_ptr_array_sort(dict, string_compare); return dict; } void rotate(char* str, size_t len) { char c = str[0]; memmove(str, str + 1, len - 1); str[len - 1] = c; } char* dictionary_search(const GPtrArray* dictionary, const char* word) { char** result = bsearch(&word, dictionary->pdata, dictionary->len, sizeof(char*), string_compare); return result != NULL ? *result : NULL; } void find_teacup_words(GPtrArray* dictionary) { GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal); GPtrArray* teacup_words = g_ptr_array_new(); GString* temp = g_string_sized_new(8); for (size_t i = 0, n = dictionary->len; i < n; ++i) { char* word = g_ptr_array_index(dictionary, i); size_t len = strlen(word); if (len < 3 || g_hash_table_contains(found, word)) continue; g_ptr_array_set_size(teacup_words, 0); g_string_assign(temp, word); bool is_teacup_word = true; for (size_t i = 0; i < len - 1; ++i) { rotate(temp->str, len); char* w = dictionary_search(dictionary, temp->str); if (w == NULL) { is_teacup_word = false; break; } if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL)) g_ptr_array_add(teacup_words, w); } if (is_teacup_word && teacup_words->len > 0) { printf("%s", word); g_hash_table_add(found, word); for (size_t i = 0; i < teacup_words->len; ++i) { char* teacup_word = g_ptr_array_index(teacup_words, i); printf(" %s", teacup_word); g_hash_table_add(found, teacup_word); } printf("\n"); } } g_string_free(temp, TRUE); g_ptr_array_free(teacup_words, TRUE); g_hash_table_destroy(found); } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s dictionary\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; GPtrArray* dictionary = load_dictionary(argv[1], &error); if (dictionary == NULL) { if (error != NULL) { fprintf(stderr, "Cannot load dictionary file '%s': %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } find_teacup_words(dictionary); g_ptr_array_free(dictionary, TRUE); return EXIT_SUCCESS; }
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } catch (Exception ex) { System.err.println(ex.getMessage()); } } private static Set<String> loadDictionary(String fileName) throws IOException { Set<String> words = new TreeSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String word; while ((word = reader.readLine()) != null) words.add(word); return words; } } private static void findTeacupWords(Set<String> words) { List<String> teacupWords = new ArrayList<>(); Set<String> found = new HashSet<>(); for (String word : words) { int len = word.length(); if (len < 3 || found.contains(word)) continue; teacupWords.clear(); teacupWords.add(word); char[] chars = word.toCharArray(); for (int i = 0; i < len - 1; ++i) { String rotated = new String(rotate(chars)); if (rotated.equals(word) || !words.contains(rotated)) break; teacupWords.add(rotated); } if (teacupWords.size() == len) { found.addAll(teacupWords); System.out.print(word); for (int i = 1; i < len; ++i) System.out.print(" " + teacupWords.get(i)); System.out.println(); } } } private static char[] rotate(char[] ch) { char c = ch[0]; System.arraycopy(ch, 1, ch, 0, ch.length - 1); ch[ch.length - 1] = c; return ch; } }
Translate the given C code snippet into Java without altering its behavior.
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false; return n % d == 0; } int main() { setlocale(LC_ALL, ""); uint64_t previous = 1, gap = 0, sum = 0; int niven_index = 0, gap_index = 1; printf("Gap index Gap Niven index Niven number\n"); for (uint64_t niven = 1; gap_index <= 32; ++niven) { sum = digit_sum(niven, sum); if (divisible(niven, sum)) { if (niven > previous + gap) { gap = niven - previous; printf("%'9d %'4llu %'14d %'15llu\n", gap_index++, gap, niven_index, previous); } previous = niven; ++niven_index; } } return 0; }
public class NivenNumberGaps { public static void main(String[] args) { long prevGap = 0; long prevN = 1; long index = 0; System.out.println("Gap Gap Index Starting Niven"); for ( long n = 2 ; n < 20_000_000_000l ; n++ ) { if ( isNiven(n) ) { index++; long curGap = n - prevN; if ( curGap > prevGap ) { System.out.printf("%3d  %,13d  %,15d%n", curGap, index, prevN); prevGap = curGap; } prevN = n; } } } public static boolean isNiven(long n) { long sum = 0; long nSave = n; while ( n > 0 ) { sum += n % 10; n /= 10; } return nSave % sum == 0; } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x) int add(int x, int y) { int result = x + y; DEBUG_INT(x); DEBUG_INT(y); DEBUG_INT(result); DEBUG_INT(result+1); return result; } int main() { add(2, 7); return 0; }
import java.util.Objects; public class PrintDebugStatement { private static void printDebug(String message) { Objects.requireNonNull(message); RuntimeException exception = new RuntimeException(); StackTraceElement[] stackTrace = exception.getStackTrace(); StackTraceElement stackTraceElement = stackTrace[1]; String fileName = stackTraceElement.getFileName(); String className = stackTraceElement.getClassName(); String methodName = stackTraceElement.getMethodName(); int lineNumber = stackTraceElement.getLineNumber(); System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message); } private static void blah() { printDebug("Made It!"); } public static void main(String[] args) { printDebug("Hello world."); blah(); Runnable oops = () -> printDebug("oops"); oops.run(); } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ double a,b,n,i,incr = 0.0001; printf("Enter major and minor axes of the SuperEllipse : "); scanf("%lf%lf",&a,&b); printf("Enter n : "); scanf("%lf",&n); initwindow(500,500,"Superellipse"); for(i=0;i<2*pi;i+=incr){ putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15); } printf("Done. %lf",i); getch(); closegraph(); }
import java.awt.*; import java.awt.geom.Path2D; import static java.lang.Math.pow; import java.util.Hashtable; import javax.swing.*; import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Dimension(650, 650)); setBackground(Color.white); setFont(new Font("Serif", Font.PLAIN, 18)); } void drawGrid(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(new Color(0xEEEEEE)); int w = getWidth(); int h = getHeight(); int spacing = 25; for (int i = 0; i < w / spacing; i++) { g.drawLine(0, i * spacing, w, i * spacing); g.drawLine(i * spacing, 0, i * spacing, w); } g.drawLine(0, h - 1, w, h - 1); g.setColor(new Color(0xAAAAAA)); g.drawLine(0, w / 2, w, w / 2); g.drawLine(w / 2, 0, w / 2, w); } void drawLegend(Graphics2D g) { g.setColor(Color.black); g.setFont(getFont()); g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45); g.drawString("a = b = 200", getWidth() - 150, 75); } void drawEllipse(Graphics2D g) { final int a = 200; double[] points = new double[a + 1]; Path2D p = new Path2D.Double(); p.moveTo(a, 0); for (int x = a; x >= 0; x--) { points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); p.lineTo(x, -points[x]); } for (int x = 0; x <= a; x++) p.lineTo(x, points[x]); for (int x = a; x >= 0; x--) p.lineTo(-x, points[x]); for (int x = 0; x <= a; x++) p.lineTo(-x, -points[x]); g.translate(getWidth() / 2, getHeight() / 2); g.setStroke(new BasicStroke(2)); g.setColor(new Color(0x25B0C4DE, true)); g.fill(p); g.setColor(new Color(0xB0C4DE)); g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawGrid(g); drawLegend(g); drawEllipse(g); } @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); exp = source.getValue() / 2.0; repaint(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Super Ellipse"); f.setResizable(false); SuperEllipse panel = new SuperEllipse(); f.add(panel, BorderLayout.CENTER); JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5); exponent.addChangeListener(panel); exponent.setMajorTickSpacing(1); exponent.setPaintLabels(true); exponent.setBackground(Color.white); exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); for (int i = 1; i < 10; i++) labelTable.put(i, new JLabel(String.valueOf(i * 0.5))); exponent.setLabelTable(labelTable); f.add(exponent, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Please provide an equivalent version of this C code in Java.
#include <stdio.h> #include <stdlib.h> #define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0) void _mr_unrank1(int rank, int n, int *vec) { int t, q, r; if (n < 1) return; q = rank / n; r = rank % n; SWAP(vec[r], vec[n-1]); _mr_unrank1(q, n-1, vec); } int _mr_rank1(int n, int *vec, int *inv) { int s, t; if (n < 2) return 0; s = vec[n-1]; SWAP(vec[n-1], vec[inv[n-1]]); SWAP(inv[s], inv[n-1]); return s + n * _mr_rank1(n-1, vec, inv); } void get_permutation(int rank, int n, int *vec) { int i; for (i = 0; i < n; ++i) vec[i] = i; _mr_unrank1(rank, n, vec); } int get_rank(int n, int *vec) { int i, r, *v, *inv; v = malloc(n * sizeof(int)); inv = malloc(n * sizeof(int)); for (i = 0; i < n; ++i) { v[i] = vec[i]; inv[vec[i]] = i; } r = _mr_rank1(n, v, inv); free(inv); free(v); return r; } int main(int argc, char *argv[]) { int i, r, tv[4]; for (r = 0; r < 24; ++r) { printf("%3d: ", r); get_permutation(r, 4, tv); for (i = 0; i < 4; ++i) { if (0 == i) printf("[ "); else printf(", "); printf("%d", tv[i]); } printf(" ] = %d\n", get_rank(4, tv)); } }
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.valueOf(n - i)); int digit = 0; int v = -1; while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i]) digit++; usedDigits.set(v); rank = rank.add(BigInteger.valueOf(digit)); } return rank; } public static int[] getPermutation(int n, BigInteger rank) { int[] digits = new int[n]; for (int digit = 2; digit <= n; digit++) { BigInteger divisor = BigInteger.valueOf(digit); digits[n - digit] = rank.mod(divisor).intValue(); if (digit < n) rank = rank.divide(divisor); } BitSet usedDigits = new BitSet(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { int v = usedDigits.nextClearBit(0); for (int j = 0; j < digits[i]; j++) v = usedDigits.nextClearBit(v + 1); permutation[i] = v; usedDigits.set(v); } return permutation; } public static void main(String[] args) { for (int i = 0; i < 6; i++) { int[] permutation = getPermutation(3, BigInteger.valueOf(i)); System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } Random rnd = new Random(); for (int n : new int[] { 12, 144 }) { BigInteger factorial = BigInteger.ONE; for (int i = 2; i <= n; i++) factorial = factorial.multiply(BigInteger.valueOf(i)); System.out.println("n = " + n); for (int i = 0; i < 5; i++) { BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd); rank = rank.mod(factorial); int[] permutation = getPermutation(n, rank); System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } } } }
Translate this program into Java but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0) void _mr_unrank1(int rank, int n, int *vec) { int t, q, r; if (n < 1) return; q = rank / n; r = rank % n; SWAP(vec[r], vec[n-1]); _mr_unrank1(q, n-1, vec); } int _mr_rank1(int n, int *vec, int *inv) { int s, t; if (n < 2) return 0; s = vec[n-1]; SWAP(vec[n-1], vec[inv[n-1]]); SWAP(inv[s], inv[n-1]); return s + n * _mr_rank1(n-1, vec, inv); } void get_permutation(int rank, int n, int *vec) { int i; for (i = 0; i < n; ++i) vec[i] = i; _mr_unrank1(rank, n, vec); } int get_rank(int n, int *vec) { int i, r, *v, *inv; v = malloc(n * sizeof(int)); inv = malloc(n * sizeof(int)); for (i = 0; i < n; ++i) { v[i] = vec[i]; inv[vec[i]] = i; } r = _mr_rank1(n, v, inv); free(inv); free(v); return r; } int main(int argc, char *argv[]) { int i, r, tv[4]; for (r = 0; r < 24; ++r) { printf("%3d: ", r); get_permutation(r, 4, tv); for (i = 0; i < 4; ++i) { if (0 == i) printf("[ "); else printf(", "); printf("%d", tv[i]); } printf(" ] = %d\n", get_rank(4, tv)); } }
import java.math.BigInteger; import java.util.*; class RankPermutation { public static BigInteger getRank(int[] permutation) { int n = permutation.length; BitSet usedDigits = new BitSet(); BigInteger rank = BigInteger.ZERO; for (int i = 0; i < n; i++) { rank = rank.multiply(BigInteger.valueOf(n - i)); int digit = 0; int v = -1; while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i]) digit++; usedDigits.set(v); rank = rank.add(BigInteger.valueOf(digit)); } return rank; } public static int[] getPermutation(int n, BigInteger rank) { int[] digits = new int[n]; for (int digit = 2; digit <= n; digit++) { BigInteger divisor = BigInteger.valueOf(digit); digits[n - digit] = rank.mod(divisor).intValue(); if (digit < n) rank = rank.divide(divisor); } BitSet usedDigits = new BitSet(); int[] permutation = new int[n]; for (int i = 0; i < n; i++) { int v = usedDigits.nextClearBit(0); for (int j = 0; j < digits[i]; j++) v = usedDigits.nextClearBit(v + 1); permutation[i] = v; usedDigits.set(v); } return permutation; } public static void main(String[] args) { for (int i = 0; i < 6; i++) { int[] permutation = getPermutation(3, BigInteger.valueOf(i)); System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } Random rnd = new Random(); for (int n : new int[] { 12, 144 }) { BigInteger factorial = BigInteger.ONE; for (int i = 2; i <= n; i++) factorial = factorial.multiply(BigInteger.valueOf(i)); System.out.println("n = " + n); for (int i = 0; i < 5; i++) { BigInteger rank = new BigInteger((factorial.bitLength() + 1) << 1, rnd); rank = rank.mod(factorial); int[] permutation = getPermutation(n, rank); System.out.println(" " + rank + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation)); } } } }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> size_t rprint(char *s, int *x, int len) { #define sep (a > s ? "," : "") #define ol (s ? 100 : 0) int i, j; char *a = s; for (i = j = 0; i < len; i = ++j) { for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); if (i + 1 < j) a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]); else while (i <= j) a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]); } return a - s; #undef sep #undef ol } int main() { int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1); rprint(s, x, sizeof(x) / sizeof(int)); printf("%s\n", s); return 0; }
public class RangeExtraction { public static void main(String[] args) { int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39}; int len = arr.length; int idx = 0, idx2 = 0; while (idx < len) { while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1); if (idx2 - idx > 2) { System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]); idx = idx2; } else { for (; idx < idx2; idx++) System.out.printf("%s,", arr[idx]); } } } }
Translate this program into Java but keep the logic exactly as in C.
#include<stdio.h> #include<ctype.h> void typeDetector(char* str){ if(isalnum(str[0])!=0) printf("\n%c is alphanumeric",str[0]); if(isalpha(str[0])!=0) printf("\n%c is alphabetic",str[0]); if(iscntrl(str[0])!=0) printf("\n%c is a control character",str[0]); if(isdigit(str[0])!=0) printf("\n%c is a digit",str[0]); if(isprint(str[0])!=0) printf("\n%c is printable",str[0]); if(ispunct(str[0])!=0) printf("\n%c is a punctuation character",str[0]); if(isxdigit(str[0])!=0) printf("\n%c is a hexadecimal digit",str[0]); } int main(int argC, char* argV[]) { int i; if(argC==1) printf("Usage : %s <followed by ASCII characters>"); else{ for(i=1;i<argC;i++) typeDetector(argV[i]); } return 0; }
public class TypeDetection { private static void showType(Object a) { if (a instanceof Integer) { System.out.printf("'%s' is an integer\n", a); } else if (a instanceof Double) { System.out.printf("'%s' is a double\n", a); } else if (a instanceof Character) { System.out.printf("'%s' is a character\n", a); } else { System.out.printf("'%s' is some other type\n", a); } } public static void main(String[] args) { showType(5); showType(7.5); showType('d'); showType(true); } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
#include <stdio.h> #include <math.h> #define max(x,y) ((x) > (y) ? (x) : (y)) int tri[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; int main(void) { const int len = sizeof(tri) / sizeof(tri[0]); const int base = (sqrt(8*len + 1) - 1) / 2; int step = base - 1; int stepc = 0; int i; for (i = len - base - 1; i >= 0; --i) { tri[i] += max(tri[i + step], tri[i + step + 1]); if (++stepc == step) { step--; stepc = 0; } } printf("%d\n", tri[0]); return 0; }
import java.nio.file.*; import static java.util.Arrays.stream; public class MaxPathSum { public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::parseInt) .toArray()) .toArray(int[][]::new); for (int r = data.length - 1; r > 0; r--) for (int c = 0; c < data[r].length - 1; c++) data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); System.out.println(data[0][0]); } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include<stdlib.h> #include<stdio.h> char** imageMatrix; char blankPixel,imagePixel; typedef struct{ int row,col; }pixel; int getBlackNeighbours(int row,int col){ int i,j,sum = 0; for(i=-1;i<=1;i++){ for(j=-1;j<=1;j++){ if(i!=0 || j!=0) sum+= (imageMatrix[row+i][col+j]==imagePixel); } } return sum; } int getBWTransitions(int row,int col){ return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel) +(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel) +(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel) +(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel) +(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel) +(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel) +(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel) +(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel)); } int zhangSuenTest1(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) && (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel)); } int zhangSuenTest2(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel)); } void zhangSuen(char* inputFile, char* outputFile){ int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed; pixel* markers; FILE* inputP = fopen(inputFile,"r"); fscanf(inputP,"%d%d",&rows,&cols); fscanf(inputP,"%d%d",&blankPixel,&imagePixel); blankPixel<=9?blankPixel+='0':blankPixel; imagePixel<=9?imagePixel+='0':imagePixel; printf("\nPrinting original image :\n"); imageMatrix = (char**)malloc(rows*sizeof(char*)); for(i=0;i<rows;i++){ imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char)); fscanf(inputP,"%s\n",imageMatrix[i]); printf("\n%s",imageMatrix[i]); } fclose(inputP); endRow = rows-2; endCol = cols-2; do{ markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } if(processed==0) processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); }while(processed==1); FILE* outputP = fopen(outputFile,"w"); printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n"); for(i=0;i<rows;i++){ for(j=0;j<cols;j++){ printf("%c",imageMatrix[i][j]); fprintf(outputP,"%c",imageMatrix[i][j]); } printf("\n"); fprintf(outputP,"\n"); } fclose(outputP); printf("\nImage also written to : %s",outputFile); } int main() { char inputFile[100],outputFile[100]; printf("Enter full path of input image file : "); scanf("%s",inputFile); printf("Enter full path of output image file : "); scanf("%s",outputFile); zhangSuen(inputFile,outputFile); return 0; }
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "}; final static int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; final static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, {0, 4, 6}}}; static List<Point> toWhite = new ArrayList<>(); static char[][] grid; public static void main(String[] args) { grid = new char[image.length][]; for (int r = 0; r < image.length; r++) grid[r] = image[r].toCharArray(); thinImage(); } static void thinImage() { boolean firstStep = false; boolean hasChanged; do { hasChanged = false; firstStep = !firstStep; for (int r = 1; r < grid.length - 1; r++) { for (int c = 1; c < grid[0].length - 1; c++) { if (grid[r][c] != '#') continue; int nn = numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (numTransitions(r, c) != 1) continue; if (!atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; toWhite.add(new Point(c, r)); hasChanged = true; } } for (Point p : toWhite) grid[p.y][p.x] = ' '; toWhite.clear(); } while (firstStep || hasChanged); printResult(); } static int numNeighbors(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++; return count; } static int numTransitions(int r, int c) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') { if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++; } return count; } static boolean atLeastOneIsWhite(int r, int c, int step) { int count = 0; int[][] group = nbrGroups[step]; for (int i = 0; i < 2; i++) for (int j = 0; j < group[i].length; j++) { int[] nbr = nbrs[group[i][j]]; if (grid[r + nbr[1]][c + nbr[0]] == ' ') { count++; break; } } return count > 1; } static void printResult() { for (char[] row : grid) System.out.println(row); } }
Convert this C block to Java, preserving its control flow and logic.
#include <stdio.h> int main() { int i, gprev = 0; int s[7] = {1, 2, 2, 3, 4, 4, 5}; for (i = 0; i < 7; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) printf("%d\n", i); prev = curr; } for (i = 0; i < 7; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) printf("%d\n", i); gprev = curr; } return 0; }
public class VariableDeclarationReset { public static void main(String[] args) { int[] s = {1, 2, 2, 3, 4, 4, 5}; for (int i = 0; i < s.length; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) System.out.println(i); prev = curr; } int gprev = 0; for (int i = 0; i < s.length; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) System.out.println(i); gprev = curr; } } }
Port the provided C code into Java while preserving the original functionality.
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } #define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) ) inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); } int main() { int32_t n; int i; for (i = 0, n = 1; ; i++, n *= 42) { printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n, n, msb32(n), msb32_idx(n), lsb32(n), lsb32_idx(n)); if (n >= INT32_MAX / 42) break; } return 0; }
public class FirstLastBits { public static int mssb(int x) { return Integer.highestOneBit(x); } public static long mssb(long x) { return Long.highestOneBit(x); } public static int mssb_idx(int x) { return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x); } public static int mssb_idx(long x) { return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); } public static int mssb_idx(BigInteger x) { return x.bitLength() - 1; } public static int lssb(int x) { return Integer.lowestOneBit(x); } public static long lssb(long x) { return Long.lowestOneBit(x); } public static int lssb_idx(int x) { return Integer.numberOfTrailingZeros(x); } public static int lssb_idx(long x) { return Long.numberOfTrailingZeros(x); } public static int lssb_idx(BigInteger x) { return x.getLowestSetBit(); } public static void main(String[] args) { System.out.println("int:"); int n1 = 1; for (int i = 0; ; i++, n1 *= 42) { System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n1, n1, mssb(n1), mssb_idx(n1), lssb(n1), lssb_idx(n1)); if (n1 >= Integer.MAX_VALUE / 42) break; } System.out.println(); System.out.println("long:"); long n2 = 1; for (int i = 0; ; i++, n2 *= 42) { System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n", i, n2, n2, mssb(n2), mssb_idx(n2), lssb(n2), lssb_idx(n2)); if (n2 >= Long.MAX_VALUE / 42) break; } System.out.println(); System.out.println("BigInteger:"); BigInteger n3 = BigInteger.ONE; BigInteger k = BigInteger.valueOf(1302); for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) { System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n", i, n3, n3, mssb_idx(n3), lssb_idx(n3)); } } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <stdio.h> #include <stdint.h> uint32_t msb32(uint32_t n) { uint32_t b = 1; if (!n) return 0; #define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } int msb32_idx(uint32_t n) { int b = 0; if (!n) return -1; #define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x step(16); step(8); step(4); step(2); step(1); #undef step return b; } #define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) ) inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); } int main() { int32_t n; int i; for (i = 0, n = 1; ; i++, n *= 42) { printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n, n, msb32(n), msb32_idx(n), lsb32(n), lsb32_idx(n)); if (n >= INT32_MAX / 42) break; } return 0; }
public class FirstLastBits { public static int mssb(int x) { return Integer.highestOneBit(x); } public static long mssb(long x) { return Long.highestOneBit(x); } public static int mssb_idx(int x) { return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x); } public static int mssb_idx(long x) { return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); } public static int mssb_idx(BigInteger x) { return x.bitLength() - 1; } public static int lssb(int x) { return Integer.lowestOneBit(x); } public static long lssb(long x) { return Long.lowestOneBit(x); } public static int lssb_idx(int x) { return Integer.numberOfTrailingZeros(x); } public static int lssb_idx(long x) { return Long.numberOfTrailingZeros(x); } public static int lssb_idx(BigInteger x) { return x.getLowestSetBit(); } public static void main(String[] args) { System.out.println("int:"); int n1 = 1; for (int i = 0; ; i++, n1 *= 42) { System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n", i, n1, n1, mssb(n1), mssb_idx(n1), lssb(n1), lssb_idx(n1)); if (n1 >= Integer.MAX_VALUE / 42) break; } System.out.println(); System.out.println("long:"); long n2 = 1; for (int i = 0; ; i++, n2 *= 42) { System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n", i, n2, n2, mssb(n2), mssb_idx(n2), lssb(n2), lssb_idx(n2)); if (n2 >= Long.MAX_VALUE / 42) break; } System.out.println(); System.out.println("BigInteger:"); BigInteger n3 = BigInteger.ONE; BigInteger k = BigInteger.valueOf(1302); for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) { System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n", i, n3, n3, mssb_idx(n3), lssb_idx(n3)); } } }
Maintain the same structure and functionality when rewriting this code in Java.
#include <stdio.h> int riseEqFall(int num) { int rdigit = num % 10; int netHeight = 0; while (num /= 10) { netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit); rdigit = num % 10; } return netHeight == 0; } int nextNum() { static int num = 0; do {num++;} while (!riseEqFall(num)); return num; } int main(void) { int total, num; printf("The first 200 numbers are: \n"); for (total = 0; total < 200; total++) printf("%d ", nextNum()); printf("\n\nThe 10,000,000th number is: "); for (; total < 10000000; total++) num = nextNum(); printf("%d\n", num); return 0; }
public class EqualRisesFalls { public static void main(String[] args) { final int limit1 = 200; final int limit2 = 10000000; System.out.printf("The first %d numbers in the sequence are:\n", limit1); int n = 0; for (int count = 0; count < limit2; ) { if (equalRisesAndFalls(++n)) { ++count; if (count <= limit1) System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' '); } } System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n); } private static boolean equalRisesAndFalls(int n) { int total = 0; for (int previousDigit = -1; n > 0; n /= 10) { int digit = n % 10; if (previousDigit > digit) ++total; else if (previousDigit >= 0 && previousDigit < digit) --total; previousDigit = digit; } return total == 0; } }
Convert this C snippet to Java and keep its semantics consistent.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #define pi M_PI typedef struct{ double x,y; }point; void kochCurve(point p1,point p2,int times){ point p3,p4,p5; double theta = pi/3; if(times>0){ p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3}; p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3}; p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)}; kochCurve(p1,p3,times-1); kochCurve(p3,p4,times-1); kochCurve(p4,p5,times-1); kochCurve(p5,p2,times-1); } else{ line(p1.x,p1.y,p2.x,p2.y); } } int main(int argC, char** argV) { int w,h,r; point p1,p2; if(argC!=4){ printf("Usage : %s <window width> <window height> <recursion level>",argV[0]); } else{ w = atoi(argV[1]); h = atoi(argV[2]); r = atoi(argV[3]); initwindow(w,h,"Koch Curve"); p1 = (point){10,h-10}; p2 = (point){w-10,h-10}; kochCurve(p1,p2,r); getch(); closegraph(); } return 0; }
int l = 300; void setup() { size(400, 400); background(0, 0, 255); stroke(255); translate(width/2.0, height/2.0); translate(-l/2.0, l*sqrt(3)/6.0); for (int i = 1; i <= 3; i++) { kcurve(0, l); rotate(radians(120)); translate(-l, 0); } } void kcurve(float x1, float x2) { float s = (x2-x1)/3; if (s < 5) { pushMatrix(); translate(x1, 0); line(0, 0, s, 0); line(2*s, 0, 3*s, 0); translate(s, 0); rotate(radians(60)); line(0, 0, s, 0); translate(s, 0); rotate(radians(-120)); line(0, 0, s, 0); popMatrix(); return; } pushMatrix(); translate(x1, 0); kcurve(0, s); kcurve(2*s, 3*s); translate(s, 0); rotate(radians(60)); kcurve(0, s); translate(s, 0); rotate(radians(-120)); kcurve(0, s); popMatrix(); }
Write the same code in Java as shown below in C.
#include<graphics.h> #include<stdlib.h> #include<time.h> int main() { srand(time(NULL)); initwindow(640,480,"Yellow Random Pixel"); putpixel(rand()%640,rand()%480,YELLOW); getch(); return 0; }
size(640,480); stroke(#ffff00); ellipse(random(640),random(480),1,1);
Convert this C block to Java, preserving its control flow and logic.
#include<graphics.h> int main() { initwindow(320,240,"Red Pixel"); putpixel(100,100,RED); getch(); return 0; }
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class DrawAPixel extends JFrame{ public DrawAPixel() { super("Red Pixel"); setSize(320, 240); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } @Override public void paint(Graphics g) { g.setColor(new Color(255, 0, 0)); g.drawRect(100, 100, 1, 1); } public static void main(String[] args) { new DrawAPixel(); } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 80 #define MIN_LENGTH 9 #define WORD_SIZE (MIN_LENGTH + 1) void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int word_compare(const void* p1, const void* p2) { return memcmp(p1, p2, WORD_SIZE); } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; FILE* in = fopen(filename, "r"); if (!in) { perror(filename); return EXIT_FAILURE; } char line[MAX_WORD_SIZE]; size_t size = 0, capacity = 1024; char* words = xmalloc(WORD_SIZE * capacity); while (fgets(line, sizeof(line), in)) { size_t len = strlen(line) - 1; if (len < MIN_LENGTH) continue; line[len] = '\0'; if (size == capacity) { capacity *= 2; words = xrealloc(words, WORD_SIZE * capacity); } memcpy(&words[size * WORD_SIZE], line, WORD_SIZE); ++size; } fclose(in); qsort(words, size, WORD_SIZE, word_compare); int count = 0; char prev_word[WORD_SIZE] = { 0 }; for (size_t i = 0; i + MIN_LENGTH <= size; ++i) { char word[WORD_SIZE] = { 0 }; for (size_t j = 0; j < MIN_LENGTH; ++j) word[j] = words[(i + j) * WORD_SIZE + j]; if (word_compare(word, prev_word) == 0) continue; if (bsearch(word, words, size, WORD_SIZE, word_compare)) printf("%2d. %s\n", ++count, word); memcpy(prev_word, word, WORD_SIZE); } free(words); return EXIT_SUCCESS; }
import java.io.*; import java.util.*; public class NeighbourWords { public static void main(String[] args) { try { int minLength = 9; List<String> words = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) { String line; while ((line = reader.readLine()) != null) { if (line.length() >= minLength) words.add(line); } } Collections.sort(words); String previousWord = null; int count = 0; for (int i = 0, n = words.size(); i + minLength <= n; ++i) { StringBuilder sb = new StringBuilder(minLength); for (int j = 0; j < minLength; ++j) sb.append(words.get(i + j).charAt(j)); String word = sb.toString(); if (word.equals(previousWord)) continue; if (Collections.binarySearch(words, word) >= 0) System.out.printf("%2d. %s\n", ++count, word); previousWord = word; } } catch (Exception e) { e.printStackTrace(); } } }
Generate an equivalent Java version of this C code.
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) #define NOT(X) (~(X)&1) #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(a, b, ps, pc); halfadder(ps, ic, s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(a0, b0, zero, o0, tc0); fulladder(a1, b1, tc0, o1, tc1); fulladder(a2, b2, tc1, o2, tc2); fulladder(a3, b3, tc2, o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3, s0, s1, s2, s3, overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
Translate this program into Java but keep the logic exactly as in C.
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** oddMagicSquare(int n) { if (n < 3 || n % 2 == 0) return NULL; int value = 0; int squareSize = n * n; int c = n / 2, r = 0,i; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); while (++value <= squareSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } int** singlyEvenMagicSquare(int n) { if (n < 6 || (n - 2) % 4 != 0) return NULL; int size = n * n; int halfN = n / 2; int subGridSize = size / 4, i; int** subGrid = oddMagicSquare(halfN); int gridFactors[] = {0, 2, 3, 1}; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int grid = (r / halfN) * 2 + (c / halfN); result[r][c] = subGrid[r % halfN][c % halfN]; result[r][c] += gridFactors[grid] * subGridSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j; for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2); } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf("Usage : %s <integer specifying rows in magic square>",argV[0]); else{ n = atoi(argV[1]); printMagicSquare(singlyEvenMagicSquare(n),n); } return 0; }
public class MagicSquareSinglyEven { public static void main(String[] args) { int n = 6; for (int[] row : magicSquareSinglyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int n) { if (n < 3 || n % 2 == 0) throw new IllegalArgumentException("base must be odd and > 2"); int value = 0; int gridSize = n * n; int c = n / 2, r = 0; int[][] result = new int[n][n]; while (++value <= gridSize) { result[r][c] = value; if (r == 0) { if (c == n - 1) { r++; } else { r = n - 1; c++; } } else if (c == n - 1) { r--; c = 0; } else if (result[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } return result; } static int[][] magicSquareSinglyEven(final int n) { if (n < 6 || (n - 2) % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4 plus 2"); int size = n * n; int halfN = n / 2; int subSquareSize = size / 4; int[][] subSquare = magicSquareOdd(halfN); int[] quadrantFactors = {0, 2, 3, 1}; int[][] result = new int[n][n]; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { int quadrant = (r / halfN) * 2 + (c / halfN); result[r][c] = subSquare[r % halfN][c % halfN]; result[r][c] += quadrantFactors[quadrant] * subSquareSize; } } int nColsLeft = halfN / 2; int nColsRight = nColsLeft - 1; for (int r = 0; r < halfN; r++) for (int c = 0; c < n; c++) { if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { if (c == 0 && r == nColsLeft) continue; int tmp = result[r][c]; result[r][c] = result[r + halfN][c]; result[r + halfN][c] = tmp; } } return result; } }
Keep all operations the same but rewrite the snippet in Java.
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h> char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e'; pos[i] = i; } do{ kPos = rand()%8; rPos1 = rand()%8; rPos2 = rand()%8; }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); rank[pos[rPos1]] = 'R'; rank[pos[kPos]] = 'K'; rank[pos[rPos2]] = 'R'; swap(rPos1,7); swap(rPos2,6); swap(kPos,5); do{ bPos1 = rand()%5; bPos2 = rand()%5; }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); rank[pos[bPos1]] = 'B'; rank[pos[bPos2]] = 'B'; swap(bPos1,4); swap(bPos2,3); do{ qPos = rand()%3; nPos1 = rand()%3; }while(qPos==nPos1); rank[pos[qPos]] = 'Q'; rank[pos[nPos1]] = 'N'; for(i=0;i<8;i++) if(rank[i]=='e'){ rank[i] = 'N'; break; } } void printRank(){ int i; #ifdef _WIN32 printf("%s\n",rank); #else { setlocale(LC_ALL,""); printf("\n"); for(i=0;i<8;i++){ if(rank[i]=='K') printf("%lc",(wint_t)9812); else if(rank[i]=='Q') printf("%lc",(wint_t)9813); else if(rank[i]=='R') printf("%lc",(wint_t)9814); else if(rank[i]=='B') printf("%lc",(wint_t)9815); if(rank[i]=='N') printf("%lc",(wint_t)9816); } } #endif } int main() { int i; srand((unsigned)time(NULL)); for(i=0;i<9;i++){ generateFirstRank(); printRank(); } return 0; }
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); return pieces; } private static boolean check(String rank){ if(!rank.matches(".*R.*K.*R.*")) return false; if(!rank.matches(".*B(..|....|......|)B.*")) return false; return true; } public static void main(String[] args){ for(int i = 0; i < 10; i++){ System.out.println(generateFirstRank()); } } }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
Maintain the same structure and functionality when rewriting this code in Java.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction != 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp--; if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp]--; break; case '.': System.out.print(memory[dp]); break; case ',': try { memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp] != 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip] != 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount--; if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount--; if (loopCount == 0) { return; } } ip--; } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+."); } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
int meaning_of_life();
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
Please provide an equivalent version of this C code in Java.
int meaning_of_life();
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }