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<stdlib.h> #include<stdio.h> #include<math.h> int p[512]; double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double lerp(double t, double a, double b) { return a + t * (b - a); } double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } double noise(double x, double y, double z) { int X = (int)floor(x) & 255, Y = (int)floor(y) & 255, Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } void loadPermutation(char* fileName){ FILE* fp = fopen(fileName,"r"); int permutation[256],i; for(i=0;i<256;i++) fscanf(fp,"%d",&permutation[i]); fclose(fp); for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } int main(int argC,char* argV[]) { if(argC!=5) printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>"); else{ loadPermutation(argV[1]); printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL))); } return 0; }
public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255, Z = (int)Math.floor(z) & 255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } static double lerp(double t, double a, double b) { return a + t * (b - a); } static double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include<stdlib.h> #include<stdio.h> #include<math.h> int p[512]; double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double lerp(double t, double a, double b) { return a + t * (b - a); } double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } double noise(double x, double y, double z) { int X = (int)floor(x) & 255, Y = (int)floor(y) & 255, Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } void loadPermutation(char* fileName){ FILE* fp = fopen(fileName,"r"); int permutation[256],i; for(i=0;i<256;i++) fscanf(fp,"%d",&permutation[i]); fclose(fp); for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } int main(int argC,char* argV[]) { if(argC!=5) printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>"); else{ loadPermutation(argV[1]); printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL))); } return 0; }
public final class ImprovedNoise { static public double noise(double x, double y, double z) { int X = (int)Math.floor(x) & 255, Y = (int)Math.floor(y) & 255, Z = (int)Math.floor(z) & 255; x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), grad(p[BA ], x-1, y , z )), lerp(u, grad(p[AB ], x , y-1, z ), grad(p[BB ], x-1, y-1, z ))), lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), grad(p[BA+1], x-1, y , z-1 )), lerp(u, grad(p[AB+1], x , y-1, z-1 ), grad(p[BB+1], x-1, y-1, z-1 )))); } static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } static double lerp(double t, double a, double b) { return a + t * (b - a); } static double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h<8 ? x : y, v = h<4 ? y : h==12||h==14 ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } static final int p[] = new int[512], permutation[] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; static { for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i]; } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> int cmpstr(const void *a, const void *b) { return strcmp(*(const char**)a, *(const char**)b); } int main(void) { DIR *basedir; char path[PATH_MAX]; struct dirent *entry; char **dirnames; int diralloc = 128; int dirsize = 0; if (!(dirnames = malloc(diralloc * sizeof(char*)))) { perror("malloc error:"); return 1; } if (!getcwd(path, PATH_MAX)) { perror("getcwd error:"); return 1; } if (!(basedir = opendir(path))) { perror("opendir error:"); return 1; } while ((entry = readdir(basedir))) { if (dirsize >= diralloc) { diralloc *= 2; if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) { perror("realloc error:"); return 1; } } dirnames[dirsize++] = strdup(entry->d_name); } qsort(dirnames, dirsize, sizeof(char*), cmpstr); int i; for (i = 0; i < dirsize; ++i) { if (dirnames[i][0] != '.') { printf("%s\n", dirnames[i]); } } for (i = 0; i < dirsize; ++i) free(dirnames[i]); free(dirnames); closedir(basedir); return 0; }
package rosetta; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class UnixLS { public static void main(String[] args) throws IOException { Files.list(Path.of("")).sorted().forEach(System.out::println); } }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> typedef struct { char mask; char lead; uint32_t beg; uint32_t end; int bits_stored; }utf_t; utf_t * utf[] = { [0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 }, [1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 }, [2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 }, [3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 }, [4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 }, &(utf_t){0}, }; int codepoint_len(const uint32_t cp); int utf8_len(const char ch); char *to_utf8(const uint32_t cp); uint32_t to_cp(const char chr[4]); int codepoint_len(const uint32_t cp) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((cp >= (*u)->beg) && (cp <= (*u)->end)) { break; } ++len; } if(len > 4) exit(1); return len; } int utf8_len(const char ch) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((ch & ~(*u)->mask) == (*u)->lead) { break; } ++len; } if(len > 4) { exit(1); } return len; } char *to_utf8(const uint32_t cp) { static char ret[5]; const int bytes = codepoint_len(cp); int shift = utf[0]->bits_stored * (bytes - 1); ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead; shift -= utf[0]->bits_stored; for(int i = 1; i < bytes; ++i) { ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead; shift -= utf[0]->bits_stored; } ret[bytes] = '\0'; return ret; } uint32_t to_cp(const char chr[4]) { int bytes = utf8_len(*chr); int shift = utf[0]->bits_stored * (bytes - 1); uint32_t codep = (*chr++ & utf[bytes]->mask) << shift; for(int i = 1; i < bytes; ++i, ++chr) { shift -= utf[0]->bits_stored; codep |= ((char)*chr & utf[0]->mask) << shift; } return codep; } int main(void) { const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0}; printf("Character Unicode UTF-8 encoding (hex)\n"); printf("----------------------------------------\n"); char *utf8; uint32_t codepoint; for(in = input; *in; ++in) { utf8 = to_utf8(*in); codepoint = to_cp(utf8); printf("%s U+%-7.4x", utf8, codepoint); for(int i = 0; utf8[i] && i < 4; ++i) { printf("%hhx ", utf8[i]); } printf("\n"); } return 0; }
import java.nio.charset.StandardCharsets; import java.util.Formatter; public class UTF8EncodeDecode { public static byte[] utf8encode(int codepoint) { return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8); } public static int utf8decode(byte[] bytes) { return new String(bytes, StandardCharsets.UTF_8).codePointAt(0); } public static void main(String[] args) { System.out.printf("%-7s %-43s %7s\t%s\t%7s%n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded"); for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] encoded = utf8encode(codepoint); Formatter formatter = new Formatter(); for (byte b : encoded) { formatter.format("%02X ", b); } String encodedHex = formatter.toString(); int decoded = utf8decode(encoded); System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n", codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded); } } }
Write the same code in Java as shown below in C.
void draw_line_antialias( image img, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, color_component r, color_component g, color_component b );
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c) { g.setColor(new Color(0f, 0f, 0f, (float)c)); g.fillOval((int) x, (int) y, 2, 2); } int ipart(double x) { return (int) x; } double fpart(double x) { return x - floor(x); } double rfpart(double x) { return 1.0 - fpart(x); } void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) { boolean steep = abs(y1 - y0) > abs(x1 - x0); if (steep) drawLine(g, y0, x0, y1, x1); if (x0 > x1) drawLine(g, x1, y1, x0, y0); double dx = x1 - x0; double dy = y1 - y0; double gradient = dy / dx; double xend = round(x0); double yend = y0 + gradient * (xend - x0); double xgap = rfpart(x0 + 0.5); double xpxl1 = xend; double ypxl1 = ipart(yend); if (steep) { plot(g, ypxl1, xpxl1, rfpart(yend) * xgap); plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap); } else { plot(g, xpxl1, ypxl1, rfpart(yend) * xgap); plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap); } double intery = yend + gradient; xend = round(x1); yend = y1 + gradient * (xend - x1); xgap = fpart(x1 + 0.5); double xpxl2 = xend; double ypxl2 = ipart(yend); if (steep) { plot(g, ypxl2, xpxl2, rfpart(yend) * xgap); plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap); } else { plot(g, xpxl2, ypxl2, rfpart(yend) * xgap); plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap); } for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) { if (steep) { plot(g, ipart(intery), x, rfpart(intery)); plot(g, ipart(intery) + 1, x, fpart(intery)); } else { plot(g, x, ipart(intery), rfpart(intery)); plot(g, x, ipart(intery) + 1, fpart(intery)); } intery = intery + gradient; } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; drawLine(g, 550, 170, 50, 435); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Xiaolin Wu's line algorithm"); f.setResizable(false); f.add(new XiaolinWu(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Keep all operations the same but rewrite the snippet in Java.
void draw_line_antialias( image img, unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, color_component r, color_component g, color_component b );
import java.awt.*; import static java.lang.Math.*; import javax.swing.*; public class XiaolinWu extends JPanel { public XiaolinWu() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); } void plot(Graphics2D g, double x, double y, double c) { g.setColor(new Color(0f, 0f, 0f, (float)c)); g.fillOval((int) x, (int) y, 2, 2); } int ipart(double x) { return (int) x; } double fpart(double x) { return x - floor(x); } double rfpart(double x) { return 1.0 - fpart(x); } void drawLine(Graphics2D g, double x0, double y0, double x1, double y1) { boolean steep = abs(y1 - y0) > abs(x1 - x0); if (steep) drawLine(g, y0, x0, y1, x1); if (x0 > x1) drawLine(g, x1, y1, x0, y0); double dx = x1 - x0; double dy = y1 - y0; double gradient = dy / dx; double xend = round(x0); double yend = y0 + gradient * (xend - x0); double xgap = rfpart(x0 + 0.5); double xpxl1 = xend; double ypxl1 = ipart(yend); if (steep) { plot(g, ypxl1, xpxl1, rfpart(yend) * xgap); plot(g, ypxl1 + 1, xpxl1, fpart(yend) * xgap); } else { plot(g, xpxl1, ypxl1, rfpart(yend) * xgap); plot(g, xpxl1, ypxl1 + 1, fpart(yend) * xgap); } double intery = yend + gradient; xend = round(x1); yend = y1 + gradient * (xend - x1); xgap = fpart(x1 + 0.5); double xpxl2 = xend; double ypxl2 = ipart(yend); if (steep) { plot(g, ypxl2, xpxl2, rfpart(yend) * xgap); plot(g, ypxl2 + 1, xpxl2, fpart(yend) * xgap); } else { plot(g, xpxl2, ypxl2, rfpart(yend) * xgap); plot(g, xpxl2, ypxl2 + 1, fpart(yend) * xgap); } for (double x = xpxl1 + 1; x <= xpxl2 - 1; x++) { if (steep) { plot(g, ipart(intery), x, rfpart(intery)); plot(g, ipart(intery) + 1, x, fpart(intery)); } else { plot(g, x, ipart(intery), rfpart(intery)); plot(g, x, ipart(intery) + 1, fpart(intery)); } intery = intery + gradient; } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; drawLine(g, 550, 170, 50, 435); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Xiaolin Wu's line algorithm"); f.setResizable(false); f.add(new XiaolinWu(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Produce a functionally identical Java code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/keysym.h> int main() { Display *d; XEvent event; d = XOpenDisplay(NULL); if ( d != NULL ) { XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync); XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync); for(;;) { XNextEvent(d, &event); if ( event.type == KeyPress ) { KeySym s = XLookupKeysym(&event.xkey, 0); if ( s == XK_F7 ) { printf("something's happened\n"); } else if ( s == XK_F6 ) { break; } } } XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d)); XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d)); } return EXIT_SUCCESS; }
package keybord.macro.demo; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; class KeyboardMacroDemo { public static void main( String [] args ) { final JFrame frame = new JFrame(); String directions = "<html><b>Ctrl-S</b> to show frame title<br>" +"<b>Ctrl-H</b> to hide it</html>"; frame.add( new JLabel(directions)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener( new KeyAdapter(){ public void keyReleased( KeyEvent e ) { if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){ frame.setTitle("Hello there"); }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){ frame.setTitle(""); } } }); frame.pack(); frame.setVisible(true); } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <stdio.h> int main() { int max = 0, i = 0, sixes, nines, twenties; loopstart: while (i < 100) { for (sixes = 0; sixes*6 < i; sixes++) { if (sixes*6 == i) { i++; goto loopstart; } for (nines = 0; nines*9 < i; nines++) { if (sixes*6 + nines*9 == i) { i++; goto loopstart; } for (twenties = 0; twenties*20 < i; twenties++) { if (sixes*6 + nines*9 + twenties*20 == i) { i++; goto loopstart; } } } } max = i; i++; } printf("Maximum non-McNuggets number is %d\n", max); return 0; }
public class McNuggets { public static void main(String... args) { int[] SIZES = new int[] { 6, 9, 20 }; int MAX_TOTAL = 100; int numSizes = SIZES.length; int[] counts = new int[numSizes]; int maxFound = MAX_TOTAL + 1; boolean[] found = new boolean[maxFound]; int numFound = 0; int total = 0; boolean advancedState = false; do { if (!found[total]) { found[total] = true; numFound++; } advancedState = false; for (int i = 0; i < numSizes; i++) { int curSize = SIZES[i]; if ((total + curSize) > MAX_TOTAL) { total -= counts[i] * curSize; counts[i] = 0; } else { counts[i]++; total += curSize; advancedState = true; break; } } } while ((numFound < maxFound) && advancedState); if (numFound < maxFound) { for (int i = MAX_TOTAL; i >= 0; i--) { if (!found[i]) { System.out.println("Largest non-McNugget number in the search space is " + i); break; } } } else { System.out.println("All numbers in the search space are McNugget numbers"); } return; } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** doublyEvenMagicSquare(int n) { if (n < 4 || n % 4 != 0) return NULL; int bits = 38505; int size = n * n; int mult = n / 4,i,r,c,bitPos; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (r = 0, i = 0; r < n; r++) { for (c = 0; c < n; c++, i++) { bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } 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,baseWidth = numDigits(rows*rows) + 3; printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2); for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } } 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(doublyEvenMagicSquare(n),n); } return 0; }
public class MagicSquareDoublyEven { public static void main(String[] args) { int n = 8; for (int[] row : magicSquareDoublyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } static int[][] magicSquareDoublyEven(final int n) { if (n < 4 || n % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[][] result = new int[n][n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } }
Convert this C block to Java, preserving its control flow and logic.
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; double inf = 1.0 / 0.0; double nan = 0.0 / 0.0; double negZero = -2.0 / inf; System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == nan)); } }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf("positive infinity: %f\n",inf); printf("negative infinity: %f\n",minus_inf); printf("negative zero: %f\n",minus_zero); printf("not a number: %f\n",nan); printf("+inf + 2.0 = %f\n",inf + 2.0); printf("+inf - 10.1 = %f\n",inf - 10.1); printf("+inf + -inf = %f\n",inf + minus_inf); printf("0.0 * +inf = %f\n",0.0 * inf); printf("1.0/-0.0 = %f\n",1.0/minus_zero); printf("NaN + 1.0 = %f\n",nan + 1.0); printf("NaN + NaN = %f\n",nan + nan); printf("NaN == NaN = %s\n",nan == nan ? "true" : "false"); printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false"); return 0; }
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; double inf = 1.0 / 0.0; double nan = 0.0 / 0.0; double negZero = -2.0 / inf; System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == nan)); } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <math.h> #include <stdint.h> #include <stdio.h> static uint64_t state; static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D; void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x >> 27); state = x; answer = ((x * STATE_MAGIC) >> 32); return answer; } float next_float() { return (float)next_int() / (1LL << 32); } int main() { int counts[5] = { 0, 0, 0, 0, 0 }; int i; seed(1234567); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("%u\n", next_int()); printf("\n"); seed(987654321); for (i = 0; i < 100000; i++) { int j = (int)floor(next_float() * 5.0); counts[j]++; } for (i = 0; i < 5; i++) { printf("%d: %d\n", i, counts[i]); } return 0; }
public class XorShiftStar { private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16); private long state; public void seed(long num) { state = num; } public int nextInt() { long x; int answer; x = state; x = x ^ (x >>> 12); x = x ^ (x << 25); x = x ^ (x >>> 27); state = x; answer = (int) ((x * MAGIC) >> 32); return answer; } public float nextFloat() { return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32); } public static void main(String[] args) { var rng = new XorShiftStar(); rng.seed(1234567); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(Integer.toUnsignedString(rng.nextInt())); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; rng.seed(987654321); for (int i = 0; i < 100_000; i++) { int j = (int) Math.floor(rng.nextFloat() * 5.0); counts[j]++; } for (int i = 0; i < counts.length; i++) { System.out.printf("%d: %d\n", i, counts[i]); } } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdlib.h> #include <stdio.h> #include <string.h> enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ID |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | QDCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ANCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | NSCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ARCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf("Extract meta-data from bit-encoded text form\n"); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; } dump_names(); } int bit_hdr(char *pLine){ char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; int k=0; for(int j=0; j<sz;j++){ if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ NAME_T *pn; printf("-name-bits-mask-data-\n"); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data); } puts("bye.."); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; header[BITS] = 0xB50A; }
import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| QDCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ANCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| NSCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ARCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; public static void main(String[] args) { validate(TEST); display(TEST); Map<String,List<Integer>> asciiMap = decode(TEST); displayMap(asciiMap); displayCode(asciiMap, "78477bbf5496e12e1bf169a4"); } private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) { System.out.printf("%nTest string in hex:%n%s%n%n", hex); String bin = new BigInteger(hex,16).toString(2); int length = 0; for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); length += pos.get(1) - pos.get(0) + 1; } while ( length > bin.length() ) { bin = "0" + bin; } System.out.printf("Test string in binary:%n%s%n%n", bin); System.out.printf("Name Size Bit Pattern%n"); System.out.printf("-------- ----- -----------%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); int start = pos.get(0); int end = pos.get(1); System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1)); } } private static void display(String ascii) { System.out.printf("%nDiagram:%n%n"); for ( String s : TEST.split("\\r\\n") ) { System.out.println(s); } } private static void displayMap(Map<String,List<Integer>> asciiMap) { System.out.printf("%nDecode:%n%n"); System.out.printf("Name Size Start End%n"); System.out.printf("-------- ----- ----- -----%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1)); } } private static Map<String,List<Integer>> decode(String ascii) { Map<String,List<Integer>> map = new LinkedHashMap<>(); String[] split = TEST.split("\\r\\n"); int size = split[0].indexOf("+", 1) - split[0].indexOf("+"); int length = split[0].length() - 1; for ( int i = 1 ; i < split.length ; i += 2 ) { int barIndex = 1; String test = split[i]; int next; while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) { List<Integer> startEnd = new ArrayList<>(); startEnd.add((barIndex/size) + (i/2)*(length/size)); startEnd.add(((next-1)/size) + (i/2)*(length/size)); String code = test.substring(barIndex, next).replace(" ", ""); map.put(code, startEnd); barIndex = next + 1; } } return map; } private static void validate(String ascii) { String[] split = TEST.split("\\r\\n"); if ( split.length % 2 != 1 ) { throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length); } int size = 0; for ( int i = 0 ; i < split.length ; i++ ) { String test = split[i]; if ( i % 2 == 0 ) { if ( ! test.matches("^\\+([-]+\\+)+$") ) { throw new RuntimeException("ERROR 2: Improper line format. Line = " + test); } if ( size == 0 ) { int firstPlus = test.indexOf("+"); int secondPlus = test.indexOf("+", 1); size = secondPlus - firstPlus; } if ( ((test.length()-1) % size) != 0 ) { throw new RuntimeException("ERROR 3: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { if ( test.charAt(j) != '+' ) { throw new RuntimeException("ERROR 4: Improper line format. Line = " + test); } for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) != '-' ) { throw new RuntimeException("ERROR 5: Improper line format. Line = " + test); } } } } else { if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) { throw new RuntimeException("ERROR 6: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) == '|' ) { throw new RuntimeException("ERROR 7: Improper line format. Line = " + test); } } } } } } }
Generate a Java translation of this C snippet without changing its computational steps.
#include <stdlib.h> #include <stdio.h> #include <string.h> enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 }; char *Lines[MAX_ROWS] = { " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ID |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | QDCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ANCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | NSCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+", " | ARCOUNT |", " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" }; typedef struct { unsigned bit3s; unsigned mask; unsigned data; char A[NAME_SZ+2]; }NAME_T; NAME_T names[MAX_NAMES]; unsigned idx_name; enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR}; unsigned header[MAX_HDR]; unsigned idx_hdr; int bit_hdr(char *pLine); int bit_names(char *pLine); void dump_names(void); void make_test_hdr(void); int main(void){ char *p1; int rv; printf("Extract meta-data from bit-encoded text form\n"); make_test_hdr(); idx_name = 0; for( int i=0; i<MAX_ROWS;i++ ){ p1 = Lines[i]; if( p1==NULL ) break; if( rv = bit_hdr(Lines[i]), rv>0) continue; if( rv = bit_names(Lines[i]),rv>0) continue; } dump_names(); } int bit_hdr(char *pLine){ char *p1 = strchr(pLine,'+'); if( p1==NULL ) return 0; int numbits=0; for( int i=0; i<strlen(p1)-1; i+=3 ){ if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0; numbits++; } return numbits; } int bit_names(char *pLine){ char *p1,*p2 = pLine, tmp[80]; unsigned sz=0, maskbitcount = 15; while(1){ p1 = strchr(p2,'|'); if( p1==NULL ) break; p1++; p2 = strchr(p1,'|'); if( p2==NULL ) break; sz = p2-p1; tmp[sz] = 0; int k=0; for(int j=0; j<sz;j++){ if( p1[j] > ' ') tmp[k++] = p1[j]; } tmp[k]= 0; sz++; NAME_T *pn = &names[idx_name++]; strcpy(&pn->A[0], &tmp[0]); pn->bit3s = sz/3; if( pn->bit3s < 16 ){ for( int i=0; i<pn->bit3s; i++){ pn->mask |= 1 << maskbitcount--; } pn->data = header[idx_hdr] & pn->mask; unsigned m2 = pn->mask; while( (m2 & 1)==0 ){ m2>>=1; pn->data >>= 1; } if( pn->mask == 0xf ) idx_hdr++; } else{ pn->data = header[idx_hdr++]; } } return sz; } void dump_names(void){ NAME_T *pn; printf("-name-bits-mask-data-\n"); for( int i=0; i<MAX_NAMES; i++ ){ pn = &names[i]; if( pn->bit3s < 1 ) break; printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data); } puts("bye.."); } void make_test_hdr(void){ header[ID] = 1024; header[QDCOUNT] = 12; header[ANCOUNT] = 34; header[NSCOUNT] = 56; header[ARCOUNT] = 78; header[BITS] = 0xB50A; }
import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class AsciiArtDiagramConverter { private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ID |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| QDCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ANCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| NSCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" + "| ARCOUNT |\r\n" + "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; public static void main(String[] args) { validate(TEST); display(TEST); Map<String,List<Integer>> asciiMap = decode(TEST); displayMap(asciiMap); displayCode(asciiMap, "78477bbf5496e12e1bf169a4"); } private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) { System.out.printf("%nTest string in hex:%n%s%n%n", hex); String bin = new BigInteger(hex,16).toString(2); int length = 0; for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); length += pos.get(1) - pos.get(0) + 1; } while ( length > bin.length() ) { bin = "0" + bin; } System.out.printf("Test string in binary:%n%s%n%n", bin); System.out.printf("Name Size Bit Pattern%n"); System.out.printf("-------- ----- -----------%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); int start = pos.get(0); int end = pos.get(1); System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1)); } } private static void display(String ascii) { System.out.printf("%nDiagram:%n%n"); for ( String s : TEST.split("\\r\\n") ) { System.out.println(s); } } private static void displayMap(Map<String,List<Integer>> asciiMap) { System.out.printf("%nDecode:%n%n"); System.out.printf("Name Size Start End%n"); System.out.printf("-------- ----- ----- -----%n"); for ( String code : asciiMap.keySet() ) { List<Integer> pos = asciiMap.get(code); System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1)); } } private static Map<String,List<Integer>> decode(String ascii) { Map<String,List<Integer>> map = new LinkedHashMap<>(); String[] split = TEST.split("\\r\\n"); int size = split[0].indexOf("+", 1) - split[0].indexOf("+"); int length = split[0].length() - 1; for ( int i = 1 ; i < split.length ; i += 2 ) { int barIndex = 1; String test = split[i]; int next; while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) { List<Integer> startEnd = new ArrayList<>(); startEnd.add((barIndex/size) + (i/2)*(length/size)); startEnd.add(((next-1)/size) + (i/2)*(length/size)); String code = test.substring(barIndex, next).replace(" ", ""); map.put(code, startEnd); barIndex = next + 1; } } return map; } private static void validate(String ascii) { String[] split = TEST.split("\\r\\n"); if ( split.length % 2 != 1 ) { throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length); } int size = 0; for ( int i = 0 ; i < split.length ; i++ ) { String test = split[i]; if ( i % 2 == 0 ) { if ( ! test.matches("^\\+([-]+\\+)+$") ) { throw new RuntimeException("ERROR 2: Improper line format. Line = " + test); } if ( size == 0 ) { int firstPlus = test.indexOf("+"); int secondPlus = test.indexOf("+", 1); size = secondPlus - firstPlus; } if ( ((test.length()-1) % size) != 0 ) { throw new RuntimeException("ERROR 3: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { if ( test.charAt(j) != '+' ) { throw new RuntimeException("ERROR 4: Improper line format. Line = " + test); } for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) != '-' ) { throw new RuntimeException("ERROR 5: Improper line format. Line = " + test); } } } } else { if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) { throw new RuntimeException("ERROR 6: Improper line format. Line = " + test); } for ( int j = 0 ; j < test.length()-1 ; j += size ) { for ( int k = j+1 ; k < j + size ; k++ ) { if ( test.charAt(k) == '|' ) { throw new RuntimeException("ERROR 7: Improper line format. Line = " + test); } } } } } } }
Convert this C snippet to Java and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t)); for (i = 1; i <= la; i++) tbl[i] = tbl[i-1] + (1+lb); for (i = la; i >= 0; i--) { char *aa = a + i; for (j = lb; j >= 0; j--) { char *bb = b + j; if (!*aa && !*bb) continue; edit e = &tbl[i][j]; edit repl = &tbl[i+1][j+1]; edit dela = &tbl[i+1][j]; edit delb = &tbl[i][j+1]; e->c1 = *aa; e->c2 = *bb; if (!*aa) { e->next = delb; e->n = e->next->n + 1; continue; } if (!*bb) { e->next = dela; e->n = e->next->n + 1; continue; } e->next = repl; if (*aa == *bb) { e->n = e->next->n; continue; } if (e->next->n > delb->n) { e->next = delb; e->c1 = 0; } if (e->next->n > dela->n) { e->next = dela; e->c1 = *aa; e->c2 = 0; } e->n = e->next->n + 1; } } edit p = tbl[0]; printf("%s -> %s: %d edits\n", a, b, p->n); while (p->next) { if (p->c1 == p->c2) printf("%c", p->c1); else { putchar('('); if (p->c1) putchar(p->c1); putchar(','); if (p->c2) putchar(p->c2); putchar(')'); } p = p->next; } putchar('\n'); free(tbl[0]); free(tbl); } int main(void) { leven("raisethysword", "rosettacode"); return 0; }
public class LevenshteinAlignment { public static String[] alignment(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); int[][] costs = new int[a.length()+1][b.length()+1]; for (int j = 0; j <= b.length(); j++) costs[0][j] = j; for (int i = 1; i <= a.length(); i++) { costs[i][0] = i; for (int j = 1; j <= b.length(); j++) { costs[i][j] = Math.min(1 + Math.min(costs[i-1][j], costs[i][j-1]), a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1); } } StringBuilder aPathRev = new StringBuilder(); StringBuilder bPathRev = new StringBuilder(); for (int i = a.length(), j = b.length(); i != 0 && j != 0; ) { if (costs[i][j] == (a.charAt(i - 1) == b.charAt(j - 1) ? costs[i-1][j-1] : costs[i-1][j-1] + 1)) { aPathRev.append(a.charAt(--i)); bPathRev.append(b.charAt(--j)); } else if (costs[i][j] == 1 + costs[i-1][j]) { aPathRev.append(a.charAt(--i)); bPathRev.append('-'); } else if (costs[i][j] == 1 + costs[i][j-1]) { aPathRev.append('-'); bPathRev.append(b.charAt(--j)); } } return new String[]{aPathRev.reverse().toString(), bPathRev.reverse().toString()}; } public static void main(String[] args) { String[] result = alignment("rosettacode", "raisethysword"); System.out.println(result[0]); System.out.println(result[1]); } }
Convert this C block to Java, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #include <ucontext.h> typedef struct { ucontext_t caller, callee; char stack[8192]; void *in, *out; } co_t; co_t * co_new(void(*f)(), void *data) { co_t * c = malloc(sizeof(*c)); getcontext(&c->callee); c->in = data; c->callee.uc_stack.ss_sp = c->stack; c->callee.uc_stack.ss_size = sizeof(c->stack); c->callee.uc_link = &c->caller; makecontext(&c->callee, f, 1, (int)c); return c; } void co_del(co_t *c) { free(c); } inline void co_yield(co_t *c, void *data) { c->out = data; swapcontext(&c->callee, &c->caller); } inline void * co_collect(co_t *c) { c->out = 0; swapcontext(&c->caller, &c->callee); return c->out; } typedef struct node node; struct node { int v; node *left, *right; }; node *newnode(int v) { node *n = malloc(sizeof(node)); n->left = n->right = 0; n->v = v; return n; } void tree_insert(node **root, node *n) { while (*root) root = ((*root)->v > n->v) ? &(*root)->left : &(*root)->right; *root = n; } void tree_trav(int x) { co_t *c = (co_t *) x; void trav(node *root) { if (!root) return; trav(root->left); co_yield(c, root); trav(root->right); } trav(c->in); } int tree_eq(node *t1, node *t2) { co_t *c1 = co_new(tree_trav, t1); co_t *c2 = co_new(tree_trav, t2); node *p = 0, *q = 0; do { p = co_collect(c1); q = co_collect(c2); } while (p && q && (p->v == q->v)); co_del(c1); co_del(c2); return !p && !q; } int main() { int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 }; int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 }; int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 }; node *t1 = 0, *t2 = 0, *t3 = 0; void mktree(int *buf, node **root) { int i; for (i = 0; buf[i] >= 0; i++) tree_insert(root, newnode(buf[i])); } mktree(x, &t1); mktree(y, &t2); mktree(z, &t3); printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no"); printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no"); return 0; }
import java.util.*; class SameFringe { public interface Node<T extends Comparable<? super T>> { Node<T> getLeft(); Node<T> getRight(); boolean isLeaf(); T getData(); } public static class SimpleNode<T extends Comparable<? super T>> implements Node<T> { private final T data; public SimpleNode<T> left; public SimpleNode<T> right; public SimpleNode(T data) { this(data, null, null); } public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right) { this.data = data; this.left = left; this.right = right; } public Node<T> getLeft() { return left; } public Node<T> getRight() { return right; } public boolean isLeaf() { return ((left == null) && (right == null)); } public T getData() { return data; } public SimpleNode<T> addToTree(T data) { int cmp = data.compareTo(this.data); if (cmp == 0) throw new IllegalArgumentException("Same data!"); if (cmp < 0) { if (left == null) return (left = new SimpleNode<T>(data)); return left.addToTree(data); } if (right == null) return (right = new SimpleNode<T>(data)); return right.addToTree(data); } } public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2) { Stack<Node<T>> stack1 = new Stack<Node<T>>(); Stack<Node<T>> stack2 = new Stack<Node<T>>(); stack1.push(node1); stack2.push(node2); while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null)) if (!node1.getData().equals(node2.getData())) return false; return (node1 == null) && (node2 == null); } private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack) { while (!stack.isEmpty()) { Node<T> node = stack.pop(); if (node.isLeaf()) return node; Node<T> rightNode = node.getRight(); if (rightNode != null) stack.push(rightNode); Node<T> leftNode = node.getLeft(); if (leftNode != null) stack.push(leftNode); } return null; } public static void main(String[] args) { SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50))); SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null)))); SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56))))); System.out.print("Leaves for set 1: "); simpleWalk(headNode1); System.out.println(); System.out.print("Leaves for set 2: "); simpleWalk(headNode2); System.out.println(); System.out.print("Leaves for set 3: "); simpleWalk(headNode3); System.out.println(); System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2)); System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3)); } public static void simpleWalk(Node<Integer> node) { if (node.isLeaf()) System.out.print(node.getData() + " "); else { Node<Integer> left = node.getLeft(); if (left != null) simpleWalk(left); Node<Integer> right = node.getRight(); if (right != null) simpleWalk(right); } } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <X11/Xlib.h> #include <X11/Xutil.h> int main(int argc, char *argv[]) { Display *dpy; Window win; GC gc; int scr; Atom WM_DELETE_WINDOW; XEvent ev; XEvent ev2; KeySym keysym; int loop; dpy = XOpenDisplay(NULL); if (dpy == NULL) { fputs("Cannot open display", stderr); exit(1); } scr = XDefaultScreen(dpy); win = XCreateSimpleWindow(dpy, XRootWindow(dpy, scr), 10, 10, 300, 200, 1, XBlackPixel(dpy, scr), XWhitePixel(dpy, scr)); XStoreName(dpy, win, argv[0]); XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask); XMapWindow(dpy, win); XFlush(dpy); gc = XDefaultGC(dpy, scr); WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True); XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1); loop = 1; while (loop) { XNextEvent(dpy, &ev); switch (ev.type) { case Expose: { char msg1[] = "Clic in the window to generate"; char msg2[] = "a key press event"; XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1); XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1); } break; case ButtonPress: puts("ButtonPress event received"); ev2.type = KeyPress; ev2.xkey.state = ShiftMask; ev2.xkey.keycode = 24 + (rand() % 33); ev2.xkey.same_screen = True; XSendEvent(dpy, win, True, KeyPressMask, &ev2); break; case ClientMessage: if (ev.xclient.data.l[0] == WM_DELETE_WINDOW) loop = 0; break; case KeyPress: puts("KeyPress event received"); printf("> keycode: %d\n", ev.xkey.keycode); keysym = XLookupKeysym(&(ev.xkey), 0); if (keysym == XK_q || keysym == XK_Escape) { loop = 0; } else { char buffer[] = " "; int nchars = XLookupString( &(ev.xkey), buffer, 2, &keysym, NULL ); if (nchars == 1) printf("> Key '%c' pressed\n", buffer[0]); } break; } } XDestroyWindow(dpy, win); XCloseDisplay(dpy); return 1; }
import java.awt.Robot public static void type(String str){ Robot robot = new Robot(); for(char ch:str.toCharArray()){ if(Character.isUpperCase(ch)){ robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress((int)ch); robot.keyRelease((int)ch); robot.keyRelease(KeyEvent.VK_SHIFT); }else{ char upCh = Character.toUpperCase(ch); robot.keyPress((int)upCh); robot.keyRelease((int)upCh); } } }
Translate this program into Java but keep the logic exactly as in C.
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> enum Piece { Empty, Black, White, }; typedef struct Position_t { int x, y; } Position; struct Node_t { Position pos; struct Node_t *next; }; void releaseNode(struct Node_t *head) { if (head == NULL) return; releaseNode(head->next); head->next = NULL; free(head); } typedef struct List_t { struct Node_t *head; struct Node_t *tail; size_t length; } List; List makeList() { return (List) { NULL, NULL, 0 }; } void releaseList(List *lst) { if (lst == NULL) return; releaseNode(lst->head); lst->head = NULL; lst->tail = NULL; } void addNode(List *lst, Position pos) { struct Node_t *newNode; if (lst == NULL) { exit(EXIT_FAILURE); } newNode = malloc(sizeof(struct Node_t)); if (newNode == NULL) { exit(EXIT_FAILURE); } newNode->next = NULL; newNode->pos = pos; if (lst->head == NULL) { lst->head = lst->tail = newNode; } else { lst->tail->next = newNode; lst->tail = newNode; } lst->length++; } void removeAt(List *lst, size_t pos) { if (lst == NULL) return; if (pos == 0) { struct Node_t *temp = lst->head; if (lst->tail == lst->head) { lst->tail = NULL; } lst->head = lst->head->next; temp->next = NULL; free(temp); lst->length--; } else { struct Node_t *temp = lst->head; struct Node_t *rem; size_t i = pos; while (i-- > 1) { temp = temp->next; } rem = temp->next; if (rem == lst->tail) { lst->tail = temp; } temp->next = rem->next; rem->next = NULL; free(rem); lst->length--; } } bool isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || abs(queen.x - pos.x) == abs(queen.y - pos.y); } bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) { struct Node_t *queenNode; bool placingBlack = true; int i, j; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } if (m == 0) return true; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Position pos = { i, j }; queenNode = pBlackQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; } if (placingBlack) { addNode(pBlackQueens, pos); placingBlack = false; } else { addNode(pWhiteQueens, pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } removeAt(pBlackQueens, pBlackQueens->length - 1); removeAt(pWhiteQueens, pWhiteQueens->length - 1); placingBlack = true; } inner: {} } } if (!placingBlack) { removeAt(pBlackQueens, pBlackQueens->length - 1); } return false; } void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) { size_t length = n * n; struct Node_t *queenNode; char *board; size_t i, j, k; if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); } board = calloc(length, sizeof(char)); if (board == NULL) { exit(EXIT_FAILURE); } queenNode = pBlackQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = Black; queenNode = queenNode->next; } queenNode = pWhiteQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = White; queenNode = queenNode->next; } for (i = 0; i < length; i++) { if (i != 0 && i % n == 0) { printf("\n"); } switch (board[i]) { case Black: printf("B "); break; case White: printf("W "); break; default: j = i / n; k = i - j * n; if (j % 2 == k % 2) { printf(" "); } else { printf("# "); } break; } } printf("\n\n"); } void test(int n, int q) { List blackQueens = makeList(); List whiteQueens = makeList(); printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n); if (place(q, n, &blackQueens, &whiteQueens)) { printBoard(n, &blackQueens, &whiteQueens); } else { printf("No solution exists.\n\n"); } releaseList(&blackQueens); releaseList(&whiteQueens); } int main() { test(2, 1); test(3, 1); test(3, 2); test(4, 1); test(4, 2); test(4, 3); test(5, 1); test(5, 2); test(5, 3); test(5, 4); test(5, 5); test(6, 1); test(6, 2); test(6, 3); test(6, 4); test(6, 5); test(6, 6); test(7, 1); test(7, 2); test(7, 3); test(7, 4); test(7, 5); test(7, 6); test(7, 7); return EXIT_SUCCESS; }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Peaceful { enum Piece { Empty, Black, White, } public static class Position { public int x, y; public Position(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj instanceof Position) { Position pos = (Position) obj; return pos.x == x && pos.y == y; } return false; } } private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } boolean placingBlack = true; for (int i = 0; i < n; ++i) { inner: for (int j = 0; j < n; ++j) { Position pos = new Position(i, j); for (Position queen : pBlackQueens) { if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) { continue inner; } } for (Position queen : pWhiteQueens) { if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) { continue inner; } } if (placingBlack) { pBlackQueens.add(pos); placingBlack = false; } else { pWhiteQueens.add(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.remove(pBlackQueens.size() - 1); pWhiteQueens.remove(pWhiteQueens.size() - 1); placingBlack = true; } } } if (!placingBlack) { pBlackQueens.remove(pBlackQueens.size() - 1); } return false; } private static boolean isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y); } private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { Piece[] board = new Piece[n * n]; Arrays.fill(board, Piece.Empty); for (Position queen : blackQueens) { board[queen.x + n * queen.y] = Piece.Black; } for (Position queen : whiteQueens) { board[queen.x + n * queen.y] = Piece.White; } for (int i = 0; i < board.length; ++i) { if ((i != 0) && i % n == 0) { System.out.println(); } Piece b = board[i]; if (b == Piece.Black) { System.out.print("B "); } else if (b == Piece.White) { System.out.print("W "); } else { int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { System.out.print("• "); } else { System.out.print("◦ "); } } } System.out.println('\n'); } public static void main(String[] args) { List<Position> nms = List.of( new Position(2, 1), new Position(3, 1), new Position(3, 2), new Position(4, 1), new Position(4, 2), new Position(4, 3), new Position(5, 1), new Position(5, 2), new Position(5, 3), new Position(5, 4), new Position(5, 5), new Position(6, 1), new Position(6, 2), new Position(6, 3), new Position(6, 4), new Position(6, 5), new Position(6, 6), new Position(7, 1), new Position(7, 2), new Position(7, 3), new Position(7, 4), new Position(7, 5), new Position(7, 6), new Position(7, 7) ); for (Position nm : nms) { int m = nm.y; int n = nm.x; System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n); List<Position> blackQueens = new ArrayList<>(); List<Position> whiteQueens = new ArrayList<>(); if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens); } else { System.out.println("No solution exists.\n"); } } } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 100 int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); shift=q-p; strncpy(str+1,p,shift); str[0]=c; free(p); return shift; } void decode(int* pass,int size,char *sym) { int i,index; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=table[pass[i]]; index=move_to_front(table,c); if(pass[i]!=index) printf("there is an error"); sym[i]=c; } sym[size]='\0'; } void encode(char *sym,int size,int *pass) { int i=0; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=sym[i]; pass[i]=move_to_front(table,c); } } int check(char *sym,int size,int *pass) { int *pass2=malloc(sizeof(int)*size); char *sym2=malloc(sizeof(char)*size); int i,val=1; encode(sym,size,pass2); i=0; while(i<size && pass[i]==pass2[i])i++; if(i!=size)val=0; decode(pass,size,sym2); if(strcmp(sym,sym2)!=0)val=0; free(sym2); free(pass2); return val; } int main() { char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"}; int pass[MAX_SIZE]={0}; int i,len,j; for(i=0;i<3;i++) { len=strlen(sym[i]); encode(sym[i],len,pass); printf("%s : [",sym[i]); for(j=0;j<len;j++) printf("%d ",pass[j]); printf("]\n"); if(check(sym[i],len,pass)) printf("Correct :)\n"); else printf("Incorrect :(\n"); } return 0; }
import java.util.LinkedList; import java.util.List; public class MTF{ public static List<Integer> encode(String msg, String symTable){ List<Integer> output = new LinkedList<Integer>(); StringBuilder s = new StringBuilder(symTable); for(char c : msg.toCharArray()){ int idx = s.indexOf("" + c); output.add(idx); s = s.deleteCharAt(idx).insert(0, c); } return output; } public static String decode(List<Integer> idxs, String symTable){ StringBuilder output = new StringBuilder(); StringBuilder s = new StringBuilder(symTable); for(int idx : idxs){ char c = s.charAt(idx); output = output.append(c); s = s.deleteCharAt(idx).insert(0, c); } return output.toString(); } private static void test(String toEncode, String symTable){ List<Integer> encoded = encode(toEncode, symTable); System.out.println(toEncode + ": " + encoded); String decoded = decode(encoded, symTable); System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded); } public static void main(String[] args){ String symTable = "abcdefghijklmnopqrstuvwxyz"; test("broood", symTable); test("bananaaa", symTable); test("hiphophiphop", symTable); } }
Preserve the algorithm and functionality while converting the code from C to Java.
#include <ldap.h> char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); LDAPMessage **result; ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE, "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", NULL, 0, result); ldap_msgfree(*result); ldap_unbind(ld);
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapSearchDemo { public static void main(String[] args) throws IOException, LdapException, CursorException { new LdapSearchDemo().demonstrateSearch(); } private void demonstrateSearch() throws IOException, LdapException, CursorException { try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) { conn.bind("uid=admin,ou=system", "********"); search(conn, "*mil*"); conn.unBind(); } } private void search(LdapConnection connection, String uid) throws LdapException, CursorException { String baseDn = "ou=users,o=mojo"; String filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; SearchScope scope = SearchScope.SUBTREE; String[] attributes = {"dn", "cn", "sn", "uid"}; int ksearch = 0; EntryCursor cursor = connection.search(baseDn, filter, scope, attributes); while (cursor.next()) { ksearch++; Entry entry = cursor.get(); System.out.printf("Search entry %d = %s%n", ksearch, entry); } } }
Generate a Java translation of this C snippet without changing its computational steps.
#include <ldap.h> char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); LDAPMessage **result; ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE, "(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))", NULL, 0, result); ldap_msgfree(*result); ldap_unbind(ld);
import java.io.IOException; import org.apache.directory.api.ldap.model.cursor.CursorException; import org.apache.directory.api.ldap.model.cursor.EntryCursor; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapSearchDemo { public static void main(String[] args) throws IOException, LdapException, CursorException { new LdapSearchDemo().demonstrateSearch(); } private void demonstrateSearch() throws IOException, LdapException, CursorException { try (LdapConnection conn = new LdapNetworkConnection("localhost", 11389)) { conn.bind("uid=admin,ou=system", "********"); search(conn, "*mil*"); conn.unBind(); } } private void search(LdapConnection connection, String uid) throws LdapException, CursorException { String baseDn = "ou=users,o=mojo"; String filter = "(&(objectClass=person)(&(uid=" + uid + ")))"; SearchScope scope = SearchScope.SUBTREE; String[] attributes = {"dn", "cn", "sn", "uid"}; int ksearch = 0; EntryCursor cursor = connection.search(baseDn, filter, scope, attributes); while (cursor.next()) { ksearch++; Entry entry = cursor.get(); System.out.printf("Search entry %d = %s%n", ksearch, entry); } } }
Convert the following code from C to Java, ensuring the logic remains intact.
#include <stdio.h> #include <gsl/gsl_linalg.h> void gsl_matrix_print(const gsl_matrix *M) { int rows = M->size1; int cols = M->size2; for (int i = 0; i < rows; i++) { printf("|"); for (int j = 0; j < cols; j++) { printf("% 12.10f ", gsl_matrix_get(M, i, j)); } printf("\b|\n"); } printf("\n"); } int main(){ double a[] = {3, 0, 4, 5}; gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2); gsl_matrix *V = gsl_matrix_alloc(2, 2); gsl_vector *S = gsl_vector_alloc(2); gsl_vector *work = gsl_vector_alloc(2); gsl_linalg_SV_decomp(&A.matrix, V, S, work); gsl_matrix_transpose(V); double s[] = {S->data[0], 0, 0, S->data[1]}; gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2); printf("U:\n"); gsl_matrix_print(&A.matrix); printf("S:\n"); gsl_matrix_print(&SM.matrix); printf("VT:\n"); gsl_matrix_print(V); gsl_matrix_free(V); gsl_vector_free(S); gsl_vector_free(work); return 0; }
import Jama.Matrix; public class SingularValueDecomposition { public static void main(String[] args) { double[][] matrixArray = {{3, 0}, {4, 5}}; var matrix = new Matrix(matrixArray); var svd = matrix.svd(); svd.getU().print(0, 10); svd.getS().print(0, 10); svd.getV().print(0, 10); } }
Generate an equivalent Java version of this C code.
#include <stdio.h> #include <complex.h> #include <math.h> #define FMTSPEC(arg) _Generic((arg), \ float: "%f", double: "%f", \ long double: "%Lf", unsigned int: "%u", \ unsigned long: "%lu", unsigned long long: "%llu", \ int: "%d", long: "%ld", long long: "%lld", \ default: "(invalid type (%p)") #define CMPPARTS(x, y) ((long double complex)((long double)(x) + \ I * (long double)(y))) #define TEST_CMPL(i, j)\ printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \ printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false")) #define TEST_REAL(i)\ printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false")) static inline int isint(long double complex n) { return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n); } int main(void) { TEST_REAL(0); TEST_REAL(-0); TEST_REAL(-2); TEST_REAL(-2.00000000000001); TEST_REAL(5); TEST_REAL(7.3333333333333); TEST_REAL(3.141592653589); TEST_REAL(-9.223372036854776e18); TEST_REAL(5e-324); TEST_REAL(NAN); TEST_CMPL(6, 0); TEST_CMPL(0, 1); TEST_CMPL(0, 0); TEST_CMPL(3.4, 0); double complex test1 = 5 + 0*I, test2 = 3.4f, test3 = 3, test4 = 0 + 1.2*I; printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false"); printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false"); printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false"); printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false"); }
import java.math.BigDecimal; import java.util.List; public class TestIntegerness { private static boolean isLong(double d) { return isLong(d, 0.0); } private static boolean isLong(double d, double tolerance) { return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance; } @SuppressWarnings("ResultOfMethodCallIgnored") private static boolean isBigInteger(BigDecimal bd) { try { bd.toBigIntegerExact(); return true; } catch (ArithmeticException ex) { return false; } } private static class Rational { long num; long denom; Rational(int num, int denom) { this.num = num; this.denom = denom; } boolean isLong() { return num % denom == 0; } @Override public String toString() { return String.format("%s/%s", num, denom); } } private static class Complex { double real; double imag; Complex(double real, double imag) { this.real = real; this.imag = imag; } boolean isLong() { return TestIntegerness.isLong(real) && imag == 0.0; } @Override public String toString() { if (imag >= 0.0) { return String.format("%s + %si", real, imag); } return String.format("%s - %si", real, imag); } } public static void main(String[] args) { List<Double> da = List.of(25.000000, 24.999999, 25.000100); for (Double d : da) { boolean exact = isLong(d); System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an"); } System.out.println(); double tolerance = 0.00001; System.out.printf("With a tolerance of %.5f:%n", tolerance); for (Double d : da) { boolean fuzzy = isLong(d, tolerance); System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an"); } System.out.println(); List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY); for (Double f : fa) { boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString())); System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an"); } System.out.println(); List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0)); for (Complex c : ca) { boolean exact = c.isLong(); System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an"); } System.out.println(); List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2)); for (Rational r : ra) { boolean exact = r.isLong(); System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an"); } } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdlib.h> int main() { system("ls"); return 0; }
import java.util.Scanner; import java.io.*; public class Program { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec("cmd /C dir"); Scanner sc = new Scanner(p.getInputStream()); while (sc.hasNext()) System.out.println(sc.nextLine()); } catch (IOException e) { System.out.println(e.getMessage()); } } }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <stdio.h> #include <math.h> typedef struct { double x, y, z; } vector; typedef struct { vector i, j, k; } matrix; double norm(vector v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } vector normalize(vector v){ double length = norm(v); vector n = {v.x / length, v.y / length, v.z / length}; return n; } double dotProduct(vector v1, vector v2) { return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; } vector crossProduct(vector v1, vector v2) { vector cp = {v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x}; return cp; } double getAngle(vector v1, vector v2) { return acos(dotProduct(v1, v2) / (norm(v1)*norm(v2))); } vector matrixMultiply(matrix m ,vector v) { vector mm = {dotProduct(m.i, v), dotProduct(m.j, v), dotProduct(m.k, v)}; return mm; } vector aRotate(vector p, vector v, double a) { double ca = cos(a), sa = sin(a); double t = 1.0 - ca; double x = v.x, y = v.y, z = v.z; matrix r = { {ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa}, {x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa}, {z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t} }; return matrixMultiply(r, p); } int main() { vector v1 = {5, -6, 4}, v2 = {8, 5, -30}; double a = getAngle(v1, v2); vector cp = crossProduct(v1, v2); vector ncp = normalize(cp); vector np = aRotate(v1, ncp, a); printf("[%.13f, %.13f, %.13f]\n", np.x, np.y, np.z); return 0; }
class Vector{ private double x, y, z; public Vector(double x1,double y1,double z1){ x = x1; y = y1; z = z1; } void printVector(int x,int y){ text("( " + this.x + " ) \u00ee + ( " + this.y + " ) + \u0135 ( " + this.z + ") \u006b\u0302",x,y); } public double norm() { return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); } public Vector normalize(){ double length = this.norm(); return new Vector(this.x / length, this.y / length, this.z / length); } public double dotProduct(Vector v2) { return this.x*v2.x + this.y*v2.y + this.z*v2.z; } public Vector crossProduct(Vector v2) { return new Vector(this.y*v2.z - this.z*v2.y, this.z*v2.x - this.x*v2.z, this.x*v2.y - this.y*v2.x); } public double getAngle(Vector v2) { return Math.acos(this.dotProduct(v2) / (this.norm()*v2.norm())); } public Vector aRotate(Vector v, double a) { double ca = Math.cos(a), sa = Math.sin(a); double t = 1.0 - ca; double x = v.x, y = v.y, z = v.z; Vector[] r = { new Vector(ca + x*x*t, x*y*t - z*sa, x*z*t + y*sa), new Vector(x*y*t + z*sa, ca + y*y*t, y*z*t - x*sa), new Vector(z*x*t - y*sa, z*y*t + x*sa, ca + z*z*t) }; return new Vector(this.dotProduct(r[0]), this.dotProduct(r[1]), this.dotProduct(r[2])); } } void setup(){ Vector v1 = new Vector(5d, -6d, 4d),v2 = new Vector(8d, 5d, -30d); double a = v1.getAngle(v2); Vector cp = v1.crossProduct(v2); Vector normCP = cp.normalize(); Vector np = v1.aRotate(normCP,a); size(1200,600); fill(#000000); textSize(30); text("v1 = ",10,100); v1.printVector(60,100); text("v2 = ",10,150); v2.printVector(60,150); text("rV = ",10,200); np.printVector(60,200); }
Rewrite the snippet below in Java so it works the same as the original C code.
#include <libxml/xmlschemastypes.h> int main(int argC, char** argV) { if (argC <= 2) { printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]); return 0; } xmlDocPtr doc; xmlSchemaPtr schema = NULL; xmlSchemaParserCtxtPtr ctxt; char *XMLFileName = argV[1]; char *XSDFileName = argV[2]; int ret; xmlLineNumbersDefault(1); ctxt = xmlSchemaNewParserCtxt(XSDFileName); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); doc = xmlReadFile(XMLFileName, NULL, 0); if (doc == NULL){ fprintf(stderr, "Could not parse %s\n", XMLFileName); } else{ xmlSchemaValidCtxtPtr ctxt; ctxt = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0){ printf("%s validates\n", XMLFileName); } else if (ret > 0){ printf("%s fails to validate\n", XMLFileName); } else{ printf("%s validation generated an internal error\n", XMLFileName); } xmlSchemaFreeValidCtxt(ctxt); xmlFreeDoc(doc); } if(schema != NULL) xmlSchemaFree(schema); xmlSchemaCleanupTypes(); xmlCleanupParser(); xmlMemoryDump(); return 0; }
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import javax.xml.ws.Holder; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class XmlValidation { public static void main(String... args) throws MalformedURLException { URL schemaLocation = new URL("http: URL documentLocation = new URL("http: if (validate(schemaLocation, documentLocation)) { System.out.println("document is valid"); } else { System.out.println("document is invalid"); } } public static boolean minimalValidate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.validate(new StreamSource(documentLocation.toString())); return true; } catch (Exception e) { return false; } } public static boolean validate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); final Holder<Boolean> valid = new Holder<>(true); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.setErrorHandler(new ErrorHandler(){ @Override public void warning(SAXParseException exception) { System.out.println("warning: " + exception.getMessage()); } @Override public void error(SAXParseException exception) { System.out.println("error: " + exception.getMessage()); valid.value = false; } @Override public void fatalError(SAXParseException exception) throws SAXException { System.out.println("fatal error: " + exception.getMessage()); throw exception; }}); validator.validate(new StreamSource(documentLocation.toString())); return valid.value; } catch (SAXException e) { return false; } catch (Exception e) { System.err.println(e); return false; } } }
Write a version of this C function in Java with identical behavior.
#include <stdio.h> #include <math.h> #include <unistd.h> const char *shades = ".:!*oe&#%@"; double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } typedef struct { double cx, cy, cz, r; } sphere_t; sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 }; int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2) { double zsq; x -= sph->cx; y -= sph->cy; zsq = sph->r * sph->r - (x * x + y * y); if (zsq < 0) return 0; zsq = sqrt(zsq); *z1 = sph->cz - zsq; *z2 = sph->cz + zsq; return 1; } void draw_sphere(double k, double ambient) { int i, j, intensity, hit_result; double b; double vec[3], x, y, zb1, zb2, zs1, zs2; for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) { y = i + .5; for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) { x = (j - pos.cx) / 2. + .5 + pos.cx; if (!hit_sphere(&pos, x, y, &zb1, &zb2)) hit_result = 0; else if (!hit_sphere(&neg, x, y, &zs1, &zs2)) hit_result = 1; else if (zs1 > zb1) hit_result = 1; else if (zs2 > zb2) hit_result = 0; else if (zs2 > zb1) hit_result = 2; else hit_result = 1; switch(hit_result) { case 0: putchar('+'); continue; case 1: vec[0] = x - pos.cx; vec[1] = y - pos.cy; vec[2] = zb1 - pos.cz; break; default: vec[0] = neg.cx - x; vec[1] = neg.cy - y; vec[2] = neg.cz - zs2; } normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } putchar('\n'); } } int main() { double ang = 0; while (1) { printf("\033[H"); light[1] = cos(ang * 2); light[2] = cos(ang); light[0] = sin(ang); normalize(light); ang += .05; draw_sphere(2, .3); usleep(100000); } return 0; }
import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Point3D; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import javafx.scene.transform.Rotate; import javafx.stage.Stage; public class DeathStar extends Application { private static final int DIVISION = 200; float radius = 300; @Override public void start(Stage primaryStage) throws Exception { Point3D otherSphere = new Point3D(-radius, 0, -radius * 1.5); final TriangleMesh triangleMesh = createMesh(DIVISION, radius, otherSphere); MeshView a = new MeshView(triangleMesh); a.setTranslateY(radius); a.setTranslateX(radius); a.setRotationAxis(Rotate.Y_AXIS); Scene scene = new Scene(new Group(a)); primaryStage.setScene(scene); primaryStage.show(); } static TriangleMesh createMesh(final int division, final float radius, final Point3D centerOtherSphere) { Rotate rotate = new Rotate(180, centerOtherSphere); final int div2 = division / 2; final int nPoints = division * (div2 - 1) + 2; final int nTPoints = (division + 1) * (div2 - 1) + division * 2; final int nFaces = division * (div2 - 2) * 2 + division * 2; final float rDiv = 1.f / division; float points[] = new float[nPoints * 3]; float tPoints[] = new float[nTPoints * 2]; int faces[] = new int[nFaces * 6]; int pPos = 0, tPos = 0; for (int y = 0; y < div2 - 1; ++y) { float va = rDiv * (y + 1 - div2 / 2) * 2 * (float) Math.PI; float sin_va = (float) Math.sin(va); float cos_va = (float) Math.cos(va); float ty = 0.5f + sin_va * 0.5f; for (int i = 0; i < division; ++i) { double a = rDiv * i * 2 * (float) Math.PI; float hSin = (float) Math.sin(a); float hCos = (float) Math.cos(a); points[pPos + 0] = hSin * cos_va * radius; points[pPos + 2] = hCos * cos_va * radius; points[pPos + 1] = sin_va * radius; final Point3D point3D = new Point3D(points[pPos + 0], points[pPos + 1], points[pPos + 2]); double distance = centerOtherSphere.distance(point3D); if (distance <= radius) { Point3D subtract = centerOtherSphere.subtract(point3D); Point3D transform = rotate.transform(subtract); points[pPos + 0] = (float) transform.getX(); points[pPos + 1] = (float) transform.getY(); points[pPos + 2] = (float) transform.getZ(); } tPoints[tPos + 0] = 1 - rDiv * i; tPoints[tPos + 1] = ty; pPos += 3; tPos += 2; } tPoints[tPos + 0] = 0; tPoints[tPos + 1] = ty; tPos += 2; } points[pPos + 0] = 0; points[pPos + 1] = -radius; points[pPos + 2] = 0; points[pPos + 3] = 0; points[pPos + 4] = radius; points[pPos + 5] = 0; pPos += 6; int pS = (div2 - 1) * division; float textureDelta = 1.f / 256; for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = textureDelta; tPos += 2; } for (int i = 0; i < division; ++i) { tPoints[tPos + 0] = rDiv * (0.5f + i); tPoints[tPos + 1] = 1 - textureDelta; tPos += 2; } int fIndex = 0; for (int y = 0; y < div2 - 2; ++y) { for (int x = 0; x < division; ++x) { int p0 = y * division + x; int p1 = p0 + 1; int p2 = p0 + division; int p3 = p1 + division; int t0 = p0 + y; int t1 = t0 + 1; int t2 = t0 + division + 1; int t3 = t1 + division + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2; faces[fIndex + 5] = t2; fIndex += 6; faces[fIndex + 0] = p3 % division == 0 ? p3 - division : p3; faces[fIndex + 1] = t3; faces[fIndex + 2] = p2; faces[fIndex + 3] = t2; faces[fIndex + 4] = p1 % division == 0 ? p1 - division : p1; faces[fIndex + 5] = t1; fIndex += 6; } } int p0 = pS; int tB = (div2 - 1) * (division + 1); for (int x = 0; x < division; ++x) { int p2 = x, p1 = x + 1, t0 = tB + x; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1 == division ? 0 : p1; faces[fIndex + 3] = p1; faces[fIndex + 4] = p2; faces[fIndex + 5] = p2; fIndex += 6; } p0 = p0 + 1; tB = tB + division; int pB = (div2 - 2) * division; for (int x = 0; x < division; ++x) { int p1 = pB + x, p2 = pB + x + 1, t0 = tB + x; int t1 = (div2 - 2) * (division + 1) + x, t2 = t1 + 1; faces[fIndex + 0] = p0; faces[fIndex + 1] = t0; faces[fIndex + 2] = p1; faces[fIndex + 3] = t1; faces[fIndex + 4] = p2 % division == 0 ? p2 - division : p2; faces[fIndex + 5] = t2; fIndex += 6; } TriangleMesh m = new TriangleMesh(); m.getPoints().setAll(points); m.getTexCoords().setAll(tPoints); m.getFaces().setAll(faces); return m; } public static void main(String[] args) { launch(args); } }
Write a version of this C function in Java with identical behavior.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #define LUCKY_SIZE 60000 int luckyOdd[LUCKY_SIZE]; int luckyEven[LUCKY_SIZE]; void compactLucky(int luckyArray[]) { int i, j, k; for (i = 0; i < LUCKY_SIZE; i++) { if (luckyArray[i] == 0) { j = i; break; } } for (j = i + 1; j < LUCKY_SIZE; j++) { if (luckyArray[j] > 0) { luckyArray[i++] = luckyArray[j]; } } for (; i < LUCKY_SIZE; i++) { luckyArray[i] = 0; } } void initialize() { int i, j; for (i = 0; i < LUCKY_SIZE; i++) { luckyEven[i] = 2 * i + 2; luckyOdd[i] = 2 * i + 1; } for (i = 1; i < LUCKY_SIZE; i++) { if (luckyOdd[i] > 0) { for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) { luckyOdd[j] = 0; } compactLucky(luckyOdd); } } for (i = 1; i < LUCKY_SIZE; i++) { if (luckyEven[i] > 0) { for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) { luckyEven[j] = 0; } compactLucky(luckyEven); } } } void printBetween(size_t j, size_t k, bool even) { int i; if (even) { if (luckyEven[j] == 0 || luckyEven[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers between %d and %d are:", j, k); for (i = 0; luckyEven[i] != 0; i++) { if (luckyEven[i] > k) { break; } if (luckyEven[i] > j) { printf(" %d", luckyEven[i]); } } } else { if (luckyOdd[j] == 0 || luckyOdd[k] == 0) { fprintf(stderr, "At least one argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers between %d and %d are:", j, k); for (i = 0; luckyOdd[i] != 0; i++) { if (luckyOdd[i] > k) { break; } if (luckyOdd[i] > j) { printf(" %d", luckyOdd[i]); } } } printf("\n"); } void printRange(size_t j, size_t k, bool even) { int i; if (even) { if (luckyEven[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyEven[i]); } } else { if (luckyOdd[k] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky numbers %d to %d are:", j, k); for (i = j - 1; i < k; i++) { printf(" %d", luckyOdd[i]); } } printf("\n"); } void printSingle(size_t j, bool even) { if (even) { if (luckyEven[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky even number %d=%d\n", j, luckyEven[j - 1]); } else { if (luckyOdd[j] == 0) { fprintf(stderr, "The argument is too large\n"); exit(EXIT_FAILURE); } printf("Lucky number %d=%d\n", j, luckyOdd[j - 1]); } } void help() { printf("./lucky j [k] [--lucky|--evenLucky]\n"); printf("\n"); printf(" argument(s) | what is displayed\n"); printf("==============================================\n"); printf("-j=m | mth lucky number\n"); printf("-j=m --lucky | mth lucky number\n"); printf("-j=m --evenLucky | mth even lucky number\n"); printf("-j=m -k=n | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n"); printf("-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n"); printf("-j=m -k=-n | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n"); printf("-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n"); } void process(int argc, char *argv[]) { bool evenLucky = false; int j = 0; int k = 0; bool good = false; int i; for (i = 1; i < argc; ++i) { if ('-' == argv[i][0]) { if ('-' == argv[i][1]) { if (0 == strcmp("--lucky", argv[i])) { evenLucky = false; } else if (0 == strcmp("--evenLucky", argv[i])) { evenLucky = true; } else { fprintf(stderr, "Unknown long argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } else { if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) { good = true; j = atoi(&argv[i][3]); } else if ('k' == argv[i][1] && '=' == argv[i][2]) { k = atoi(&argv[i][3]); } else { fprintf(stderr, "Unknown short argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } } else { fprintf(stderr, "Unknown argument: [%s]\n", argv[i]); exit(EXIT_FAILURE); } } if (!good) { help(); exit(EXIT_FAILURE); } if (k > 0) { printRange(j, k, evenLucky); } else if (k < 0) { printBetween(j, -k, evenLucky); } else { printSingle(j, evenLucky); } } void test() { printRange(1, 20, false); printRange(1, 20, true); printBetween(6000, 6100, false); printBetween(6000, 6100, true); printSingle(10000, false); printSingle(10000, true); } int main(int argc, char *argv[]) { initialize(); if (argc < 2) { help(); return 1; } process(argc, argv); return 0; }
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LuckyNumbers { private static int MAX = 200000; private static List<Integer> luckyEven = luckyNumbers(MAX, true); private static List<Integer> luckyOdd = luckyNumbers(MAX, false); public static void main(String[] args) { if ( args.length == 1 || ( args.length == 2 && args[1].compareTo("lucky") == 0 ) ) { int n = Integer.parseInt(args[0]); System.out.printf("LuckyNumber(%d) = %d%n", n, luckyOdd.get(n-1)); } else if ( args.length == 2 && args[1].compareTo("evenLucky") == 0 ) { int n = Integer.parseInt(args[0]); System.out.printf("EvenLuckyNumber(%d) = %d%n", n, luckyEven.get(n-1)); } else if ( args.length == 2 || args.length == 3 ) { int j = Integer.parseInt(args[0]); int k = Integer.parseInt(args[1]); if ( ( args.length == 2 && k > 0 ) || (args.length == 3 && k > 0 && args[2].compareTo("lucky") == 0 ) ) { System.out.printf("LuckyNumber(%d) through LuckyNumber(%d) = %s%n", j, k, luckyOdd.subList(j-1, k)); } else if ( args.length == 3 && k > 0 && args[2].compareTo("evenLucky") == 0 ) { System.out.printf("EvenLuckyNumber(%d) through EvenLuckyNumber(%d) = %s%n", j, k, luckyEven.subList(j-1, k)); } else if ( ( args.length == 2 && k < 0 ) || (args.length == 3 && k < 0 && args[2].compareTo("lucky") == 0 ) ) { int n = Collections.binarySearch(luckyOdd, j); int m = Collections.binarySearch(luckyOdd, -k); System.out.printf("Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyOdd.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } else if ( args.length == 3 && k < 0 && args[2].compareTo("evenLucky") == 0 ) { int n = Collections.binarySearch(luckyEven, j); int m = Collections.binarySearch(luckyEven, -k); System.out.printf("Even Lucky Numbers in the range %d to %d inclusive = %s%n", j, -k, luckyEven.subList(n < 0 ? -n-1 : n, m < 0 ? -m-1 : m+1)); } } } private static List<Integer> luckyNumbers(int max, boolean even) { List<Integer> luckyList = new ArrayList<>(); for ( int i = even ? 2 : 1 ; i <= max ; i += 2 ) { luckyList.add(i); } int start = 1; boolean removed = true; while ( removed ) { removed = false; int increment = luckyList.get(start); List<Integer> remove = new ArrayList<>(); for ( int i = increment-1 ; i < luckyList.size() ; i += increment ) { remove.add(0, i); removed = true; } for ( int i : remove ) { luckyList.remove(i); } start++; } return luckyList; } }
Convert this C snippet to Java and keep its semantics consistent.
int a; static int p; extern float v; int code(int arg) { int myp; static int myc; } static void code2(void) { v = v * 1.02; }
public protected private static public void function(int x){ int y; { int z; } }
Convert this C block to Java, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define _XOPEN_SOURCE #define __USE_XOPEN #include <time.h> #define DB "database.csv" #define TRY(a) if (!(a)) {perror(#a);exit(1);} #define TRY2(a) if((a)<0) {perror(#a);exit(1);} #define FREE(a) if(a) {free(a);a=NULL;} #define sort_by(foo) \ static int by_##foo (const void*p1, const void*p2) { \ return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); } typedef struct db { char title[26]; char first_name[26]; char last_name[26]; time_t date; char publ[100]; struct db *next; } db_t,*pdb_t; typedef int (sort)(const void*, const void*); enum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY}; static pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby); static char *time2str (time_t *time); static time_t str2time (char *date); sort_by(last_name); sort_by(title); static int by_date(pdb_t *p1, pdb_t *p2); int main (int argc, char **argv) { char buf[100]; const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; db_t db; db.next=NULL; pdb_t dblist; int i; FILE *f; TRY (f=fopen(DB,"a+")); if (argc<2) { usage: printf ("Usage: %s [commands]\n" "-c Create new entry.\n" "-p Print the latest entry.\n" "-t Print all entries sorted by title.\n" "-d Print all entries sorted by date.\n" "-a Print all entries sorted by author.\n",argv[0]); fclose (f); return 0; } for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); switch (i) { case CREATE: printf("-c Create a new entry.\n"); printf("Title  :");if((scanf(" %25[^\n]",db.title ))<0)break; printf("Author Firstname:");if((scanf(" %25[^\n]",db.first_name))<0)break; printf("Author Lastname :");if((scanf(" %25[^\n]",db.last_name ))<0)break; printf("Date 10-12-2000 :");if((scanf(" %10[^\n]",buf ))<0)break; printf("Publication  :");if((scanf(" %99[^\n]",db.publ ))<0)break; db.date=str2time (buf); dao (CREATE,f,&db,NULL); break; case PRINT: printf ("-p Print the latest entry.\n"); while (!feof(f)) dao (READLINE,f,&db,NULL); dao (PRINT,f,&db,NULL); break; case TITLE: printf ("-t Print all entries sorted by title.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,by_title); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; case DATE: printf ("-d Print all entries sorted by date.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,(int (*)(const void *,const void *)) by_date); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; case AUTH: printf ("-a Print all entries sorted by author.\n"); dblist = dao (READ,f,&db,NULL); dblist = dao (SORT,f,dblist,by_last_name); dao (PRINT,f,dblist,NULL); dao (DESTROY,f,dblist,NULL); break; default: { printf ("Unknown command: %s.\n",strlen(argv[1])<10?argv[1]:""); goto usage; } } fclose (f); return 0; } static pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) { pdb_t *pdb=NULL,rec=NULL,hd=NULL; int i=0,ret; char buf[100]; switch (cmd) { case CREATE: fprintf (f,"\"%s\",",in_db->title); fprintf (f,"\"%s\",",in_db->first_name); fprintf (f,"\"%s\",",in_db->last_name); fprintf (f,"\"%s\",",time2str(&in_db->date)); fprintf (f,"\"%s\" \n",in_db->publ); break; case PRINT: for (;in_db;i++) { printf ("Title  : %s\n", in_db->title); printf ("Author  : %s %s\n", in_db->first_name, in_db->last_name); printf ("Date  : %s\n", time2str(&in_db->date)); printf ("Publication : %s\n\n", in_db->publ); if (!((i+1)%3)) { printf ("Press Enter to continue.\n"); ret = scanf ("%*[^\n]"); if (ret<0) return rec; else getchar(); } in_db=in_db->next; } break; case READLINE: if((fscanf(f," \"%[^\"]\",",in_db->title ))<0)break; if((fscanf(f," \"%[^\"]\",",in_db->first_name))<0)break; if((fscanf(f," \"%[^\"]\",",in_db->last_name ))<0)break; if((fscanf(f," \"%[^\"]\",",buf ))<0)break; if((fscanf(f," \"%[^\"]\" ",in_db->publ ))<0)break; in_db->date=str2time (buf); break; case READ: while (!feof(f)) { dao (READLINE,f,in_db,NULL); TRY (rec=malloc(sizeof(db_t))); *rec=*in_db; rec->next=hd; hd=rec;i++; } if (i<2) { puts ("Empty database. Please create some entries."); fclose (f); exit (0); } break; case SORT: rec=in_db; for (;in_db;i++) in_db=in_db->next; TRY (pdb=malloc(i*sizeof(pdb_t))); in_db=rec; for (i=0;in_db;i++) { pdb[i]=in_db; in_db=in_db->next; } qsort (pdb,i,sizeof in_db,sortby); pdb[i-1]->next=NULL; for (i=i-1;i;i--) { pdb[i-1]->next=pdb[i]; } rec=pdb[0]; FREE (pdb); pdb=NULL; break; case DESTROY: { while ((rec=in_db)) { in_db=in_db->next; FREE (rec); } } } return rec; } static char *time2str (time_t *time) { static char buf[255]; struct tm *ptm; ptm=localtime (time); strftime(buf, 255, "%m-%d-%Y", ptm); return buf; } static time_t str2time (char *date) { struct tm tm; memset (&tm, 0, sizeof(struct tm)); strptime(date, "%m-%d-%Y", &tm); return mktime(&tm); } static int by_date (pdb_t *p1, pdb_t *p2) { if ((*p1)->date < (*p2)->date) { return -1; } else return ((*p1)->date > (*p2)->date); }
import java.io.*; import java.text.*; import java.util.*; public class SimpleDatabase { final static String filename = "simdb.csv"; public static void main(String[] args) { if (args.length < 1 || args.length > 3) { printUsage(); return; } switch (args[0].toLowerCase()) { case "add": addItem(args); break; case "latest": printLatest(args); break; case "all": printAll(); break; default: printUsage(); break; } } private static class Item implements Comparable<Item>{ final String name; final String date; final String category; Item(String n, String d, String c) { name = n; date = d; category = c; } @Override public int compareTo(Item item){ return date.compareTo(item.date); } @Override public String toString() { return String.format("%s,%s,%s%n", name, date, category); } } private static void addItem(String[] input) { if (input.length < 2) { printUsage(); return; } List<Item> db = load(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(new Date()); String cat = (input.length == 3) ? input[2] : "none"; db.add(new Item(input[1], date, cat)); store(db); } private static void printLatest(String[] a) { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); if (a.length == 2) { for (Item item : db) if (item.category.equals(a[1])) System.out.println(item); } else { System.out.println(db.get(0)); } } private static void printAll() { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); for (Item item : db) System.out.println(item); } private static List<Item> load() { List<Item> db = new ArrayList<>(); try (Scanner sc = new Scanner(new File(filename))) { while (sc.hasNext()) { String[] item = sc.nextLine().split(","); db.add(new Item(item[0], item[1], item[2])); } } catch (IOException e) { System.out.println(e); } return db; } private static void store(List<Item> db) { try (FileWriter fw = new FileWriter(filename)) { for (Item item : db) fw.write(item.toString()); } catch (IOException e) { System.out.println(e); } } private static void printUsage() { System.out.println("Usage:"); System.out.println(" simdb cmd [categoryName]"); System.out.println(" add add item, followed by optional category"); System.out.println(" latest print last added item(s), followed by " + "optional category"); System.out.println(" all print all"); System.out.println(" For instance: add \"some item name\" " + "\"some category name\""); } }
Keep all operations the same but rewrite the snippet in Java.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2; } private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) { if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] && rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; } double r2 = circ[2] + Math.max(rect[2], rect[3]); r2 = r2 * r2; return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2; } private static boolean[] surelyOutside; private static double totalArea(double[] rect, double[][] circs, int d) { int surelyOutsideCount = 0; for(int i = 0; i < circs.length; i++) { if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; } if(rectangleSurelyOutsideCircle(rect, circs[i])) { surelyOutside[i] = true; surelyOutsideCount++; } else { surelyOutside[i] = false; } } if(surelyOutsideCount == circs.length) { return 0; } if(d < 1) { return rect[2] * rect[3] / 3; } if(surelyOutsideCount > 0) { double[][] newCircs = new double[circs.length - surelyOutsideCount][3]; int loc = 0; for(int i = 0; i < circs.length; i++) { if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; } } circs = newCircs; } double w = rect[2] / 2; double h = rect[3] / 2; double[][] pieces = { { rect[0], rect[1], w, h }, { rect[0] + w, rect[1], w, h }, { rect[0], rect[1] - h, w, h }, { rect[0] + w, rect[1] - h, w, h } }; double total = 0; for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); } return total; } public static double totalArea(double[][] circs, int d) { double maxx = Double.NEGATIVE_INFINITY; double minx = Double.POSITIVE_INFINITY; double maxy = Double.NEGATIVE_INFINITY; double miny = Double.POSITIVE_INFINITY; for(double[] circ: circs) { if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; } if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; } if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; } if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; } } double[] rect = { minx, maxy, maxx - minx, maxy - miny }; surelyOutside = new boolean[circs.length]; return totalArea(rect, circs, d); } public static void main(String[] args) { double[][] circs = { { 1.6417233788, 1.6121789534, 0.0848270516 }, {-1.4944608174, 1.2077959613, 1.1039549836 }, { 0.6110294452, -0.6907087527, 0.9089162485 }, { 0.3844862411, 0.2923344616, 0.2375743054 }, {-0.2495892950, -0.3832854473, 1.0845181219 }, {1.7813504266, 1.6178237031, 0.8162655711 }, {-0.1985249206, -0.8343333301, 0.0538864941 }, {-1.7011985145, -0.1263820964, 0.4776976918 }, {-0.4319462812, 1.4104420482, 0.7886291537 }, {0.2178372997, -0.9499557344, 0.0357871187 }, {-0.6294854565, -1.3078893852, 0.7653357688 }, {1.7952608455, 0.6281269104, 0.2727652452 }, {1.4168575317, 1.0683357171, 1.1016025378 }, {1.4637371396, 0.9463877418, 1.1846214562 }, {-0.5263668798, 1.7315156631, 1.4428514068 }, {-1.2197352481, 0.9144146579, 1.0727263474 }, {-0.1389358881, 0.1092805780, 0.7350208828 }, {1.5293954595, 0.0030278255, 1.2472867347 }, {-0.5258728625, 1.3782633069, 1.3495508831 }, {-0.1403562064, 0.2437382535, 1.3804956588 }, {0.8055826339, -0.0482092025, 0.3327165165 }, {-0.6311979224, 0.7184578971, 0.2491045282 }, {1.4685857879, -0.8347049536, 1.3670667538 }, {-0.6855727502, 1.6465021616, 1.0593087096 }, {0.0152957411, 0.0638919221, 0.9771215985 } }; double ans = totalArea(circs, 24); System.out.println("Approx. area is " + ans); System.out.println("Error is " + Math.abs(21.56503660 - ans)); } }
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <stdbool.h> typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf("%.4f +/- %.4f (%zd samples)\n", area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; return distSq(rect[0], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) <= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) <= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) <= r2; } private static boolean rectangleSurelyOutsideCircle(double[] rect, double[] circ) { if(rect[0] <= circ[0] && circ[0] <= rect[0] + rect[2] && rect[1] - rect[3] <= circ[1] && circ[1] <= rect[1]) { return false; } double r2 = circ[2] + Math.max(rect[2], rect[3]); r2 = r2 * r2; return distSq(rect[0], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1], circ[0], circ[1]) >= r2 && distSq(rect[0], rect[1] - rect[3], circ[0], circ[1]) >= r2 && distSq(rect[0] + rect[2], rect[1] - rect[3], circ[0], circ[1]) >= r2; } private static boolean[] surelyOutside; private static double totalArea(double[] rect, double[][] circs, int d) { int surelyOutsideCount = 0; for(int i = 0; i < circs.length; i++) { if(rectangleFullyInsideCircle(rect, circs[i])) { return rect[2] * rect[3]; } if(rectangleSurelyOutsideCircle(rect, circs[i])) { surelyOutside[i] = true; surelyOutsideCount++; } else { surelyOutside[i] = false; } } if(surelyOutsideCount == circs.length) { return 0; } if(d < 1) { return rect[2] * rect[3] / 3; } if(surelyOutsideCount > 0) { double[][] newCircs = new double[circs.length - surelyOutsideCount][3]; int loc = 0; for(int i = 0; i < circs.length; i++) { if(!surelyOutside[i]) { newCircs[loc++] = circs[i]; } } circs = newCircs; } double w = rect[2] / 2; double h = rect[3] / 2; double[][] pieces = { { rect[0], rect[1], w, h }, { rect[0] + w, rect[1], w, h }, { rect[0], rect[1] - h, w, h }, { rect[0] + w, rect[1] - h, w, h } }; double total = 0; for(double[] piece: pieces) { total += totalArea(piece, circs, d - 1); } return total; } public static double totalArea(double[][] circs, int d) { double maxx = Double.NEGATIVE_INFINITY; double minx = Double.POSITIVE_INFINITY; double maxy = Double.NEGATIVE_INFINITY; double miny = Double.POSITIVE_INFINITY; for(double[] circ: circs) { if(circ[0] + circ[2] > maxx) { maxx = circ[0] + circ[2]; } if(circ[0] - circ[2] < minx) { minx = circ[0] - circ[2]; } if(circ[1] + circ[2] > maxy) { maxy = circ[1] + circ[2]; } if(circ[1] - circ[2] < miny) { miny = circ[1] - circ[2]; } } double[] rect = { minx, maxy, maxx - minx, maxy - miny }; surelyOutside = new boolean[circs.length]; return totalArea(rect, circs, d); } public static void main(String[] args) { double[][] circs = { { 1.6417233788, 1.6121789534, 0.0848270516 }, {-1.4944608174, 1.2077959613, 1.1039549836 }, { 0.6110294452, -0.6907087527, 0.9089162485 }, { 0.3844862411, 0.2923344616, 0.2375743054 }, {-0.2495892950, -0.3832854473, 1.0845181219 }, {1.7813504266, 1.6178237031, 0.8162655711 }, {-0.1985249206, -0.8343333301, 0.0538864941 }, {-1.7011985145, -0.1263820964, 0.4776976918 }, {-0.4319462812, 1.4104420482, 0.7886291537 }, {0.2178372997, -0.9499557344, 0.0357871187 }, {-0.6294854565, -1.3078893852, 0.7653357688 }, {1.7952608455, 0.6281269104, 0.2727652452 }, {1.4168575317, 1.0683357171, 1.1016025378 }, {1.4637371396, 0.9463877418, 1.1846214562 }, {-0.5263668798, 1.7315156631, 1.4428514068 }, {-1.2197352481, 0.9144146579, 1.0727263474 }, {-0.1389358881, 0.1092805780, 0.7350208828 }, {1.5293954595, 0.0030278255, 1.2472867347 }, {-0.5258728625, 1.3782633069, 1.3495508831 }, {-0.1403562064, 0.2437382535, 1.3804956588 }, {0.8055826339, -0.0482092025, 0.3327165165 }, {-0.6311979224, 0.7184578971, 0.2491045282 }, {1.4685857879, -0.8347049536, 1.3670667538 }, {-0.6855727502, 1.6465021616, 1.0593087096 }, {0.0152957411, 0.0638919221, 0.9771215985 } }; double ans = totalArea(circs, 24); System.out.println("Approx. area is " + ans); System.out.println("Error is " + Math.abs(21.56503660 - ans)); } }
Write the same code in Java as shown below in C.
#include "SL_Generated.h" #include "CImg.h" using namespace cimg_library; int main( int argc, char** argv ) { string fileName = "Pentagon.bmp"; if(argc > 1) fileName = argv[1]; int thetaAxisSize = 640; if(argc > 2) thetaAxisSize = atoi(argv[2]); int rAxisSize = 480; if(argc > 3) rAxisSize = atoi(argv[3]); int minContrast = 64; if(argc > 4) minContrast = atoi(argv[4]); int threads = 0; if(argc > 5) threads = atoi(argv[5]); char titleBuffer[200]; SLTimer t; CImg<int> image(fileName.c_str()); int imageDimensions[] = {image.height(), image.width(), 0}; Sequence<Sequence<int> > imageSeq((void*) image.data(), imageDimensions); Sequence< Sequence<int> > result; sl_init(threads); t.start(); sl_hough(imageSeq, thetaAxisSize, rAxisSize, minContrast, threads, result); t.stop(); CImg<int> resultImage(result[1].size(), result.size()); for(int y = 0; y < result.size(); y++) for(int x = 0; x < result[y+1].size(); x++) resultImage(x,result.size() - 1 - y) = result[y+1][x+1]; sprintf(titleBuffer, "SequenceL Hough Transformation: %d X %d Image to %d X %d Result | %d Cores | Processed in %f sec\0", image.width(), image.height(), resultImage.width(), resultImage.height(), threads, t.getTime()); resultImage.display(titleBuffer); sl_done(); return 0; }
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class HoughTransform { public static ArrayData houghTransform(ArrayData inputData, int thetaAxisSize, int rAxisSize, int minContrast) { int width = inputData.width; int height = inputData.height; int maxRadius = (int)Math.ceil(Math.hypot(width, height)); int halfRAxisSize = rAxisSize >>> 1; ArrayData outputData = new ArrayData(thetaAxisSize, rAxisSize); double[] sinTable = new double[thetaAxisSize]; double[] cosTable = new double[thetaAxisSize]; for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double thetaRadians = theta * Math.PI / thetaAxisSize; sinTable[theta] = Math.sin(thetaRadians); cosTable[theta] = Math.cos(thetaRadians); } for (int y = height - 1; y >= 0; y--) { for (int x = width - 1; x >= 0; x--) { if (inputData.contrast(x, y, minContrast)) { for (int theta = thetaAxisSize - 1; theta >= 0; theta--) { double r = cosTable[theta] * x + sinTable[theta] * y; int rScaled = (int)Math.round(r * halfRAxisSize / maxRadius) + halfRAxisSize; outputData.accumulate(theta, rScaled, 1); } } } } return outputData; } public static class ArrayData { public final int[] dataArray; public final int width; public final int height; public ArrayData(int width, int height) { this(new int[width * height], width, height); } public ArrayData(int[] dataArray, int width, int height) { this.dataArray = dataArray; this.width = width; this.height = height; } public int get(int x, int y) { return dataArray[y * width + x]; } public void set(int x, int y, int value) { dataArray[y * width + x] = value; } public void accumulate(int x, int y, int delta) { set(x, y, get(x, y) + delta); } public boolean contrast(int x, int y, int minContrast) { int centerValue = get(x, y); for (int i = 8; i >= 0; i--) { if (i == 4) continue; int newx = x + (i % 3) - 1; int newy = y + (i / 3) - 1; if ((newx < 0) || (newx >= width) || (newy < 0) || (newy >= height)) continue; if (Math.abs(get(newx, newy) - centerValue) >= minContrast) return true; } return false; } public int getMax() { int max = dataArray[0]; for (int i = width * height - 1; i > 0; i--) if (dataArray[i] > max) max = dataArray[i]; return max; } } public static ArrayData getArrayDataFromImage(String filename) throws IOException { BufferedImage inputImage = ImageIO.read(new File(filename)); int width = inputImage.getWidth(); int height = inputImage.getHeight(); int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width); ArrayData arrayData = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11); arrayData.set(x, height - 1 - y, rgbValue); } } return arrayData; } public static void writeOutputImage(String filename, ArrayData arrayData) throws IOException { int max = arrayData.getMax(); BufferedImage outputImage = new BufferedImage(arrayData.width, arrayData.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < arrayData.height; y++) { for (int x = 0; x < arrayData.width; x++) { int n = Math.min((int)Math.round(arrayData.get(x, y) * 255.0 / max), 255); outputImage.setRGB(x, arrayData.height - 1 - y, (n << 16) | (n << 8) | 0x90 | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { ArrayData inputData = getArrayDataFromImage(args[0]); int minContrast = (args.length >= 4) ? 64 : Integer.parseInt(args[4]); ArrayData outputData = houghTransform(inputData, Integer.parseInt(args[2]), Integer.parseInt(args[3]), minContrast); writeOutputImage(args[1], outputData); return; } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif typedef double (* Ifctn)( double t); double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b); for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
import static java.lang.Math.pow; import java.util.Arrays; import static java.util.Arrays.stream; import org.apache.commons.math3.special.Gamma; public class Test { static double x2Dist(double[] data) { double avg = stream(data).sum() / data.length; double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2)); return sqs / avg; } static double x2Prob(double dof, double distance) { return Gamma.regularizedGammaQ(dof / 2, distance / 2); } static boolean x2IsUniform(double[] data, double significance) { return x2Prob(data.length - 1.0, x2Dist(data)) > significance; } public static void main(String[] a) { double[][] dataSets = {{199809, 200665, 199607, 200270, 199649}, {522573, 244456, 139979, 71531, 21461}}; System.out.printf(" %4s %12s %12s %8s %s%n", "dof", "distance", "probability", "Uniform?", "dataset"); for (double[] ds : dataSets) { int dof = ds.length - 1; double dist = x2Dist(ds); double prob = x2Prob(dof, dist); System.out.printf("%4d %12.3f %12.8f %5s %6s%n", dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO", Arrays.toString(ds)); } } }
Convert this C snippet to Java and keep its semantics consistent.
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { v += (x - m) * (x - m); } v /= (n - 1); return new double[] {m, v}; } public static double[] welch_ttest(double[] x, double[] y) { double mx, my, vx, vy, t, df, p; double[] res; int nx = x.length, ny = y.length; res = meanvar(x); mx = res[0]; vx = res[1]; res = meanvar(y); my = res[0]; vy = res[1]; t = (mx-my)/Math.sqrt(vx/nx+vy/ny); df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1))); TDistribution dist = new TDistribution(df); p = 2.0*dist.cumulativeProbability(-Math.abs(t)); return new double[] {t, df, p}; } public static void main(String[] args) { double x[] = {3.0, 4.0, 1.0, 2.1}; double y[] = {490.2, 340.0, 433.9}; double res[] = welch_ttest(x, y); System.out.println("t = " + res[0]); System.out.println("df = " + res[1]); System.out.println("p = " + res[2]); } }
Keep all operations the same but rewrite the snippet in Java.
#include <stdio.h> #include <math.h> #include <stdlib.h> double Pvalue (const double *restrict ARRAY1, const size_t ARRAY1_SIZE, const double *restrict ARRAY2, const size_t ARRAY2_SIZE) { if (ARRAY1_SIZE <= 1) { return 1.0; } else if (ARRAY2_SIZE <= 1) { return 1.0; } double fmean1 = 0.0, fmean2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { if (isfinite(ARRAY1[x]) == 0) { puts("Got a non-finite number in 1st array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean1 += ARRAY1[x]; } fmean1 /= ARRAY1_SIZE; for (size_t x = 0; x < ARRAY2_SIZE; x++) { if (isfinite(ARRAY2[x]) == 0) { puts("Got a non-finite number in 2nd array, can't calculate P-value."); exit(EXIT_FAILURE); } fmean2 += ARRAY2[x]; } fmean2 /= ARRAY2_SIZE; if (fmean1 == fmean2) { return 1.0; } double unbiased_sample_variance1 = 0.0, unbiased_sample_variance2 = 0.0; for (size_t x = 0; x < ARRAY1_SIZE; x++) { unbiased_sample_variance1 += (ARRAY1[x]-fmean1)*(ARRAY1[x]-fmean1); } for (size_t x = 0; x < ARRAY2_SIZE; x++) { unbiased_sample_variance2 += (ARRAY2[x]-fmean2)*(ARRAY2[x]-fmean2); } unbiased_sample_variance1 = unbiased_sample_variance1/(ARRAY1_SIZE-1); unbiased_sample_variance2 = unbiased_sample_variance2/(ARRAY2_SIZE-1); const double WELCH_T_STATISTIC = (fmean1-fmean2)/sqrt(unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE); const double DEGREES_OF_FREEDOM = pow((unbiased_sample_variance1/ARRAY1_SIZE+unbiased_sample_variance2/ARRAY2_SIZE),2.0) / ( (unbiased_sample_variance1*unbiased_sample_variance1)/(ARRAY1_SIZE*ARRAY1_SIZE*(ARRAY1_SIZE-1))+ (unbiased_sample_variance2*unbiased_sample_variance2)/(ARRAY2_SIZE*ARRAY2_SIZE*(ARRAY2_SIZE-1)) ); const double a = DEGREES_OF_FREEDOM/2; double value = DEGREES_OF_FREEDOM/(WELCH_T_STATISTIC*WELCH_T_STATISTIC+DEGREES_OF_FREEDOM); if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } if ((isinf(value) != 0) || (isnan(value) != 0)) { return 1.0; } const double beta = lgammal(a)+0.57236494292470009-lgammal(a+0.5); const double acu = 0.1E-14; double ai; double cx; int indx; int ns; double pp; double psq; double qq; double rx; double temp; double term; double xx; if ( (a <= 0.0)) { } if ( value < 0.0 || 1.0 < value ) { return value; } if ( value == 0.0 || value == 1.0 ) { return value; } psq = a + 0.5; cx = 1.0 - value; if ( a < psq * value ) { xx = cx; cx = value; pp = 0.5; qq = a; indx = 1; } else { xx = value; pp = a; qq = 0.5; indx = 0; } term = 1.0; ai = 1.0; value = 1.0; ns = ( int ) ( qq + cx * psq ); rx = xx / cx; temp = qq - ai; if ( ns == 0 ) { rx = xx; } for ( ; ; ) { term = term * temp * rx / ( pp + ai ); value = value + term;; temp = fabs ( term ); if ( temp <= acu && temp <= acu * value ) { value = value * exp ( pp * log ( xx ) + ( qq - 1.0 ) * log ( cx ) - beta ) / pp; if ( indx ) { value = 1.0 - value; } break; } ai = ai + 1.0; ns = ns - 1; if ( 0 <= ns ) { temp = qq - ai; if ( ns == 0 ) { rx = xx; } } else { temp = psq; psq = psq + 1.0; } } return value; } int main(void) { const double d1[] = {27.5,21.0,19.0,23.6,17.0,17.9,16.9,20.1,21.9,22.6,23.1,19.6,19.0,21.7,21.4}; const double d2[] = {27.1,22.0,20.8,23.4,23.4,23.5,25.8,22.0,24.8,20.2,21.9,22.1,22.9,20.5,24.4}; const double d3[] = {17.2,20.9,22.6,18.1,21.7,21.4,23.5,24.2,14.7,21.8}; const double d4[] = {21.5,22.8,21.0,23.0,21.6,23.6,22.5,20.7,23.4,21.8,20.7,21.7,21.5,22.5,23.6,21.5,22.5,23.5,21.5,21.8}; const double d5[] = {19.8,20.4,19.6,17.8,18.5,18.9,18.3,18.9,19.5,22.0}; const double d6[] = {28.2,26.6,20.1,23.3,25.2,22.1,17.7,27.6,20.6,13.7,23.2,17.5,20.6,18.0,23.9,21.6,24.3,20.4,24.0,13.2}; const double d7[] = {30.02,29.99,30.11,29.97,30.01,29.99}; const double d8[] = {29.89,29.93,29.72,29.98,30.02,29.98}; const double x[] = {3.0,4.0,1.0,2.1}; const double y[] = {490.2,340.0,433.9}; const double v1[] = {0.010268,0.000167,0.000167}; const double v2[] = {0.159258,0.136278,0.122389}; const double s1[] = {1.0/15,10.0/62.0}; const double s2[] = {1.0/10,2/50.0}; const double z1[] = {9/23.0,21/45.0,0/38.0}; const double z2[] = {0/44.0,42/94.0,0/22.0}; const double CORRECT_ANSWERS[] = {0.021378001462867, 0.148841696605327, 0.0359722710297968, 0.090773324285671, 0.0107515611497845, 0.00339907162713746, 0.52726574965384, 0.545266866977794}; double pvalue = Pvalue(d1,sizeof(d1)/sizeof(*d1),d2,sizeof(d2)/sizeof(*d2)); double error = fabs(pvalue - CORRECT_ANSWERS[0]); printf("Test sets 1 p-value = %g\n", pvalue); pvalue = Pvalue(d3,sizeof(d3)/sizeof(*d3),d4,sizeof(d4)/sizeof(*d4)); error += fabs(pvalue - CORRECT_ANSWERS[1]); printf("Test sets 2 p-value = %g\n",pvalue); pvalue = Pvalue(d5,sizeof(d5)/sizeof(*d5),d6,sizeof(d6)/sizeof(*d6)); error += fabs(pvalue - CORRECT_ANSWERS[2]); printf("Test sets 3 p-value = %g\n", pvalue); pvalue = Pvalue(d7,sizeof(d7)/sizeof(*d7),d8,sizeof(d8)/sizeof(*d8)); printf("Test sets 4 p-value = %g\n", pvalue); error += fabs(pvalue - CORRECT_ANSWERS[3]); pvalue = Pvalue(x,sizeof(x)/sizeof(*x),y,sizeof(y)/sizeof(*y)); error += fabs(pvalue - CORRECT_ANSWERS[4]); printf("Test sets 5 p-value = %g\n", pvalue); pvalue = Pvalue(v1,sizeof(v1)/sizeof(*v1),v2,sizeof(v2)/sizeof(*v2)); error += fabs(pvalue - CORRECT_ANSWERS[5]); printf("Test sets 6 p-value = %g\n", pvalue); pvalue = Pvalue(s1,sizeof(s1)/sizeof(*s1),s2,sizeof(s2)/sizeof(*s2)); error += fabs(pvalue - CORRECT_ANSWERS[6]); printf("Test sets 7 p-value = %g\n", pvalue); pvalue = Pvalue(z1, 3, z2, 3); error += fabs(pvalue - CORRECT_ANSWERS[7]); printf("Test sets z p-value = %g\n", pvalue); printf("the cumulative error is %g\n", error); return 0; }
import org.apache.commons.math3.distribution.TDistribution; public class WelchTTest { public static double[] meanvar(double[] a) { double m = 0.0, v = 0.0; int n = a.length; for (double x: a) { m += x; } m /= n; for (double x: a) { v += (x - m) * (x - m); } v /= (n - 1); return new double[] {m, v}; } public static double[] welch_ttest(double[] x, double[] y) { double mx, my, vx, vy, t, df, p; double[] res; int nx = x.length, ny = y.length; res = meanvar(x); mx = res[0]; vx = res[1]; res = meanvar(y); my = res[0]; vy = res[1]; t = (mx-my)/Math.sqrt(vx/nx+vy/ny); df = Math.pow(vx/nx+vy/ny, 2)/(vx*vx/(nx*nx*(nx-1))+vy*vy/(ny*ny*(ny-1))); TDistribution dist = new TDistribution(df); p = 2.0*dist.cumulativeProbability(-Math.abs(t)); return new double[] {t, df, p}; } public static void main(String[] args) { double x[] = {3.0, 4.0, 1.0, 2.1}; double y[] = {490.2, 340.0, 433.9}; double res[] = welch_ttest(x, y); System.out.println("t = " + res[0]); System.out.println("df = " + res[1]); System.out.println("p = " + res[2]); } }
Port the following code from C to Java with equivalent syntax and logic.
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1"; Graph g = new Graph(s, new int[][]{ {0, 10}, {0, 2}, {0, 3}, {1, 10}, {1, 3}, {1, 4}, {2, 17}, {2, 5}, {2, 9}, {3, 6}, {3, 7}, {3, 8}, {3, 9}, {10, 11}, {10, 12}, {10, 13}, {11, 14}, {11, 15}, {13, 16}, {13, 17},}); System.out.println("Top levels: " + g.toplevels()); String[] files = {"top1", "top2", "ip1"}; for (String f : files) System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f)); } } class Graph { List<String> vertices; boolean[][] adjacency; int numVertices; public Graph(String s, int[][] edges) { vertices = asList(s.split(",")); numVertices = vertices.size(); adjacency = new boolean[numVertices][numVertices]; for (int[] edge : edges) adjacency[edge[0]][edge[1]] = true; } List<String> toplevels() { List<String> result = new ArrayList<>(); outer: for (int c = 0; c < numVertices; c++) { for (int r = 0; r < numVertices; r++) { if (adjacency[r][c]) continue outer; } result.add(vertices.get(c)); } return result; } List<String> compileOrder(String item) { LinkedList<String> result = new LinkedList<>(); LinkedList<Integer> queue = new LinkedList<>(); queue.add(vertices.indexOf(item)); while (!queue.isEmpty()) { int r = queue.poll(); for (int c = 0; c < numVertices; c++) { if (adjacency[r][c] && !queue.contains(c)) { queue.add(c); } } result.addFirst(vertices.get(r)); } return result.stream().distinct().collect(toList()); } }
Translate this program into Java but keep the logic exactly as in C.
char input[] = "top1 des1 ip1 ip2\n" "top2 des1 ip2 ip3\n" "ip1 extra1 ip1a ipcommon\n" "ip2 ip2a ip2b ip2c ipcommon\n" "des1 des1a des1b des1c\n" "des1a des1a1 des1a2\n" "des1c des1c1 extra1\n"; ... int find_name(item base, int len, const char *name) { int i; for (i = 0; i < len; i++) if (!strcmp(base[i].name, name)) return i; return -1; } int depends_on(item base, int n1, int n2) { int i; if (n1 == n2) return 1; for (i = 0; i < base[n1].n_deps; i++) if (depends_on(base, base[n1].deps[i], n2)) return 1; return 0; } void compile_order(item base, int n_items, int *top, int n_top) { int i, j, lvl; int d = 0; printf("Compile order for:"); for (i = 0; i < n_top; i++) { printf(" %s", base[top[i]].name); if (base[top[i]].depth > d) d = base[top[i]].depth; } printf("\n"); for (lvl = 1; lvl <= d; lvl ++) { printf("level %d:", lvl); for (i = 0; i < n_items; i++) { if (base[i].depth != lvl) continue; for (j = 0; j < n_top; j++) { if (depends_on(base, top[j], i)) { printf(" %s", base[i].name); break; } } } printf("\n"); } printf("\n"); } int main() { int i, n, bad = -1; item items; n = parse_input(&items); for (i = 0; i < n; i++) if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; int top[3]; top[0] = find_name(items, n, "top1"); top[1] = find_name(items, n, "top2"); top[2] = find_name(items, n, "ip1"); compile_order(items, n, top, 1); compile_order(items, n, top + 1, 1); compile_order(items, n, top, 2); compile_order(items, n, top + 2, 1); return 0; }
import java.util.*; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; public class TopologicalSort2 { public static void main(String[] args) { String s = "top1,top2,ip1,ip2,ip3,ip1a,ip2a,ip2b,ip2c,ipcommon,des1," + "des1a,des1b,des1c,des1a1,des1a2,des1c1,extra1"; Graph g = new Graph(s, new int[][]{ {0, 10}, {0, 2}, {0, 3}, {1, 10}, {1, 3}, {1, 4}, {2, 17}, {2, 5}, {2, 9}, {3, 6}, {3, 7}, {3, 8}, {3, 9}, {10, 11}, {10, 12}, {10, 13}, {11, 14}, {11, 15}, {13, 16}, {13, 17},}); System.out.println("Top levels: " + g.toplevels()); String[] files = {"top1", "top2", "ip1"}; for (String f : files) System.out.printf("Compile order for %s %s%n", f, g.compileOrder(f)); } } class Graph { List<String> vertices; boolean[][] adjacency; int numVertices; public Graph(String s, int[][] edges) { vertices = asList(s.split(",")); numVertices = vertices.size(); adjacency = new boolean[numVertices][numVertices]; for (int[] edge : edges) adjacency[edge[0]][edge[1]] = true; } List<String> toplevels() { List<String> result = new ArrayList<>(); outer: for (int c = 0; c < numVertices; c++) { for (int r = 0; r < numVertices; r++) { if (adjacency[r][c]) continue outer; } result.add(vertices.get(c)); } return result; } List<String> compileOrder(String item) { LinkedList<String> result = new LinkedList<>(); LinkedList<Integer> queue = new LinkedList<>(); queue.add(vertices.indexOf(item)); while (!queue.isEmpty()) { int r = queue.poll(); for (int c = 0; c < numVertices; c++) { if (adjacency[r][c] && !queue.contains(c)) { queue.add(c); } } result.addFirst(vertices.get(r)); } return result.stream().distinct().collect(toList()); } }
Generate a Java translation of this C snippet without changing its computational steps.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 typedef unsigned char character; typedef character *string; typedef struct node_t node; struct node_t { enum tag_t { NODE_LEAF, NODE_TREE, NODE_SEQ, } tag; union { string str; node *root; } data; node *next; }; node *allocate_node(enum tag_t tag) { node *n = malloc(sizeof(node)); if (n == NULL) { fprintf(stderr, "Failed to allocate node for tag: %d\n", tag); exit(1); } n->tag = tag; n->next = NULL; return n; } node *make_leaf(string str) { node *n = allocate_node(NODE_LEAF); n->data.str = str; return n; } node *make_tree() { node *n = allocate_node(NODE_TREE); n->data.root = NULL; return n; } node *make_seq() { node *n = allocate_node(NODE_SEQ); n->data.root = NULL; return n; } void deallocate_node(node *n) { if (n == NULL) { return; } deallocate_node(n->next); n->next = NULL; if (n->tag == NODE_LEAF) { free(n->data.str); n->data.str = NULL; } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) { deallocate_node(n->data.root); n->data.root = NULL; } else { fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag); exit(1); } free(n); } void append(node *root, node *elem) { if (root == NULL) { fprintf(stderr, "Cannot append to uninitialized node."); exit(1); } if (elem == NULL) { return; } if (root->tag == NODE_SEQ || root->tag == NODE_TREE) { if (root->data.root == NULL) { root->data.root = elem; } else { node *it = root->data.root; while (it->next != NULL) { it = it->next; } it->next = elem; } } else { fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag); exit(1); } } size_t count(node *n) { if (n == NULL) { return 0; } if (n->tag == NODE_LEAF) { return 1; } if (n->tag == NODE_TREE) { size_t sum = 0; node *it = n->data.root; while (it != NULL) { sum += count(it); it = it->next; } return sum; } if (n->tag == NODE_SEQ) { size_t prod = 1; node *it = n->data.root; while (it != NULL) { prod *= count(it); it = it->next; } return prod; } fprintf(stderr, "Cannot count node with tag: %d\n", n->tag); exit(1); } void expand(node *n, size_t pos) { if (n == NULL) { return; } if (n->tag == NODE_LEAF) { printf(n->data.str); } else if (n->tag == NODE_TREE) { node *it = n->data.root; while (true) { size_t cnt = count(it); if (pos < cnt) { expand(it, pos); break; } pos -= cnt; it = it->next; } } else if (n->tag == NODE_SEQ) { size_t prod = pos; node *it = n->data.root; while (it != NULL) { size_t cnt = count(it); size_t rem = prod % cnt; expand(it, rem); it = it->next; } } else { fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag); exit(1); } } string allocate_string(string src) { size_t len = strlen(src); string out = calloc(len + 1, sizeof(character)); if (out == NULL) { fprintf(stderr, "Failed to allocate a copy of the string."); exit(1); } strcpy(out, src); return out; } node *parse_seq(string input, size_t *pos); node *parse_tree(string input, size_t *pos) { node *root = make_tree(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; size_t depth = 0; bool asSeq = false; bool allow = false; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = '\\'; buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { buffer[bufpos++] = c; buffer[bufpos] = 0; asSeq = true; depth++; } else if (c == '}') { if (depth-- > 0) { buffer[bufpos++] = c; buffer[bufpos] = 0; } else { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); } else { append(root, make_leaf(allocate_string(buffer))); } break; } } else if (c == ',') { if (depth == 0) { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); bufpos = 0; buffer[bufpos] = 0; asSeq = false; } else { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } return root; } node *parse_seq(string input, size_t *pos) { node *root = make_seq(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { node *tree = parse_tree(input, pos); if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } append(root, tree); } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } return root; } void test(string input) { size_t pos = 0; node *n = parse_seq(input, &pos); size_t cnt = count(n); size_t i; printf("Pattern: %s\n", input); for (i = 0; i < cnt; i++) { expand(n, i); printf("\n"); } printf("\n"); deallocate_node(n); } int main() { test("~/{Downloads,Pictures}/*.{jpg,gif,png}"); test("It{{em,alic}iz,erat}e{d,}, please."); test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!"); return 0; }
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) { System.out.println(); expand(s); } } public static void expand(String s) { expandR("", s, ""); } private static void expandR(String pre, String s, String suf) { int i1 = -1, i2 = 0; String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " "); StringBuilder sb = null; outer: while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) { i2 = i1 + 1; sb = new StringBuilder(s); for (int depth = 1; i2 < s.length() && depth > 0; i2++) { char c = noEscape.charAt(i2); depth = (c == '{') ? ++depth : depth; depth = (c == '}') ? --depth : depth; if (c == ',' && depth == 1) { sb.setCharAt(i2, '\u0000'); } else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1) break outer; } } if (i1 == -1) { if (suf.length() > 0) expandR(pre + s, suf, ""); else System.out.printf("%s%s%s%n", pre, s, suf); } else { for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1)) expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf); } } }
Generate an equivalent Java version of this C code.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
foo(); Int x = bar();
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
foo(); Int x = bar();
Generate a Java translation of this C snippet without changing its computational steps.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
foo(); Int x = bar();
Can you help me rewrite this code in Java instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 12 char *super = 0; int pos, cnt[MAX]; int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; } int r(int n) { if (!n) return 0; char c = super[pos - n]; if (!--cnt[n]) { cnt[n] = n; if (!r(n-1)) return 0; } super[pos++] = c; return 1; } void superperm(int n) { int i, len; pos = n; len = fact_sum(n); super = realloc(super, len + 1); super[len] = '\0'; for (i = 0; i <= n; i++) cnt[i] = i; for (i = 1; i <= n; i++) super[i - 1] = i + '0'; while (r(n)); } int main(void) { int n; for (n = 0; n < MAX; n++) { printf("superperm(%2d) ", n); superperm(n); printf("len = %d", (int)strlen(super)); putchar('\n'); } return 0; }
import static java.util.stream.IntStream.rangeClosed; public class Test { final static int nMax = 12; static char[] superperm; static int pos; static int[] count = new int[nMax]; static int factSum(int n) { return rangeClosed(1, n) .map(m -> rangeClosed(1, m).reduce(1, (a, b) -> a * b)).sum(); } static boolean r(int n) { if (n == 0) return false; char c = superperm[pos - n]; if (--count[n] == 0) { count[n] = n; if (!r(n - 1)) return false; } superperm[pos++] = c; return true; } static void superPerm(int n) { String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pos = n; superperm = new char[factSum(n)]; for (int i = 0; i < n + 1; i++) count[i] = i; for (int i = 1; i < n + 1; i++) superperm[i - 1] = chars.charAt(i); while (r(n)) { } } public static void main(String[] args) { for (int n = 0; n < nMax; n++) { superPerm(n); System.out.printf("superPerm(%2d) len = %d", n, superperm.length); System.out.println(); } } }
Write the same algorithm in Java as shown in this C implementation.
#include <windows.h> #include "resource.h" BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) { switch( msg ) { case WM_INITDIALOG: srand( GetTickCount() ); SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE ); break; case WM_COMMAND: switch( LOWORD(wPar) ) { case IDC_INCREMENT: { UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE ); SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE ); } break; case IDC_RANDOM: { int reply = MessageBox( hwnd, "Do you really want to\nget a random number?", "Random input confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE ); } break; case IDC_QUIT: SendMessage( hwnd, WM_CLOSE, 0, 0 ); break; default: ; } break; case WM_CLOSE: { int reply = MessageBox( hwnd, "Do you really want to quit?", "Quit confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) EndDialog( hwnd, 0 ); } break; default: ; } return 0; } int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) { return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc ); }
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class Interact extends JFrame{ final JTextField numberField; final JButton incButton, randButton; public Interact(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); numberField = new JTextField(); incButton = new JButton("Increment"); randButton = new JButton("Random"); numberField.setText("0"); numberField.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if(!Character.isDigit(e.getKeyChar())){ e.consume(); } } @Override public void keyReleased(KeyEvent e){} @Override public void keyPressed(KeyEvent e){} }); incButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = numberField.getText(); if(text.isEmpty()){ numberField.setText("1"); }else{ numberField.setText((Long.valueOf(text) + 1) + ""); } } }); randButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if(JOptionPane.showConfirmDialog(null, "Are you sure?") == JOptionPane.YES_OPTION){ numberField.setText(Long.toString((long)(Math.random() * Long.MAX_VALUE))); } } }); setLayout(new GridLayout(2, 1)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); buttonPanel.add(incButton); buttonPanel.add(randButton); add(numberField); add(buttonPanel); pack(); } public static void main(String[] args){ new Interact().setVisible(true); } }
Port the following code from C to Java with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
import java.util.Arrays; import java.util.Random; public class OneOfNLines { static Random rand; public static int oneOfN(int n) { int choice = 0; for(int i = 1; i < n; i++) { if(rand.nextInt(i+1) == 0) choice = i; } return choice; } public static void main(String[] args) { int n = 10; int trials = 1000000; int[] bins = new int[n]; rand = new Random(); for(int i = 0; i < trials; i++) bins[oneOfN(n)]++; System.out.println(Arrays.toString(bins)); } }
Ensure the translated Java code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { if (head == tail) { head = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } #else #define new_rec() calloc(sizeof(rec_t), 1) #endif rec_t *find_rec(char *s) { int i; rec_t *r = &root; while (*s) { i = *s++ - '0'; if (!r->p[i]) r->p[i] = new_rec(); r = r->p[i]; } return r; } char number[100][4]; void init() { int i; for (i = 0; i < 100; i++) sprintf(number[i], "%d", i); } void count(char *buf) { int i, c[10] = {0}; char *s; for (s = buf; *s; c[*s++ - '0']++); for (i = 9; i >= 0; i--) { if (!c[i]) continue; s = number[c[i]]; *buf++ = s[0]; if ((*buf = s[1])) buf++; *buf++ = i + '0'; } *buf = '\0'; } int depth(char *in, int d) { rec_t *r = find_rec(in); if (r->depth > 0) return r->depth; d++; if (!r->depth) r->depth = -d; else r->depth += d; count(in); d = depth(in, d); if (r->depth <= 0) r->depth = d + 1; return r->depth; } int main(void) { char a[100]; int i, d, best_len = 0, n_best = 0; int best_ints[32]; rec_t *r; init(); for (i = 0; i < 1000000; i++) { sprintf(a, "%d", i); d = depth(a, 0); if (d < best_len) continue; if (d > best_len) { n_best = 0; best_len = d; } if (d == best_len) best_ints[n_best++] = i; } printf("longest length: %d\n", best_len); for (i = 0; i < n_best; i++) { printf("%d\n", best_ints[i]); sprintf(a, "%d", best_ints[i]); for (d = 0; d <= best_len; d++) { r = find_rec(a); printf("%3d: %s\n", r->depth, a); count(a); } putchar('\n'); } return 0; }
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class SelfReferentialSequence { static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000); public static void main(String[] args) { Seeds res = IntStream.range(0, 1000_000) .parallel() .mapToObj(n -> summarize(n, false)) .collect(Seeds::new, Seeds::accept, Seeds::combine); System.out.println("Seeds:"); res.seeds.forEach(e -> System.out.println(Arrays.toString(e))); System.out.println("\nSequence:"); summarize(res.seeds.get(0)[0], true); } static int[] summarize(int seed, boolean display) { String n = String.valueOf(seed); String k = Arrays.toString(n.chars().sorted().toArray()); if (!display && cache.get(k) != null) return new int[]{seed, cache.get(k)}; Set<String> seen = new HashSet<>(); StringBuilder sb = new StringBuilder(); int[] freq = new int[10]; while (!seen.contains(n)) { seen.add(n); int len = n.length(); for (int i = 0; i < len; i++) freq[n.charAt(i) - '0']++; sb.setLength(0); for (int i = 9; i >= 0; i--) { if (freq[i] != 0) { sb.append(freq[i]).append(i); freq[i] = 0; } } if (display) System.out.println(n); n = sb.toString(); } cache.put(k, seen.size()); return new int[]{seed, seen.size()}; } static class Seeds { int largest = Integer.MIN_VALUE; List<int[]> seeds = new ArrayList<>(); void accept(int[] s) { int size = s[1]; if (size >= largest) { if (size > largest) { largest = size; seeds.clear(); } seeds.add(s); } } void combine(Seeds acc) { acc.seeds.forEach(this::accept); } } }
Write the same code in Java as shown below in C.
#include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <glib.h> typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf("%llu: %s\n", n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
import java.util.HashMap; import java.util.Map; public class SpellingOfOrdinalNumbers { public static void main(String[] args) { for ( long test : new long[] {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003L} ) { System.out.printf("%d = %s%n", test, toOrdinal(test)); } } private static Map<String,String> ordinalMap = new HashMap<>(); static { ordinalMap.put("one", "first"); ordinalMap.put("two", "second"); ordinalMap.put("three", "third"); ordinalMap.put("five", "fifth"); ordinalMap.put("eight", "eighth"); ordinalMap.put("nine", "ninth"); ordinalMap.put("twelve", "twelfth"); } private static String toOrdinal(long n) { String spelling = numToString(n); String[] split = spelling.split(" "); String last = split[split.length - 1]; String replace = ""; if ( last.contains("-") ) { String[] lastSplit = last.split("-"); String lastWithDash = lastSplit[1]; String lastReplace = ""; if ( ordinalMap.containsKey(lastWithDash) ) { lastReplace = ordinalMap.get(lastWithDash); } else if ( lastWithDash.endsWith("y") ) { lastReplace = lastWithDash.substring(0, lastWithDash.length() - 1) + "ieth"; } else { lastReplace = lastWithDash + "th"; } replace = lastSplit[0] + "-" + lastReplace; } else { if ( ordinalMap.containsKey(last) ) { replace = ordinalMap.get(last); } else if ( last.endsWith("y") ) { replace = last.substring(0, last.length() - 1) + "ieth"; } else { replace = last + "th"; } } split[split.length - 1] = replace; return String.join(" ", split); } 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 numToString(long n) { return numToStringHelper(n); } private static final String numToStringHelper(long n) { if ( n < 0 ) { return "negative " + numToStringHelper(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? "-" + numToStringHelper(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 numToStringHelper(n / factor) + " " + label + (n % factor > 0 ? " " + numToStringHelper(n % factor ) : ""); } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
public class SelfDescribingNumbers{ public static boolean isSelfDescribing(int a){ String s = Integer.toString(a); for(int i = 0; i < s.length(); i++){ String s0 = s.charAt(i) + ""; int b = Integer.parseInt(s0); int count = 0; for(int j = 0; j < s.length(); j++){ int temp = Integer.parseInt(s.charAt(j) + ""); if(temp == i){ count++; } if (count > b) return false; } if(count != b) return false; } return true; } public static void main(String[] args){ for(int i = 0; i < 100000000; i++){ if(isSelfDescribing(i)){ System.out.println(i); } } } }
Write the same algorithm in Java as shown in this C implementation.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 typedef int bool; typedef struct { int x, y; } pair; int* example = NULL; int exampleLen = 0; void reverse(int s[], int len) { int i, j, t; for (i = 0, j = len - 1; i < j; ++i, --j) { t = s[i]; s[i] = s[j]; s[j] = t; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen); pair checkSeq(int pos, int seq[], int n, int len, int minLen) { pair p; if (pos > minLen || seq[0] > n) { p.x = minLen; p.y = 0; return p; } else if (seq[0] == n) { example = malloc(len * sizeof(int)); memcpy(example, seq, len * sizeof(int)); exampleLen = len; p.x = pos; p.y = 1; return p; } else if (pos < minLen) { return tryPerm(0, pos, seq, n, len, minLen); } else { p.x = minLen; p.y = 0; return p; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) { int *seq2; pair p, res1, res2; size_t size = sizeof(int); if (i > pos) { p.x = minLen; p.y = 0; return p; } seq2 = malloc((len + 1) * size); memcpy(seq2 + 1, seq, len * size); seq2[0] = seq[0] + seq[i]; res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen); res2 = tryPerm(i + 1, pos, seq, n, len, res1.x); free(seq2); if (res2.x < res1.x) return res2; else if (res2.x == res1.x) { p.x = res2.x; p.y = res1.y + res2.y; return p; } else { printf("Error in tryPerm\n"); p.x = 0; p.y = 0; return p; } } pair initTryPerm(int x, int minLen) { int seq[1] = {1}; return tryPerm(0, 0, seq, x, 1, minLen); } void printArray(int a[], int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]\n"); } bool isBrauer(int a[], int len) { int i, j; bool ok; for (i = 2; i < len; ++i) { ok = FALSE; for (j = i - 1; j >= 0; j--) { if (a[i-1] + a[j] == a[i]) { ok = TRUE; break; } } if (!ok) return FALSE; } return TRUE; } bool isAdditionChain(int a[], int len) { int i, j, k; bool ok, exit; for (i = 2; i < len; ++i) { if (a[i] > a[i - 1] * 2) return FALSE; ok = FALSE; exit = FALSE; for (j = i - 1; j >= 0; --j) { for (k = j; k >= 0; --k) { if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; } } if (exit) break; } if (!ok) return FALSE; } if (example == NULL && !isBrauer(a, len)) { example = malloc(len * sizeof(int)); memcpy(example, a, len * sizeof(int)); exampleLen = len; } return TRUE; } void nextChains(int index, int len, int seq[], int *pcount) { for (;;) { int i; if (index < len - 1) { nextChains(index + 1, len, seq, pcount); } if (seq[index] + len - 1 - index >= seq[len - 1]) return; seq[index]++; for (i = index + 1; i < len - 1; ++i) { seq[i] = seq[i-1] + 1; } if (isAdditionChain(seq, len)) (*pcount)++; } } int findNonBrauer(int num, int len, int brauer) { int i, count = 0; int *seq = malloc(len * sizeof(int)); seq[0] = 1; seq[len - 1] = num; for (i = 1; i < len - 1; ++i) { seq[i] = seq[i - 1] + 1; } if (isAdditionChain(seq, len)) count = 1; nextChains(2, len, seq, &count); free(seq); return count - brauer; } void findBrauer(int num, int minLen, int nbLimit) { pair p = initTryPerm(num, minLen); int actualMin = p.x, brauer = p.y, nonBrauer; printf("\nN = %d\n", num); printf("Minimum length of chains : L(%d) = %d\n", num, actualMin); printf("Number of minimum length Brauer chains : %d\n", brauer); if (brauer > 0) { printf("Brauer example : "); reverse(example, exampleLen); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } if (num <= nbLimit) { nonBrauer = findNonBrauer(num, actualMin + 1, brauer); printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer); if (nonBrauer > 0) { printf("Non-Brauer example : "); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } } else { printf("Non-Brauer analysis suppressed\n"); } } int main() { int i; int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; printf("Searching for Brauer chains up to a minimum length of 12:\n"); for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79); return 0; }
public class AdditionChains { private static class Pair { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1]; result[0] = n; System.arraycopy(seq, 0, result, 1, seq.length); return result; } private static Pair check_seq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Pair(min_len, 0); else if (seq[0] == n) return new Pair(pos, 1); else if (pos < min_len) return try_perm(0, pos, seq, n, min_len); else return new Pair(min_len, 0); } private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Pair(min_len, 0); Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len); Pair res2 = try_perm(i + 1, pos, seq, n, res1.f); if (res2.f < res1.f) return res2; else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s); else throw new RuntimeException("Try_perm exception"); } private static Pair init_try_perm(int x) { return try_perm(0, 0, new int[]{1}, x, 12); } private static void find_brauer(int num) { Pair res = init_try_perm(num); System.out.println(); System.out.println("N = " + num); System.out.println("Minimum length of chains: L(n)= " + res.f); System.out.println("Number of minimum length Brauer chains: " + res.s); } public static void main(String[] args) { int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; for (int i : nums) { find_brauer(i); } } }
Convert this C snippet to Java and keep its semantics consistent.
#include <locale.h> #include <stdio.h> int main() { unsigned long long int trillion = 1000000000000; setlocale(LC_NUMERIC,""); printf("Locale : %s, One Trillion : %'llu\n", setlocale(LC_CTYPE,NULL),trillion); return 0; }
public class NumericSeparatorSyntax { public static void main(String[] args) { runTask("Underscore allowed as seperator", 1_000); runTask("Multiple consecutive underscores allowed:", 1__0_0_0); runTask("Many multiple consecutive underscores allowed:", 1________________________00); runTask("Underscores allowed in multiple positions", 1__4__4); runTask("Underscores allowed in negative number", -1__4__4); runTask("Underscores allowed in floating point number", 1__4__4e-5); runTask("Underscores allowed in floating point exponent", 1__4__440000e-1_2); } private static void runTask(String description, long n) { runTask(description, n, "%d"); } private static void runTask(String description, double n) { runTask(description, n, "%3.7f"); } private static void runTask(String description, Number n, String format) { System.out.printf("%s: " + format + "%n", description, n); } }
Write the same code in Java as shown below in C.
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
import java.util.function.Consumer; import java.util.stream.IntStream; public class Repeat { public static void main(String[] args) { repeat(3, (x) -> System.out.println("Example " + x)); } static void repeat (int n, Consumer<Integer> fun) { IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); } }
Generate a Java translation of this C snippet without changing its computational steps.
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; now.display1D(arr1); System.out.println(now.getSparkline(arr1)); } public void display1D(float[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public String getSparkline(float[] arr) { float min=Integer.MAX_VALUE; float max=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } float range=max-min; int num=bars.length()-1; String line=""; for(int i=0;i<arr.length;i++) { line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num))); } return line; } }
Convert this C block to Java, preserving its control flow and logic.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str_to_nodes = new HashMap<>(); 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(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"), nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"), nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"), nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"), nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or"); private final String name; NodeType(String name) { this.name = name; } @Override public String toString() { return this.name; } } static String str(String s) { String result = ""; int i = 0; s = s.replace("\"", ""); while (i < s.length()) { if (s.charAt(i) == '\\' && i + 1 < s.length()) { if (s.charAt(i + 1) == 'n') { result += '\n'; i += 2; } else if (s.charAt(i) == '\\') { result += '\\'; i += 2; } } else { result += s.charAt(i); i++; } } return result; } static boolean itob(int i) { return i != 0; } static int btoi(boolean b) { return b ? 1 : 0; } static int fetch_var(String name) { int result; if (globals.containsKey(name)) { result = globals.get(name); } else { globals.put(name, 0); result = 0; } return result; } static Integer interpret(Node n) throws Exception { if (n == null) { return 0; } switch (n.nt) { case nd_Integer: return Integer.parseInt(n.value); case nd_Ident: return fetch_var(n.value); case nd_String: return 1; case nd_Assign: globals.put(n.left.value, interpret(n.right)); return 0; case nd_Add: return interpret(n.left) + interpret(n.right); case nd_Sub: return interpret(n.left) - interpret(n.right); case nd_Mul: return interpret(n.left) * interpret(n.right); case nd_Div: return interpret(n.left) / interpret(n.right); case nd_Mod: return interpret(n.left) % interpret(n.right); case nd_Lss: return btoi(interpret(n.left) < interpret(n.right)); case nd_Leq: return btoi(interpret(n.left) <= interpret(n.right)); case nd_Gtr: return btoi(interpret(n.left) > interpret(n.right)); case nd_Geq: return btoi(interpret(n.left) >= interpret(n.right)); case nd_Eql: return btoi(interpret(n.left) == interpret(n.right)); case nd_Neq: return btoi(interpret(n.left) != interpret(n.right)); case nd_And: return btoi(itob(interpret(n.left)) && itob(interpret(n.right))); case nd_Or: return btoi(itob(interpret(n.left)) || itob(interpret(n.right))); case nd_Not: if (interpret(n.left) == 0) { return 1; } else { return 0; } case nd_Negate: return -interpret(n.left); case nd_If: if (interpret(n.left) != 0) { interpret(n.right.left); } else { interpret(n.right.right); } return 0; case nd_While: while (interpret(n.left) != 0) { interpret(n.right); } return 0; case nd_Prtc: System.out.printf("%c", interpret(n.left)); return 0; case nd_Prti: System.out.printf("%d", interpret(n.left)); return 0; case nd_Prts: System.out.print(str(n.left.value)); return 0; case nd_Sequence: interpret(n.left); interpret(n.right); return 0; default: throw new Exception("Error: '" + n.nt + "' found, expecting operator"); } } 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(); interpret(n); } catch (Exception e) { System.out.println("Ex: "+e.getMessage()); } } } }
Keep all operations the same but rewrite the snippet in Java.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str_to_nodes = new HashMap<>(); 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(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"), nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"), nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"), nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"), nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or"); private final String name; NodeType(String name) { this.name = name; } @Override public String toString() { return this.name; } } static String str(String s) { String result = ""; int i = 0; s = s.replace("\"", ""); while (i < s.length()) { if (s.charAt(i) == '\\' && i + 1 < s.length()) { if (s.charAt(i + 1) == 'n') { result += '\n'; i += 2; } else if (s.charAt(i) == '\\') { result += '\\'; i += 2; } } else { result += s.charAt(i); i++; } } return result; } static boolean itob(int i) { return i != 0; } static int btoi(boolean b) { return b ? 1 : 0; } static int fetch_var(String name) { int result; if (globals.containsKey(name)) { result = globals.get(name); } else { globals.put(name, 0); result = 0; } return result; } static Integer interpret(Node n) throws Exception { if (n == null) { return 0; } switch (n.nt) { case nd_Integer: return Integer.parseInt(n.value); case nd_Ident: return fetch_var(n.value); case nd_String: return 1; case nd_Assign: globals.put(n.left.value, interpret(n.right)); return 0; case nd_Add: return interpret(n.left) + interpret(n.right); case nd_Sub: return interpret(n.left) - interpret(n.right); case nd_Mul: return interpret(n.left) * interpret(n.right); case nd_Div: return interpret(n.left) / interpret(n.right); case nd_Mod: return interpret(n.left) % interpret(n.right); case nd_Lss: return btoi(interpret(n.left) < interpret(n.right)); case nd_Leq: return btoi(interpret(n.left) <= interpret(n.right)); case nd_Gtr: return btoi(interpret(n.left) > interpret(n.right)); case nd_Geq: return btoi(interpret(n.left) >= interpret(n.right)); case nd_Eql: return btoi(interpret(n.left) == interpret(n.right)); case nd_Neq: return btoi(interpret(n.left) != interpret(n.right)); case nd_And: return btoi(itob(interpret(n.left)) && itob(interpret(n.right))); case nd_Or: return btoi(itob(interpret(n.left)) || itob(interpret(n.right))); case nd_Not: if (interpret(n.left) == 0) { return 1; } else { return 0; } case nd_Negate: return -interpret(n.left); case nd_If: if (interpret(n.left) != 0) { interpret(n.right.left); } else { interpret(n.right.right); } return 0; case nd_While: while (interpret(n.left) != 0) { interpret(n.right); } return 0; case nd_Prtc: System.out.printf("%c", interpret(n.left)); return 0; case nd_Prti: System.out.printf("%d", interpret(n.left)); return 0; case nd_Prts: System.out.print(str(n.left.value)); return 0; case nd_Sequence: interpret(n.left); interpret(n.right); return 0; default: throw new Exception("Error: '" + n.nt + "' found, expecting operator"); } } 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(); interpret(n); } catch (Exception e) { System.out.println("Ex: "+e.getMessage()); } } } }
Change the programming language of this snippet from C to Java without modifying what it does.
count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str_to_nodes = new HashMap<>(); 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(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"), nd_Sequence("Sequence"), nd_If("If"), nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"), nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"), nd_Mod("Mod"), nd_Add("Add"), nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"), nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or"); private final String name; NodeType(String name) { this.name = name; } @Override public String toString() { return this.name; } } static String str(String s) { String result = ""; int i = 0; s = s.replace("\"", ""); while (i < s.length()) { if (s.charAt(i) == '\\' && i + 1 < s.length()) { if (s.charAt(i + 1) == 'n') { result += '\n'; i += 2; } else if (s.charAt(i) == '\\') { result += '\\'; i += 2; } } else { result += s.charAt(i); i++; } } return result; } static boolean itob(int i) { return i != 0; } static int btoi(boolean b) { return b ? 1 : 0; } static int fetch_var(String name) { int result; if (globals.containsKey(name)) { result = globals.get(name); } else { globals.put(name, 0); result = 0; } return result; } static Integer interpret(Node n) throws Exception { if (n == null) { return 0; } switch (n.nt) { case nd_Integer: return Integer.parseInt(n.value); case nd_Ident: return fetch_var(n.value); case nd_String: return 1; case nd_Assign: globals.put(n.left.value, interpret(n.right)); return 0; case nd_Add: return interpret(n.left) + interpret(n.right); case nd_Sub: return interpret(n.left) - interpret(n.right); case nd_Mul: return interpret(n.left) * interpret(n.right); case nd_Div: return interpret(n.left) / interpret(n.right); case nd_Mod: return interpret(n.left) % interpret(n.right); case nd_Lss: return btoi(interpret(n.left) < interpret(n.right)); case nd_Leq: return btoi(interpret(n.left) <= interpret(n.right)); case nd_Gtr: return btoi(interpret(n.left) > interpret(n.right)); case nd_Geq: return btoi(interpret(n.left) >= interpret(n.right)); case nd_Eql: return btoi(interpret(n.left) == interpret(n.right)); case nd_Neq: return btoi(interpret(n.left) != interpret(n.right)); case nd_And: return btoi(itob(interpret(n.left)) && itob(interpret(n.right))); case nd_Or: return btoi(itob(interpret(n.left)) || itob(interpret(n.right))); case nd_Not: if (interpret(n.left) == 0) { return 1; } else { return 0; } case nd_Negate: return -interpret(n.left); case nd_If: if (interpret(n.left) != 0) { interpret(n.right.left); } else { interpret(n.right.right); } return 0; case nd_While: while (interpret(n.left) != 0) { interpret(n.right); } return 0; case nd_Prtc: System.out.printf("%c", interpret(n.left)); return 0; case nd_Prti: System.out.printf("%d", interpret(n.left)); return 0; case nd_Prts: System.out.print(str(n.left.value)); return 0; case nd_Sequence: interpret(n.left); interpret(n.right); return 0; default: throw new Exception("Error: '" + n.nt + "' found, expecting operator"); } } 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(); interpret(n); } catch (Exception e) { System.out.println("Ex: "+e.getMessage()); } } } }
Generate an equivalent Java version of this C code.
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
Write the same algorithm in Java as shown in this C implementation.
#define WINVER 0x500 #include<windows.h> int main() { int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); int x = maxX/2, y = maxY/2; double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY; INPUT ip; ZeroMemory(&ip,sizeof(ip)); ip.type = INPUT_MOUSE; while(x > 5 || y < maxY-5){ ip.mi.mouseData = 0; ip.mi.dx = x * factorX; ip.mi.dy = y * factorY; ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; SendInput(1,&ip,sizeof(ip)); Sleep(1); if(x>3) x-=1; if(y<maxY-3) y+=1; } ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP; SendInput(1,&ip,sizeof(ip)); return 0; }
Point p = component.getLocation(); Robot robot = new Robot(); robot.mouseMove(p.getX(), p.getY()); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK);
Port the following code from C to Java with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class HelloWorld{ public static void main(String[] args) throws IOException{ ServerSocket listener = new ServerSocket(8080); while(true){ Socket sock = listener.accept(); new PrintWriter(sock.getOutputStream(), true). println("Goodbye, World!"); sock.close(); } } }
Generate a Java translation of this C snippet without changing its computational steps.
void cls(void) { printf("\33[2J"); }
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
Convert this C block to Java, preserving its control flow and logic.
#include<graphics.h> #include<math.h> #define pi M_PI void sunflower(int winWidth, int winHeight, double diskRatio, int iter){ double factor = .5 + sqrt(1.25),r,theta; double x = winWidth/2.0, y = winHeight/2.0; double maxRad = pow(iter,factor)/iter; int i; setbkcolor(LIGHTBLUE); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW); theta = 2*pi*factor*i; circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter)); } } int main() { initwindow(1000,1000,"Sunflower..."); sunflower(1000,1000,0.5,3000); getch(); closegraph(); return 0; }
size(1000,1000); surface.setTitle("Sunflower..."); int iter = 3000; float factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5; float x = width/2.0, y = height/2.0; double maxRad = pow(iter,factor)/iter; int i; background(#add8e6); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; if(r/maxRad < diskRatio){ stroke(#000000); } else stroke(#ffff00); theta = 2*PI*factor*i; ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter)); }
Translate the given C code snippet into Java without altering its behavior.
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 4 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
import java.util.Arrays; import static java.util.Arrays.stream; import java.util.concurrent.*; public class VogelsApproximationMethod { final static int[] demand = {30, 20, 70, 30, 60}; final static int[] supply = {50, 60, 50, 50}; final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}}; final static int nRows = supply.length; final static int nCols = demand.length; static boolean[] rowDone = new boolean[nRows]; static boolean[] colDone = new boolean[nCols]; static int[][] result = new int[nRows][nCols]; static ExecutorService es = Executors.newFixedThreadPool(2); public static void main(String[] args) throws Exception { int supplyLeft = stream(supply).sum(); int totalCost = 0; while (supplyLeft > 0) { int[] cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = Math.min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) colDone[c] = true; supply[r] -= quantity; if (supply[r] == 0) rowDone[r] = true; result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } stream(result).forEach(a -> System.out.println(Arrays.toString(a))); System.out.println("Total cost: " + totalCost); es.shutdown(); } static int[] nextCell() throws Exception { Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true)); Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false)); int[] res1 = f1.get(); int[] res2 = f2.get(); if (res1[3] == res2[3]) return res1[2] < res2[2] ? res1 : res2; return (res1[3] > res2[3]) ? res2 : res1; } static int[] diff(int j, int len, boolean isRow) { int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) continue; int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) min2 = c; } return new int[]{min2 - min1, min1, minP}; } static int[] maxPenalty(int len1, int len2, boolean isRow) { int md = Integer.MIN_VALUE; int pc = -1, pm = -1, mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) continue; int[] res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; pm = i; mc = res[1]; pc = res[2]; } } return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md}; } }
Change the programming language of this snippet from C to Java without modifying what it does.
#include <math.h> #include <stdio.h> #define DEG 0.017453292519943295769236907684886127134 #define RE 6371000.0 #define DD 0.001 #define FIN 10000000.0 static double rho(double a) { return exp(-a / 8500.0); } static double height(double a, double z, double d) { double aa = RE + a; double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG)); return hh - RE; } static double column_density(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = DD * d; if (delta < DD) delta = DD; sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } static double airmass(double a, double z) { return column_density(a, z) / column_density(a, 0.0); } int main() { puts("Angle 0 m 13700 m"); puts("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } }
public class AirMass { public static void main(String[] args) { System.out.println("Angle 0 m 13700 m"); System.out.println("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { System.out.printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } } private static double rho(double a) { return Math.exp(-a / 8500.0); } private static double height(double a, double z, double d) { double aa = RE + a; double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z))); return hh - RE; } private static double columnDensity(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = Math.max(DD * d, DD); sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } private static double airmass(double a, double z) { return columnDensity(a, z) / columnDensity(a, 0.0); } private static final double RE = 6371000.0; private static final double DD = 0.001; private static final double FIN = 10000000.0; }
Convert this C block to Java, preserving its control flow and logic.
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
public class PancakeSort { int[] heap; public String toString() { String info = ""; for (int x: heap) info += x + " "; return info; } public void flip(int n) { for (int i = 0; i < (n+1) / 2; ++i) { int tmp = heap[i]; heap[i] = heap[n-i]; heap[n-i] = tmp; } System.out.println("flip(0.." + n + "): " + toString()); } public int[] minmax(int n) { int xm, xM; xm = xM = heap[0]; int posm = 0, posM = 0; for (int i = 1; i < n; ++i) { if (heap[i] < xm) { xm = heap[i]; posm = i; } else if (heap[i] > xM) { xM = heap[i]; posM = i; } } return new int[] {posm, posM}; } public void sort(int n, int dir) { if (n == 0) return; int[] mM = minmax(n); int bestXPos = mM[dir]; int altXPos = mM[1-dir]; boolean flipped = false; if (bestXPos == n-1) { --n; } else if (bestXPos == 0) { flip(n-1); --n; } else if (altXPos == n-1) { dir = 1-dir; --n; flipped = true; } else { flip(bestXPos); } sort(n, dir); if (flipped) { flip(n); } } PancakeSort(int[] numbers) { heap = numbers; sort(numbers.length, 1); } public static void main(String[] args) { int[] numbers = new int[args.length]; for (int i = 0; i < args.length; ++i) numbers[i] = Integer.valueOf(args[i]); PancakeSort pancakes = new PancakeSort(numbers); System.out.println(pancakes); } }
Generate a Java translation of this C snippet without changing its computational steps.
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
public class PancakeSort { int[] heap; public String toString() { String info = ""; for (int x: heap) info += x + " "; return info; } public void flip(int n) { for (int i = 0; i < (n+1) / 2; ++i) { int tmp = heap[i]; heap[i] = heap[n-i]; heap[n-i] = tmp; } System.out.println("flip(0.." + n + "): " + toString()); } public int[] minmax(int n) { int xm, xM; xm = xM = heap[0]; int posm = 0, posM = 0; for (int i = 1; i < n; ++i) { if (heap[i] < xm) { xm = heap[i]; posm = i; } else if (heap[i] > xM) { xM = heap[i]; posM = i; } } return new int[] {posm, posM}; } public void sort(int n, int dir) { if (n == 0) return; int[] mM = minmax(n); int bestXPos = mM[dir]; int altXPos = mM[1-dir]; boolean flipped = false; if (bestXPos == n-1) { --n; } else if (bestXPos == 0) { flip(n-1); --n; } else if (altXPos == n-1) { dir = 1-dir; --n; flipped = true; } else { flip(bestXPos); } sort(n, dir); if (flipped) { flip(n); } } PancakeSort(int[] numbers) { heap = numbers; sort(numbers.length, 1); } public static void main(String[] args) { int[] numbers = new int[args.length]; for (int i = 0; i < args.length; ++i) numbers[i] = Integer.valueOf(args[i]); PancakeSort pancakes = new PancakeSort(numbers); System.out.println(pancakes); } }
Write the same code in Java as shown below in C.
#include <ldap.h> ... char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); ... after done with it... ldap_unbind(ld);
import java.io.IOException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapConnectionDemo { public static void main(String[] args) throws LdapException, IOException { try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) { connection.bind(); connection.unBind(); } } }
Convert this C snippet to Java and keep its semantics consistent.
#include<stdlib.h> #include<string.h> #include<stdio.h> int flag = 1; void heapPermute(int n, int arr[],int arrLen){ int temp; int i; if(n==1){ printf("\n["); for(i=0;i<arrLen;i++) printf("%d,",arr[i]); printf("\b] Sign : %d",flag); flag*=-1; } else{ for(i=0;i<n-1;i++){ heapPermute(n-1,arr,arrLen); if(n%2==0){ temp = arr[i]; arr[i] = arr[n-1]; arr[n-1] = temp; } else{ temp = arr[0]; arr[0] = arr[n-1]; arr[n-1] = temp; } } heapPermute(n-1,arr,arrLen); } } int main(int argC,char* argV[0]) { int *arr, i=0, count = 1; char* token; if(argC==1) printf("Usage : %s <comma separated list of integers>",argV[0]); else{ while(argV[1][i]!=00){ if(argV[1][i++]==',') count++; } arr = (int*)malloc(count*sizeof(int)); i = 0; token = strtok(argV[1],","); while(token!=NULL){ arr[i++] = atoi(token); token = strtok(NULL,","); } heapPermute(i,arr,count); } return 0; }
package org.rosettacode.java; import java.util.Arrays; import java.util.stream.IntStream; public class HeapsAlgorithm { public static void main(String[] args) { Object[] array = IntStream.range(0, 4) .boxed() .toArray(); HeapsAlgorithm algorithm = new HeapsAlgorithm(); algorithm.recursive(array); System.out.println(); algorithm.loop(array); } void recursive(Object[] array) { recursive(array, array.length, true); } void recursive(Object[] array, int n, boolean plus) { if (n == 1) { output(array, plus); } else { for (int i = 0; i < n; i++) { recursive(array, n - 1, i == 0); swap(array, n % 2 == 0 ? i : 0, n - 1); } } } void output(Object[] array, boolean plus) { System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1")); } void swap(Object[] array, int a, int b) { Object o = array[a]; array[a] = array[b]; array[b] = o; } void loop(Object[] array) { loop(array, array.length); } void loop(Object[] array, int n) { int[] c = new int[n]; output(array, true); boolean plus = false; for (int i = 0; i < n; ) { if (c[i] < i) { if (i % 2 == 0) { swap(array, 0, i); } else { swap(array, c[i], i); } output(array, plus); plus = !plus; c[i]++; i = 0; } else { c[i] = 0; i++; } } } }
Write a version of this C function in Java with identical behavior.
#include <stdio.h> #include <math.h> #include <string.h> #define N 2200 int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); } private static List<Long> getPythagoreanQuadruples(long max) { List<Long> list = new ArrayList<>(); long n = -1; long m = -1; while ( true ) { long nTest = (long) Math.pow(2, n+1); long mTest = (long) (5L * Math.pow(2, m+1)); long test = 0; if ( nTest > mTest ) { test = mTest; m++; } else { test = nTest; n++; } if ( test < max ) { list.add(test); } else { break; } } return list; } }
Rewrite this program in Java while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <math.h> #include <string.h> #define N 2200 int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); } private static List<Long> getPythagoreanQuadruples(long max) { List<Long> list = new ArrayList<>(); long n = -1; long m = -1; while ( true ) { long nTest = (long) Math.pow(2, n+1); long mTest = (long) (5L * Math.pow(2, m+1)); long test = 0; if ( nTest > mTest ) { test = mTest; m++; } else { test = nTest; n++; } if ( test < max ) { list.add(test); } else { break; } } return list; } }
Port the following code from C to Java with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); disableOption("needspeeling"); setOption("numberofbananas", "1024"); addOption("numberofstrawberries", "62000"); store(); } } private enum EntryType { EMPTY, ENABLED, DISABLED, COMMENT } private static class Entry { EntryType type; String name, value; Entry(EntryType t, String n, String v) { type = t; name = n; value = v; } } private static Map<String, Entry> entries = new LinkedHashMap<>(); private static String path; private static boolean readConfig(String p) { path = p; File f = new File(path); if (!f.exists() || f.isDirectory()) return false; String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)"; Pattern regex = Pattern.compile(regexString); try (Scanner sc = new Scanner(new FileReader(f))){ int emptyLines = 0; String line; while (sc.hasNext()) { line = sc.nextLine().trim(); if (line.isEmpty()) { addOption("" + emptyLines++, null, EntryType.EMPTY); } else if (line.charAt(0) == '#') { entries.put(line, new Entry(EntryType.COMMENT, line, null)); } else { line = line.replaceAll("[^a-zA-Z0-9\\x20;]", ""); Matcher m = regex.matcher(line); if (m.find() && !m.group(2).isEmpty()) { EntryType t = EntryType.ENABLED; if (!m.group(1).isEmpty()) t = EntryType.DISABLED; addOption(m.group(2), m.group(3), t); } } } } catch (IOException e) { System.out.println(e); } return true; } private static void addOption(String name, String value) { addOption(name, value, EntryType.ENABLED); } private static void addOption(String name, String value, EntryType t) { name = name.toUpperCase(); entries.put(name, new Entry(t, name, value)); } private static void enableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.ENABLED; } private static void disableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.DISABLED; } private static void setOption(String name, String value) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.value = value; } private static void store() { try (PrintWriter pw = new PrintWriter(path)) { for (Entry e : entries.values()) { switch (e.type) { case EMPTY: pw.println(); break; case ENABLED: pw.format("%s %s%n", e.name, e.value); break; case DISABLED: pw.format("; %s %s%n", e.name, e.value); break; case COMMENT: pw.println(e.name); break; default: break; } } if (pw.checkError()) { throw new IOException("writing to file failed"); } } catch (IOException e) { System.out.println(e); } } }
Write a version of this C function in Java with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); disableOption("needspeeling"); setOption("numberofbananas", "1024"); addOption("numberofstrawberries", "62000"); store(); } } private enum EntryType { EMPTY, ENABLED, DISABLED, COMMENT } private static class Entry { EntryType type; String name, value; Entry(EntryType t, String n, String v) { type = t; name = n; value = v; } } private static Map<String, Entry> entries = new LinkedHashMap<>(); private static String path; private static boolean readConfig(String p) { path = p; File f = new File(path); if (!f.exists() || f.isDirectory()) return false; String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)"; Pattern regex = Pattern.compile(regexString); try (Scanner sc = new Scanner(new FileReader(f))){ int emptyLines = 0; String line; while (sc.hasNext()) { line = sc.nextLine().trim(); if (line.isEmpty()) { addOption("" + emptyLines++, null, EntryType.EMPTY); } else if (line.charAt(0) == '#') { entries.put(line, new Entry(EntryType.COMMENT, line, null)); } else { line = line.replaceAll("[^a-zA-Z0-9\\x20;]", ""); Matcher m = regex.matcher(line); if (m.find() && !m.group(2).isEmpty()) { EntryType t = EntryType.ENABLED; if (!m.group(1).isEmpty()) t = EntryType.DISABLED; addOption(m.group(2), m.group(3), t); } } } } catch (IOException e) { System.out.println(e); } return true; } private static void addOption(String name, String value) { addOption(name, value, EntryType.ENABLED); } private static void addOption(String name, String value, EntryType t) { name = name.toUpperCase(); entries.put(name, new Entry(t, name, value)); } private static void enableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.ENABLED; } private static void disableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.DISABLED; } private static void setOption(String name, String value) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.value = value; } private static void store() { try (PrintWriter pw = new PrintWriter(path)) { for (Entry e : entries.values()) { switch (e.type) { case EMPTY: pw.println(); break; case ENABLED: pw.format("%s %s%n", e.name, e.value); break; case DISABLED: pw.format("; %s %s%n", e.name, e.value); break; case COMMENT: pw.println(e.name); break; default: break; } } if (pw.checkError()) { throw new IOException("writing to file failed"); } } catch (IOException e) { System.out.println(e); } } }
Please provide an equivalent version of this C code in Java.
image filter(image img, double *K, int Ks, double, double);
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class ImageConvolution { public static class ArrayData { public final int[] dataArray; public final int width; public final int height; public ArrayData(int width, int height) { this(new int[width * height], width, height); } public ArrayData(int[] dataArray, int width, int height) { this.dataArray = dataArray; this.width = width; this.height = height; } public int get(int x, int y) { return dataArray[y * width + x]; } public void set(int x, int y, int value) { dataArray[y * width + x] = value; } } private static int bound(int value, int endIndex) { if (value < 0) return 0; if (value < endIndex) return value; return endIndex - 1; } public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor) { int inputWidth = inputData.width; int inputHeight = inputData.height; int kernelWidth = kernel.width; int kernelHeight = kernel.height; if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd width"); if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd height"); int kernelWidthRadius = kernelWidth >>> 1; int kernelHeightRadius = kernelHeight >>> 1; ArrayData outputData = new ArrayData(inputWidth, inputHeight); for (int i = inputWidth - 1; i >= 0; i--) { for (int j = inputHeight - 1; j >= 0; j--) { double newValue = 0.0; for (int kw = kernelWidth - 1; kw >= 0; kw--) for (int kh = kernelHeight - 1; kh >= 0; kh--) newValue += kernel.get(kw, kh) * inputData.get( bound(i + kw - kernelWidthRadius, inputWidth), bound(j + kh - kernelHeightRadius, inputHeight)); outputData.set(i, j, (int)Math.round(newValue / kernelDivisor)); } } return outputData; } public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException { BufferedImage inputImage = ImageIO.read(new File(filename)); int width = inputImage.getWidth(); int height = inputImage.getHeight(); int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width); ArrayData reds = new ArrayData(width, height); ArrayData greens = new ArrayData(width, height); ArrayData blues = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; reds.set(x, y, (rgbValue >>> 16) & 0xFF); greens.set(x, y, (rgbValue >>> 8) & 0xFF); blues.set(x, y, rgbValue & 0xFF); } } return new ArrayData[] { reds, greens, blues }; } public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException { ArrayData reds = redGreenBlue[0]; ArrayData greens = redGreenBlue[1]; ArrayData blues = redGreenBlue[2]; BufferedImage outputImage = new BufferedImage(reds.width, reds.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < reds.height; y++) { for (int x = 0; x < reds.width; x++) { int red = bound(reds.get(x, y), 256); int green = bound(greens.get(x, y), 256); int blue = bound(blues.get(x, y), 256); outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { int kernelWidth = Integer.parseInt(args[2]); int kernelHeight = Integer.parseInt(args[3]); int kernelDivisor = Integer.parseInt(args[4]); System.out.println("Kernel size: " + kernelWidth + "x" + kernelHeight + ", divisor=" + kernelDivisor); int y = 5; ArrayData kernel = new ArrayData(kernelWidth, kernelHeight); for (int i = 0; i < kernelHeight; i++) { System.out.print("["); for (int j = 0; j < kernelWidth; j++) { kernel.set(j, i, Integer.parseInt(args[y++])); System.out.print(" " + kernel.get(j, i) + " "); } System.out.println("]"); } ArrayData[] dataArrays = getArrayDatasFromImage(args[0]); for (int i = 0; i < dataArrays.length; i++) dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor); writeOutputImage(args[1], dataArrays); return; } }
Transform the following C implementation into Java, maintaining the same output and logic.
#include <stdio.h> #include <stdint.h> typedef uint32_t uint; typedef uint64_t ulong; ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; } uint min(const uint x, const uint y) { return (x < y) ? x : y; } void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; } for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); } double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1); const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2); const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2)); double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; } int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
import java.util.Random; public class Dice{ private static int roll(int nDice, int nSides){ int sum = 0; Random rand = new Random(); for(int i = 0; i < nDice; i++){ sum += rand.nextInt(nSides) + 1; } return sum; } private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){ int p1Wins = 0; for(int i = 0; i < rolls; i++){ int p1Roll = roll(p1Dice, p1Sides); int p2Roll = roll(p2Dice, p2Sides); if(p1Roll > p2Roll) p1Wins++; } return p1Wins; } public static void main(String[] args){ int p1Dice = 9; int p1Sides = 4; int p2Dice = 6; int p2Sides = 6; int rolls = 10000; int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 5; p1Sides = 10; p2Dice = 6; p2Sides = 7; rolls = 10000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 9; p1Sides = 4; p2Dice = 6; p2Sides = 6; rolls = 1000000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 5; p1Sides = 10; p2Dice = 6; p2Sides = 7; rolls = 1000000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); } }
Generate a Java translation of this C snippet without changing its computational steps.
#include<windows.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<math.h> #define pi M_PI int main() { CONSOLE_SCREEN_BUFFER_INFO info; int cols, rows; time_t t; int i,j; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); cols = info.srWindow.Right - info.srWindow.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system("@clear||cls"); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf("%c",219); } getchar(); return 0; }
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB); plasma = createPlasma(dim.height, dim.width); new Timer(42, (ActionEvent e) -> { hueShift = (hueShift + 0.02f) % 1; repaint(); }).start(); } float[][] createPlasma(int w, int h) { float[][] buffer = new float[h][w]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { double value = sin(x / 16.0); value += sin(y / 8.0); value += sin((x + y) / 16.0); value += sin(sqrt(x * x + y * y) / 8.0); value += 4; value /= 8; assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds"; buffer[y][x] = (float) value; } return buffer; } void drawPlasma(Graphics2D g) { int h = plasma.length; int w = plasma[0].length; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float hue = hueShift + plasma[y][x] % 1; img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1)); } g.drawImage(img, 0, 0, null); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPlasma(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Plasma Effect"); f.setResizable(false); f.add(new PlasmaEffect(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Produce a language-to-language conversion: from C to Java, same semantics.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <expat.h> #include <pcre.h> #ifdef XML_LARGE_SIZE # define XML_FMT_INT_MOD "ll" #else # define XML_FMT_INT_MOD "l" #endif #ifdef XML_UNICODE_WCHAR_T # define XML_FMT_STR "ls" #else # define XML_FMT_STR "s" #endif void reset_char_data_buffer(); void process_char_data_buffer(); static bool last_tag_is_title; static bool last_tag_is_text; static pcre *reCompiled; static pcre_extra *pcreExtra; void start_element(void *data, const char *element, const char **attribute) { process_char_data_buffer(); reset_char_data_buffer(); if (strcmp("title", element) == 0) { last_tag_is_title = true; } if (strcmp("text", element) == 0) { last_tag_is_text = true; } } void end_element(void *data, const char *el) { process_char_data_buffer(); reset_char_data_buffer(); } #define TITLE_BUF_SIZE (1024 * 8) static char char_data_buffer[1024 * 64 * 8]; static char title_buffer[TITLE_BUF_SIZE]; static size_t offs; static bool overflow; void reset_char_data_buffer(void) { offs = 0; overflow = false; } void char_data(void *userData, const XML_Char *s, int len) { if (!overflow) { if (len + offs >= sizeof(char_data_buffer)) { overflow = true; fprintf(stderr, "Warning: buffer overflow\n"); fflush(stderr); } else { memcpy(char_data_buffer + offs, s, len); offs += len; } } } void try_match(); void process_char_data_buffer(void) { if (offs > 0) { char_data_buffer[offs] = '\0'; if (last_tag_is_title) { unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1); memcpy(title_buffer, char_data_buffer, n); last_tag_is_title = false; } if (last_tag_is_text) { try_match(); last_tag_is_text = false; } } } void try_match() { int subStrVec[80]; int subStrVecLen; int pcreExecRet; subStrVecLen = sizeof(subStrVec) / sizeof(int); pcreExecRet = pcre_exec( reCompiled, pcreExtra, char_data_buffer, strlen(char_data_buffer), 0, 0, subStrVec, subStrVecLen); if (pcreExecRet < 0) { switch (pcreExecRet) { case PCRE_ERROR_NOMATCH : break; case PCRE_ERROR_NULL : fprintf(stderr, "Something was null\n"); break; case PCRE_ERROR_BADOPTION : fprintf(stderr, "A bad option was passed\n"); break; case PCRE_ERROR_BADMAGIC : fprintf(stderr, "Magic number bad (compiled re corrupt?)\n"); break; case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, "Something kooky in the compiled re\n"); break; case PCRE_ERROR_NOMEMORY : fprintf(stderr, "Ran out of memory\n"); break; default : fprintf(stderr, "Unknown error\n"); break; } } else { puts(title_buffer); } } #define BUF_SIZE 1024 int main(int argc, char *argv[]) { char buffer[BUF_SIZE]; int n; const char *pcreErrorStr; int pcreErrorOffset; char *aStrRegex; char **aLineToMatch; aStrRegex = "(.*)(==French==)(.*)"; reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL); if (reCompiled == NULL) { fprintf(stderr, "ERROR: Could not compile regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr); if (pcreErrorStr != NULL) { fprintf(stderr, "ERROR: Could not study regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } XML_Parser parser = XML_ParserCreate(NULL); XML_SetElementHandler(parser, start_element, end_element); XML_SetCharacterDataHandler(parser, char_data); reset_char_data_buffer(); while (1) { int done; int len; len = (int)fread(buffer, 1, BUF_SIZE, stdin); if (ferror(stdin)) { fprintf(stderr, "Read error\n"); exit(1); } done = feof(stdin); if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) { fprintf(stderr, "Parse error at line %" XML_FMT_INT_MOD "u:\n%" XML_FMT_STR "\n", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); exit(1); } if (done) break; } XML_ParserFree(parser); pcre_free(reCompiled); if (pcreExtra != NULL) { #ifdef PCRE_CONFIG_JIT pcre_free_study(pcreExtra); #else pcre_free(pcreExtra); #endif } return 0; }
import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import java.util.regex.Pattern; import java.util.regex.Matcher; class MyHandler extends DefaultHandler { private static final String TITLE = "title"; private static final String TEXT = "text"; private String lastTag = ""; private String title = ""; @Override public void characters(char[] ch, int start, int length) throws SAXException { String regex = ".*==French==.*"; Pattern pat = Pattern.compile(regex, Pattern.DOTALL); switch (lastTag) { case TITLE: title = new String(ch, start, length); break; case TEXT: String text = new String(ch, start, length); Matcher mat = pat.matcher(text); if (mat.matches()) { System.out.println(title); } break; } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { lastTag = qName; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { lastTag = ""; } } public class WiktoWords { public static void main(java.lang.String[] args) { try { SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser = spFactory.newSAXParser(); MyHandler handler = new MyHandler(); saxParser.parse(new InputSource(System.in), handler); } catch(Exception e) { System.exit(1); } } }
Change the following C code into Java without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <expat.h> #include <pcre.h> #ifdef XML_LARGE_SIZE # define XML_FMT_INT_MOD "ll" #else # define XML_FMT_INT_MOD "l" #endif #ifdef XML_UNICODE_WCHAR_T # define XML_FMT_STR "ls" #else # define XML_FMT_STR "s" #endif void reset_char_data_buffer(); void process_char_data_buffer(); static bool last_tag_is_title; static bool last_tag_is_text; static pcre *reCompiled; static pcre_extra *pcreExtra; void start_element(void *data, const char *element, const char **attribute) { process_char_data_buffer(); reset_char_data_buffer(); if (strcmp("title", element) == 0) { last_tag_is_title = true; } if (strcmp("text", element) == 0) { last_tag_is_text = true; } } void end_element(void *data, const char *el) { process_char_data_buffer(); reset_char_data_buffer(); } #define TITLE_BUF_SIZE (1024 * 8) static char char_data_buffer[1024 * 64 * 8]; static char title_buffer[TITLE_BUF_SIZE]; static size_t offs; static bool overflow; void reset_char_data_buffer(void) { offs = 0; overflow = false; } void char_data(void *userData, const XML_Char *s, int len) { if (!overflow) { if (len + offs >= sizeof(char_data_buffer)) { overflow = true; fprintf(stderr, "Warning: buffer overflow\n"); fflush(stderr); } else { memcpy(char_data_buffer + offs, s, len); offs += len; } } } void try_match(); void process_char_data_buffer(void) { if (offs > 0) { char_data_buffer[offs] = '\0'; if (last_tag_is_title) { unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1); memcpy(title_buffer, char_data_buffer, n); last_tag_is_title = false; } if (last_tag_is_text) { try_match(); last_tag_is_text = false; } } } void try_match() { int subStrVec[80]; int subStrVecLen; int pcreExecRet; subStrVecLen = sizeof(subStrVec) / sizeof(int); pcreExecRet = pcre_exec( reCompiled, pcreExtra, char_data_buffer, strlen(char_data_buffer), 0, 0, subStrVec, subStrVecLen); if (pcreExecRet < 0) { switch (pcreExecRet) { case PCRE_ERROR_NOMATCH : break; case PCRE_ERROR_NULL : fprintf(stderr, "Something was null\n"); break; case PCRE_ERROR_BADOPTION : fprintf(stderr, "A bad option was passed\n"); break; case PCRE_ERROR_BADMAGIC : fprintf(stderr, "Magic number bad (compiled re corrupt?)\n"); break; case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, "Something kooky in the compiled re\n"); break; case PCRE_ERROR_NOMEMORY : fprintf(stderr, "Ran out of memory\n"); break; default : fprintf(stderr, "Unknown error\n"); break; } } else { puts(title_buffer); } } #define BUF_SIZE 1024 int main(int argc, char *argv[]) { char buffer[BUF_SIZE]; int n; const char *pcreErrorStr; int pcreErrorOffset; char *aStrRegex; char **aLineToMatch; aStrRegex = "(.*)(==French==)(.*)"; reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL); if (reCompiled == NULL) { fprintf(stderr, "ERROR: Could not compile regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr); if (pcreErrorStr != NULL) { fprintf(stderr, "ERROR: Could not study regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } XML_Parser parser = XML_ParserCreate(NULL); XML_SetElementHandler(parser, start_element, end_element); XML_SetCharacterDataHandler(parser, char_data); reset_char_data_buffer(); while (1) { int done; int len; len = (int)fread(buffer, 1, BUF_SIZE, stdin); if (ferror(stdin)) { fprintf(stderr, "Read error\n"); exit(1); } done = feof(stdin); if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) { fprintf(stderr, "Parse error at line %" XML_FMT_INT_MOD "u:\n%" XML_FMT_STR "\n", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); exit(1); } if (done) break; } XML_ParserFree(parser); pcre_free(reCompiled); if (pcreExtra != NULL) { #ifdef PCRE_CONFIG_JIT pcre_free_study(pcreExtra); #else pcre_free(pcreExtra); #endif } return 0; }
import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import java.util.regex.Pattern; import java.util.regex.Matcher; class MyHandler extends DefaultHandler { private static final String TITLE = "title"; private static final String TEXT = "text"; private String lastTag = ""; private String title = ""; @Override public void characters(char[] ch, int start, int length) throws SAXException { String regex = ".*==French==.*"; Pattern pat = Pattern.compile(regex, Pattern.DOTALL); switch (lastTag) { case TITLE: title = new String(ch, start, length); break; case TEXT: String text = new String(ch, start, length); Matcher mat = pat.matcher(text); if (mat.matches()) { System.out.println(title); } break; } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { lastTag = qName; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { lastTag = ""; } } public class WiktoWords { public static void main(java.lang.String[] args) { try { SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser = spFactory.newSAXParser(); MyHandler handler = new MyHandler(); saxParser.parse(new InputSource(System.in), handler); } catch(Exception e) { System.exit(1); } } }
Preserve the algorithm and functionality while converting the code from C++ to C#.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
Port the provided C++ code into C# while preserving the original functionality.
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
Change the following C++ code into C# without altering its purpose.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(double a) { return normalize<double>(a, 400); } inline double m2m(double a) { return normalize<double>(a, 6400); } inline double r2r(double a) { return normalize<double>(a, 2*M_PI); } double d2g(double a) { return g2g(a * 10 / 9); } double d2m(double a) { return m2m(a * 160 / 9); } double d2r(double a) { return r2r(a * M_PI / 180); } double g2d(double a) { return d2d(a * 9 / 10); } double g2m(double a) { return m2m(a * 16); } double g2r(double a) { return r2r(a * M_PI / 200); } double m2d(double a) { return d2d(a * 9 / 160); } double m2g(double a) { return g2g(a / 16); } double m2r(double a) { return r2r(a * M_PI / 3200); } double r2d(double a) { return d2d(a * 180 / M_PI); } double r2g(double a) { return g2g(a * 200 / M_PI); } double r2m(double a) { return m2m(a * 3200 / M_PI); } void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) { using namespace std; ostringstream out; out << " ┌───────────────────┐\n"; out << " │ " << setw(17) << s << " │\n"; out << "┌─────────────────┼───────────────────┤\n"; for (double i : values) out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n"; out << "└─────────────────┴───────────────────┘\n"; auto str = out.str(); boost::algorithm::replace_all(str, ".000000", " "); cout << str; } int main() { std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }; print(values, "normalized (deg)", d2d); print(values, "normalized (grad)", g2g); print(values, "normalized (mil)", m2m); print(values, "normalized (rad)", r2r); print(values, "deg -> grad ", d2g); print(values, "deg -> mil ", d2m); print(values, "deg -> rad ", d2r); print(values, "grad -> deg ", g2d); print(values, "grad -> mil ", g2m); print(values, "grad -> rad ", g2r); print(values, "mil -> deg ", m2d); print(values, "mil -> grad ", m2g); print(values, "mil -> rad ", m2r); print(values, "rad -> deg ", r2d); print(values, "rad -> grad ", r2g); print(values, "rad -> mil ", r2m); return 0; }
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Math.Round(a, 4); Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad }; Func<double, double>[,] convert = { { a => a, DegToGrad, DegToMil, DegToRad }, { GradToDeg, a => a, GradToMil, GradToRad }, { MilToDeg, MilToGrad, a => a, MilToRad }, { RadToDeg, RadToGrad, RadToMil, a => a } }; Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{ "Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}"); foreach (double angle in angles) { for (int i = 0; i < 4; i++) { double nAngle = normal[i](angle); Console.WriteLine($@"{ rnd(angle),-12}{ rnd(nAngle),-12}{ names[i],-12}{ rnd(convert[i, 0](nAngle)),-12}{ rnd(convert[i, 1](nAngle)),-12}{ rnd(convert[i, 2](nAngle)),-12}{ rnd(convert[i, 3](nAngle)),-12}"); } } } public static double NormalizeDeg(double angle) => Normalize(angle, 360); public static double NormalizeGrad(double angle) => Normalize(angle, 400); public static double NormalizeMil(double angle) => Normalize(angle, 6400); public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI); private static double Normalize(double angle, double N) { while (angle <= -N) angle += N; while (angle >= N) angle -= N; return angle; } public static double DegToGrad(double angle) => angle * 10 / 9; public static double DegToMil(double angle) => angle * 160 / 9; public static double DegToRad(double angle) => angle * Math.PI / 180; public static double GradToDeg(double angle) => angle * 9 / 10; public static double GradToMil(double angle) => angle * 16; public static double GradToRad(double angle) => angle * Math.PI / 200; public static double MilToDeg(double angle) => angle * 9 / 160; public static double MilToGrad(double angle) => angle / 16; public static double MilToRad(double angle) => angle * Math.PI / 3200; public static double RadToDeg(double angle) => angle * 180 / Math.PI; public static double RadToGrad(double angle) => angle * 200 / Math.PI; public static double RadToMil(double angle) => angle * 3200 / Math.PI; }
Transform the following C++ implementation into C#, maintaining the same output and logic.
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( ); foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } } return CommonPath; } } }
Keep all operations the same but rewrite the snippet in C++.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
Port the provided C++ code into C# while preserving the original functionality.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
Change the programming language of this snippet from C++ to C# without modifying what it does.
#include <string> int main() { int* p; p = new int; delete p; p = new int(2); delete p; std::string* p2; p2 = new std::string; delete p2; p = new int[10]; delete[] p; p2 = new std::string[10]; delete[] p2; }
using System; using System.Runtime.InteropServices; public unsafe class Program { public static unsafe void HeapMemory() { const int HEAP_ZERO_MEMORY = 0x00000008; const int size = 1000; int ph = GetProcessHeap(); void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if (pointer == null) throw new OutOfMemoryException(); Console.WriteLine(HeapSize(ph, 0, pointer)); HeapFree(ph, 0, pointer); } public static unsafe void StackMemory() { byte* buffer = stackalloc byte[1000]; } public static void Main(string[] args) { HeapMemory(); StackMemory(); } [DllImport("kernel32")] static extern void* HeapAlloc(int hHeap, int flags, int size); [DllImport("kernel32")] static extern bool HeapFree(int hHeap, int flags, void* block); [DllImport("kernel32")] static extern int GetProcessHeap(); [DllImport("kernel32")] static extern int HeapSize(int hHeap, int flags, void* block); }
Write a version of this C++ function in C# with identical behavior.
#include <windows.h> #include <iostream> #include <string> using namespace std; enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; class ttt { public: ttt() { _p = rand() % 2; reset(); } void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove(); drawGrid(); res = checkVictory(); if( res != None ) break; ++_p %= 2; } if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!"; cout << endl << endl; string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return; ++_p %= 2; reset(); } } private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; } void drawGrid() { system( "cls" ); COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl; int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; } c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); } int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } } int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw; return None; } void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 ); if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; } _field[m - 1] = Human; } void getComputerMove() { int move = 0; do{ move = rand() % 9; } while( _field[move] != None ); for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2]; if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; } if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; } if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer; } int _p; int _field[9]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); ttt tic; tic.play(); return 0; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const int Computer = 0; const int Human = 1; static int[] GameBoard = new int[9]; static int[] corners = new int[] { 0, 2, 6, 8 }; static int[][] wins = new int[][] { new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); initializeGameBoard(); displayGameBoard(); int currentPlayer = rnd.Next(0, 2); Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); while (true) { int thisMove = getMoveFor(currentPlayer); if (thisMove == Unplayed) { Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); break; } playMove(thisMove, currentPlayer); displayGameBoard(); if (isGameWon()) { Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); break; } else if (isGameTied()) { Console.WriteLine("Cat game ... we have a tie."); break; } currentPlayer = getNextPlayer(currentPlayer); } if (!playAgain()) return; } } static int getMoveFor(int player) { if (player == Human) return getManualMove(player); else { int selectedMove = getSemiRandomMove(player); Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); return selectedMove; } } static int getManualMove(int player) { while (true) { Console.Write("{0}, enter you move (number): ", playerName(player)); ConsoleKeyInfo keyInfo = Console.ReadKey(); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape) return Unplayed; if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) { int move = keyInfo.KeyChar - '1'; if (GameBoard[move] == Unplayed) return move; else Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); } else Console.WriteLine("Illegal move, please select again.\n"); } } static int getRandomMove(int player) { int movesLeft = GameBoard.Count(position => position == Unplayed); int x = rnd.Next(0, movesLeft); for (int i = 0; i < GameBoard.Length; i++) { if (GameBoard[i] == Unplayed && x < 0) return i; x--; } return Unplayed; } static int getSemiRandomMove(int player) { int posToPlay; if (checkForWinningMove(player, out posToPlay)) return posToPlay; if (checkForBlockingMove(player, out posToPlay)) return posToPlay; return getRandomMove(player); } static int getBestMove(int player) { return -1; } static bool checkForWinningMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(player, line, out posToPlay)) return true; return false; } static bool checkForBlockingMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) return true; return false; } static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) { int cnt = 0; posToPlay = int.MinValue; foreach (int pos in line) { if (GameBoard[pos] == player) cnt++; else if (GameBoard[pos] == Unplayed) posToPlay = pos; } return cnt == 2 && posToPlay >= 0; } static void playMove(int boardPosition, int player) { GameBoard[boardPosition] = player; } static bool isGameWon() { return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); } static bool takenBySamePlayer(int a, int b, int c) { return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; } static bool isGameTied() { return !GameBoard.Any(spot => spot == Unplayed); } static Random rnd = new Random(); static void initializeGameBoard() { for (int i = 0; i < GameBoard.Length; i++) GameBoard[i] = Unplayed; } static string playerName(int player) { return Players[player][0]; } static string playerToken(int player) { return Players[player][1]; } static int getNextPlayer(int player) { return (player + 1) % 2; } static void displayGameBoard() { Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); Console.WriteLine(); } static string pieceAt(int boardPosition) { if (GameBoard[boardPosition] == Unplayed) return (boardPosition + 1).ToString(); return playerToken(GameBoard[boardPosition]); } private static bool playAgain() { Console.WriteLine("\nDo you want to play again?"); return Console.ReadKey(false).Key == ConsoleKey.Y; } } }
Rewrite this program in C# while keeping its functionality equivalent to the C++ version.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
Generate a C++ translation of this C# snippet without changing its computational steps.
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
Port the following code from C++ to C# with equivalent syntax and logic.
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Change the programming language of this snippet from C++ to C# without modifying what it does.
template<typename F> class fivetoseven { public: fivetoseven(F f): d5(f), rem(0), max(1) {} int operator()(); private: F d5; int rem, max; }; template<typename F> int fivetoseven<F>::operator()() { while (rem/7 == max/7) { while (max < 7) { int rand5 = d5()-1; max *= 5; rem = 5*rem + rand5; } int groups = max / 7; if (rem >= 7*groups) { rem -= 7*groups; max -= 7*groups; } } int result = rem % 7; rem /= 7; max /= 7; return result+1; } int d5() { return 5.0*std::rand()/(RAND_MAX + 1.0) + 1; } fivetoseven<int(*)()> d7(d5); int main() { srand(time(0)); test_distribution(d5, 1000000, 0.001); test_distribution(d7, 1000000, 0.001); }
using System; public class SevenSidedDice { Random random = new Random(); static void Main(string[] args) { SevenSidedDice sevenDice = new SevenSidedDice(); Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven()); Console.Read(); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1 + random.Next(5); } }
Keep all operations the same but rewrite the snippet in C#.
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } bool is_magnanimous(unsigned int n) { for (unsigned int p = 10; n >= p; p *= 10) { if (!is_prime(n % p + n / p)) return false; } return true; } int main() { unsigned int count = 0, n = 0; std::cout << "First 45 magnanimous numbers:\n"; for (; count < 45; ++n) { if (is_magnanimous(n)) { if (count > 0) std::cout << (count % 15 == 0 ? "\n" : ", "); std::cout << std::setw(3) << n; ++count; } } std::cout << "\n\n241st through 250th magnanimous numbers:\n"; for (unsigned int i = 0; count < 250; ++n) { if (is_magnanimous(n)) { if (count++ >= 240) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << "\n\n391st through 400th magnanimous numbers:\n"; for (unsigned int i = 0; count < 400; ++n) { if (is_magnanimous(n)) { if (count++ >= 390) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << '\n'; return 0; }
using System; using static System.Console; class Program { static bool[] np; static void ms(long lmt) { np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt; k += n) np[k] = true; } static bool is_Mag(long n) { long res, rem; for (long p = 10; n >= p; p *= 10) { res = Math.DivRem (n, p, out rem); if (np[res + rem]) return false; } return true; } static void Main(string[] args) { ms(100_009); string mn; WriteLine("First 45{0}", mn = " magnanimous numbers:"); for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) { if (c++ < 45 || (c > 240 && c <= 250) || c > 390) Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l); if (c < 45 && c % 15 == 0) WriteLine(); if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn); if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } } }
Convert this C++ snippet to C# and keep its semantics consistent.
#include <iostream> int main() { int dim1, dim2; std::cin >> dim1 >> dim2; double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; array[0][0] = 3.5; std::cout << array[0][0] << std::endl; delete[] array; delete[] array_data; return 0; }
class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console.ReadLine(); int[,] myArray=new int[(int)s[0],(int)s[2]]; myArray[0, 0] = 2; Console.WriteLine(myArray[0, 0]); Console.ReadLine(); } }
Generate an equivalent C# version of this C++ code.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Rewrite this program in C++ while keeping its functionality equivalent to the C# version.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Translate this program into C# but keep the logic exactly as in C++.
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; for(;;) { std::cout << *++g; } }
using System; using System.Numerics; namespace PiCalc { internal class Program { private readonly BigInteger FOUR = new BigInteger(4); private readonly BigInteger SEVEN = new BigInteger(7); private readonly BigInteger TEN = new BigInteger(10); private readonly BigInteger THREE = new BigInteger(3); private readonly BigInteger TWO = new BigInteger(2); private BigInteger k = BigInteger.One; private BigInteger l = new BigInteger(3); private BigInteger n = new BigInteger(3); private BigInteger q = BigInteger.One; private BigInteger r = BigInteger.Zero; private BigInteger t = BigInteger.One; public void CalcPiDigits() { BigInteger nn, nr; bool first = true; while (true) { if ((FOUR*q + r - t).CompareTo(n*t) == -1) { Console.Write(n); if (first) { Console.Write("."); first = false; } nr = TEN*(r - (n*t)); n = TEN*(THREE*q + r)/t - (TEN*n); q *= TEN; r = nr; } else { nr = (TWO*q + r)*l; nn = (q*(SEVEN*k) + TWO + r*l)/(t*l); q *= k; t *= l; l += TWO; k += BigInteger.One; n = nn; r = nr; } } } private static void Main(string[] args) { new Program().CalcPiDigits(); } } }
Produce a language-to-language conversion: from C++ to C#, same semantics.
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) { return f(std::function<B(A)>([w](A x) { return w.o(w)(x); })); }) }; return r.o(r); } typedef std::function<int(int)> Func; typedef std::function<Func(Func)> FuncFunc; FuncFunc almost_fac = [](Func f) { return Func([f](int n) { if (n <= 1) return 1; return n * f(n - 1); }); }; FuncFunc almost_fib = [](Func f) { return Func([f](int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }); }; int main() { auto fib = Y(almost_fib); auto fac = Y(almost_fac); std::cout << "fib(10) = " << fib(10) << std::endl; std::cout << "fac(10) = " << fac(10) << std::endl; return 0; }
using System; static class YCombinator<T, TResult> { private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r); public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x))); } static class Program { static void Main() { var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1)); var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2)); Console.WriteLine(fac(10)); Console.WriteLine(fib(10)); } }
Convert the following code from C# to C++, ensuring the logic remains intact.
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
Produce a language-to-language conversion: from C++ to C#, same semantics.
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
Preserve the algorithm and functionality while converting the code from C++ to C#.
for(int i = 1;i <= 10; i++){ cout << i; if(i % 5 == 0){ cout << endl; continue; } cout << ", "; }
using System; class Program { static void Main(string[] args) { for (int i = 1; i <= 10; i++) { Console.Write(i); if (i % 5 == 0) { Console.WriteLine(); continue; } Console.Write(", "); } } }
Write the same algorithm in C# as shown in this C++ implementation.
#include <algorithm> #include <iostream> #include <vector> #include <string> class pair { public: pair( int s, std::string z ) { p = std::make_pair( s, z ); } bool operator < ( const pair& o ) const { return i() < o.i(); } int i() const { return p.first; } std::string s() const { return p.second; } private: std::pair<int, std::string> p; }; void gFizzBuzz( int c, std::vector<pair>& v ) { bool output; for( int x = 1; x <= c; x++ ) { output = false; for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) { if( !( x % ( *i ).i() ) ) { std::cout << ( *i ).s(); output = true; } } if( !output ) std::cout << x; std::cout << "\n"; } } int main( int argc, char* argv[] ) { std::vector<pair> v; v.push_back( pair( 7, "Baxx" ) ); v.push_back( pair( 3, "Fizz" ) ); v.push_back( pair( 5, "Buzz" ) ); std::sort( v.begin(), v.end() ); gFizzBuzz( 20, v ); return 0; }
using System; public class GeneralFizzBuzz { public static void Main() { int i; int j; int k; int limit; string iString; string jString; string kString; Console.WriteLine("First integer:"); i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("First string:"); iString = Console.ReadLine(); Console.WriteLine("Second integer:"); j = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Second string:"); jString = Console.ReadLine(); Console.WriteLine("Third integer:"); k = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Third string:"); kString = Console.ReadLine(); Console.WriteLine("Limit (inclusive):"); limit = Convert.ToInt32(Console.ReadLine()); for(int n = 1; n<= limit; n++) { bool flag = true; if(n%i == 0) { Console.Write(iString); flag = false; } if(n%j == 0) { Console.Write(jString); flag = false; } if(n%k == 0) { Console.Write(kString); flag = false; } if(flag) Console.Write(n); Console.WriteLine(); } } }
Generate a C# translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <chrono> #include <atomic> #include <mutex> #include <random> #include <thread> std::mutex cout_lock; class Latch { std::atomic<int> semafor; public: Latch(int limit) : semafor(limit) {} void wait() { semafor.fetch_sub(1); while(semafor.load() > 0) std::this_thread::yield(); } }; struct Worker { static void do_work(int how_long, Latch& barrier, std::string name) { std::this_thread::sleep_for(std::chrono::milliseconds(how_long)); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished work\n"; } barrier.wait(); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished assembly\n"; } } }; int main() { Latch latch(5); std::mt19937 rng(std::random_device{}()); std::uniform_int_distribution<> dist(300, 3000); std::thread threads[] { std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"), std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"}, }; for(auto& t: threads) t.join(); std::cout << "Assembly is finished"; }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Rosetta.CheckPointSync; public class Program { public async Task Main() { RobotBuilder robotBuilder = new RobotBuilder(); Task work = robotBuilder.BuildRobots( "Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin", "Bender", "Number Six", "C3-PO", "Dolores"); await work; } public class RobotBuilder { static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" }; static readonly Random rng = new Random(); static readonly object key = new object(); public Task BuildRobots(params string[] robots) { int r = 0; Barrier checkpoint = new Barrier(parts.Length, b => { Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!"); Console.WriteLine(); r++; }); var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray(); return Task.WhenAll(tasks); } private static int GetTime() { lock (key) { return rng.Next(100, 1000); } } private async Task BuildPart(Barrier barrier, string part, string[] robots) { foreach (var robot in robots) { int time = GetTime(); Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms."); await Task.Delay(time); Console.WriteLine($"{part} for {robot} finished."); barrier.SignalAndWait(); } } } }
Rewrite the snippet below in C# so it works the same as the original C++ code.
#include <iomanip> #include <iostream> #include <vector> std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) { auto it = v.cbegin(); auto end = v.cend(); os << "[ "; if (it != end) { os << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } while (it != end) { os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } return os << " ]"; } std::vector<uint8_t> to_seq(uint64_t x) { int i; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) { break; } } std::vector<uint8_t> out; for (int j = 0; j <= i; j++) { out.push_back(((x >> ((i - j) * 7)) & 127) | 128); } out[i] ^= 128; return out; } uint64_t from_seq(const std::vector<uint8_t> &seq) { uint64_t r = 0; for (auto b : seq) { r = (r << 7) | (b & 127); } return r; } int main() { std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL }; for (auto x : src) { auto s = to_seq(x); std::cout << std::hex; std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n'; std::cout << std::dec; } return 0; }
namespace Vlq { using System; using System.Collections.Generic; using System.Linq; public static class VarLenQuantity { public static ulong ToVlq(ulong integer) { var array = new byte[8]; var buffer = ToVlqCollection(integer) .SkipWhile(b => b == 0) .Reverse() .ToArray(); Array.Copy(buffer, array, buffer.Length); return BitConverter.ToUInt64(array, 0); } public static ulong FromVlq(ulong integer) { var collection = BitConverter.GetBytes(integer).Reverse(); return FromVlqCollection(collection); } public static IEnumerable<byte> ToVlqCollection(ulong integer) { if (integer > Math.Pow(2, 56)) throw new OverflowException("Integer exceeds max value."); var index = 7; var significantBitReached = false; var mask = 0x7fUL << (index * 7); while (index >= 0) { var buffer = (mask & integer); if (buffer > 0 || significantBitReached) { significantBitReached = true; buffer >>= index * 7; if (index > 0) buffer |= 0x80; yield return (byte)buffer; } mask >>= 7; index--; } } public static ulong FromVlqCollection(IEnumerable<byte> vlq) { ulong integer = 0; var significantBitReached = false; using (var enumerator = vlq.GetEnumerator()) { int index = 0; while (enumerator.MoveNext()) { var buffer = enumerator.Current; if (buffer > 0 || significantBitReached) { significantBitReached = true; integer <<= 7; integer |= (buffer & 0x7fUL); } if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80)) break; } } return integer; } public static void Main() { var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff }; foreach (var original in integers) { Console.WriteLine("Original: 0x{0:X}", original); var seq = ToVlqCollection(original); Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat)); var decoded = FromVlqCollection(seq); Console.WriteLine("Decoded: 0x{0:X}", decoded); var encoded = ToVlq(original); Console.WriteLine("Encoded: 0x{0:X}", encoded); decoded = FromVlq(encoded); Console.WriteLine("Decoded: 0x{0:X}", decoded); Console.WriteLine(); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
Produce a functionally identical C# code for the snippet given in C++.
#include <algorithm> #include <string> #include <cctype> void str_toupper(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::toupper); } void str_tolower(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::tolower); }
using System; namespace StringCase { class Program { public static void Main() { String input = scope .("alphaBETA"); input.ToUpper(); Console.WriteLine(input); input.ToLower(); Console.WriteLine(input); } } }