Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this Java snippet to Python and keep its semantics consistent.
class MD5 { private static final int INIT_A = 0x67452301; private static final int INIT_B = (int)0xEFCDAB89L; private static final int INIT_C = (int)0x98BADCFEL; private static final int INIT_D = 0x10325476; private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 }; private static final int[] TABLE_T = new int[64]; static { for (int i = 0; i < 64; i++) TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1))); } public static byte[] computeMD5(byte[] message) { int messageLenBytes = message.length; int numBlocks = ((messageLenBytes + 8) >>> 6) + 1; int totalLen = numBlocks << 6; byte[] paddingBytes = new byte[totalLen - messageLenBytes]; paddingBytes[0] = (byte)0x80; long messageLenBits = (long)messageLenBytes << 3; for (int i = 0; i < 8; i++) { paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits; messageLenBits >>>= 8; } int a = INIT_A; int b = INIT_B; int c = INIT_C; int d = INIT_D; int[] buffer = new int[16]; for (int i = 0; i < numBlocks; i ++) { int index = i << 6; for (int j = 0; j < 64; j++, index++) buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8); int originalA = a; int originalB = b; int originalC = c; int originalD = d; for (int j = 0; j < 64; j++) { int div16 = j >>> 4; int f = 0; int bufferIndex = j; switch (div16) { case 0: f = (b & c) | (~b & d); break; case 1: f = (b & d) | (c & ~d); bufferIndex = (bufferIndex * 5 + 1) & 0x0F; break; case 2: f = b ^ c ^ d; bufferIndex = (bufferIndex * 3 + 5) & 0x0F; break; case 3: f = c ^ (b | ~d); bufferIndex = (bufferIndex * 7) & 0x0F; break; } int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]); a = d; d = c; c = b; b = temp; } a += originalA; b += originalB; c += originalC; d += originalD; } byte[] md5 = new byte[16]; int count = 0; for (int i = 0; i < 4; i++) { int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d)); for (int j = 0; j < 4; j++) { md5[count++] = (byte)n; n >>>= 8; } } return md5; } public static String toHexString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { sb.append(String.format("%02X", b[i] & 0xFF)); } return sb.toString(); } public static void main(String[] args) { String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }; for (String s : testStrings) System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\""); return; } }
import math rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)] init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \ 16*[lambda b, c, d: (d & b) | (~d & c)] + \ 16*[lambda b, c, d: b ^ c ^ d] + \ 16*[lambda b, c, d: c ^ (b | ~d)] index_functions = 16*[lambda i: i] + \ 16*[lambda i: (5*i + 1)%16] + \ 16*[lambda i: (3*i + 5)%16] + \ 16*[lambda i: (7*i)%16] def left_rotate(x, amount): x &= 0xFFFFFFFF return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF def md5(message): message = bytearray(message) orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff message.append(0x80) while len(message)%64 != 56: message.append(0) message += orig_len_in_bits.to_bytes(8, byteorder='little') hash_pieces = init_values[:] for chunk_ofst in range(0, len(message), 64): a, b, c, d = hash_pieces chunk = message[chunk_ofst:chunk_ofst+64] for i in range(64): f = functions[i](b, c, d) g = index_functions[i](i) to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little') new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF a, b, c, d = d, new_b, b, c for i, val in enumerate([a, b, c, d]): hash_pieces[i] += val hash_pieces[i] &= 0xFFFFFFFF return sum(x<<(32*i) for i, x in enumerate(hash_pieces)) def md5_to_hex(digest): raw = digest.to_bytes(16, byteorder='little') return '{:032x}'.format(int.from_bytes(raw, byteorder='big')) if __name__=='__main__': demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz", b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"] for message in demo: print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')
Change the following Java code into Python without altering its purpose.
import java.util.Random; public class KMeansWithKpp{ public Point[] points; public Point[] centroids; Random rand; public int n; public int k; private KMeansWithKpp(){ } KMeansWithKpp(Point[] p, int clusters){ points = p; n = p.length; k = Math.max(1, clusters); centroids = new Point[k]; rand = new Random(); } private static double distance(Point a, Point b){ return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } private static int nearest(Point pt, Point[] others, int len){ double minD = Double.MAX_VALUE; int index = pt.group; len = Math.min(others.length, len); double dist; for (int i = 0; i < len; i++) { if (minD > (dist = distance(pt, others[i]))) { minD = dist; index = i; } } return index; } private static double nearestDistance(Point pt, Point[] others, int len){ double minD = Double.MAX_VALUE; len = Math.min(others.length, len); double dist; for (int i = 0; i < len; i++) { if (minD > (dist = distance(pt, others[i]))) { minD = dist; } } return minD; } private void kpp(){ centroids[0] = points[rand.nextInt(n)]; double[] dist = new double[n]; double sum = 0; for (int i = 1; i < k; i++) { for (int j = 0; j < n; j++) { dist[j] = nearestDistance(points[j], centroids, i); sum += dist[j]; } sum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; for (int j = 0; j < n; j++) { if ((sum -= dist[j]) > 0) continue; centroids[i].x = points[j].x; centroids[i].y = points[j].y; } } for (int i = 0; i < n; i++) { points[i].group = nearest(points[i], centroids, k); } } public void kMeans(int maxTimes){ if (k == 1 || n <= 0) { return; } if(k >= n){ for(int i =0; i < n; i++){ points[i].group = i; } return; } maxTimes = Math.max(1, maxTimes); int changed; int bestPercent = n/1000; int minIndex; kpp(); do { for (Point c : centroids) { c.x = 0.0; c.y = 0.0; c.group = 0; } for (Point pt : points) { if(pt.group < 0 || pt.group > centroids.length){ pt.group = rand.nextInt(centroids.length); } centroids[pt.group].x += pt.x; centroids[pt.group].y = pt.y; centroids[pt.group].group++; } for (Point c : centroids) { c.x /= c.group; c.y /= c.group; } changed = 0; for (Point pt : points) { minIndex = nearest(pt, centroids, k); if (k != pt.group) { changed++; pt.group = minIndex; } } maxTimes--; } while (changed > bestPercent && maxTimes > 0); } } class Point{ public double x; public double y; public int group; Point(){ x = y = 0.0; group = 0; } public Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){ if (size <= 0) return null; double xdiff, ydiff; xdiff = maxX - minX; ydiff = maxY - minY; if (minX > maxX) { xdiff = minX - maxX; minX = maxX; } if (maxY < minY) { ydiff = minY - maxY; minY = maxY; } Point[] data = new Point[size]; Random rand = new Random(); for (int i = 0; i < size; i++) { data[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; data[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; } return data; } public Point[] getRandomPolarData(double radius, int size){ if (size <= 0) { return null; } Point[] data = new Point[size]; double radi, arg; Random rand = new Random(); for (int i = 0; i < size; i++) { radi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; arg = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; data[i].x = radi * Math.cos(arg); data[i].y = radi * Math.sin(arg); } return data; } }
from math import pi, sin, cos from collections import namedtuple from random import random, choice from copy import copy try: import psyco psyco.full() except ImportError: pass FLOAT_MAX = 1e100 class Point: __slots__ = ["x", "y", "group"] def __init__(self, x=0.0, y=0.0, group=0): self.x, self.y, self.group = x, y, group def generate_points(npoints, radius): points = [Point() for _ in xrange(npoints)] for p in points: r = random() * radius ang = random() * 2 * pi p.x = r * cos(ang) p.y = r * sin(ang) return points def nearest_cluster_center(point, cluster_centers): def sqr_distance_2D(a, b): return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 min_index = point.group min_dist = FLOAT_MAX for i, cc in enumerate(cluster_centers): d = sqr_distance_2D(cc, point) if min_dist > d: min_dist = d min_index = i return (min_index, min_dist) def kpp(points, cluster_centers): cluster_centers[0] = copy(choice(points)) d = [0.0 for _ in xrange(len(points))] for i in xrange(1, len(cluster_centers)): sum = 0 for j, p in enumerate(points): d[j] = nearest_cluster_center(p, cluster_centers[:i])[1] sum += d[j] sum *= random() for j, di in enumerate(d): sum -= di if sum > 0: continue cluster_centers[i] = copy(points[j]) break for p in points: p.group = nearest_cluster_center(p, cluster_centers)[0] def lloyd(points, nclusters): cluster_centers = [Point() for _ in xrange(nclusters)] kpp(points, cluster_centers) lenpts10 = len(points) >> 10 changed = 0 while True: for cc in cluster_centers: cc.x = 0 cc.y = 0 cc.group = 0 for p in points: cluster_centers[p.group].group += 1 cluster_centers[p.group].x += p.x cluster_centers[p.group].y += p.y for cc in cluster_centers: cc.x /= cc.group cc.y /= cc.group changed = 0 for p in points: min_i = nearest_cluster_center(p, cluster_centers)[0] if min_i != p.group: changed += 1 p.group = min_i if changed <= lenpts10: break for i, cc in enumerate(cluster_centers): cc.group = i return cluster_centers def print_eps(points, cluster_centers, W=400, H=400): Color = namedtuple("Color", "r g b"); colors = [] for i in xrange(len(cluster_centers)): colors.append(Color((3 * (i + 1) % 11) / 11.0, (7 * i % 11) / 11.0, (9 * i % 11) / 11.0)) max_x = max_y = -FLOAT_MAX min_x = min_y = FLOAT_MAX for p in points: if max_x < p.x: max_x = p.x if min_x > p.x: min_x = p.x if max_y < p.y: max_y = p.y if min_y > p.y: min_y = p.y scale = min(W / (max_x - min_x), H / (max_y - min_y)) cx = (max_x + min_x) / 2 cy = (max_y + min_y) / 2 print "%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %d %d" % (W + 10, H + 10) print ("/l {rlineto} def /m {rmoveto} def\n" + "/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n" + "/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath " + " gsave 1 setgray fill grestore gsave 3 setlinewidth" + " 1 setgray stroke grestore 0 setgray stroke }def") for i, cc in enumerate(cluster_centers): print ("%g %g %g setrgbcolor" % (colors[i].r, colors[i].g, colors[i].b)) for p in points: if p.group != i: continue print ("%.3f %.3f c" % ((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2)) print ("\n0 setgray %g %g s" % ((cc.x - cx) * scale + W / 2, (cc.y - cy) * scale + H / 2)) print "\n%%%%EOF" def main(): npoints = 30000 k = 7 points = generate_points(npoints, 10) cluster_centers = lloyd(points, k) print_eps(points, cluster_centers) main()
Please provide an equivalent version of this Java code in Python.
import java.util.Random; public class KMeansWithKpp{ public Point[] points; public Point[] centroids; Random rand; public int n; public int k; private KMeansWithKpp(){ } KMeansWithKpp(Point[] p, int clusters){ points = p; n = p.length; k = Math.max(1, clusters); centroids = new Point[k]; rand = new Random(); } private static double distance(Point a, Point b){ return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); } private static int nearest(Point pt, Point[] others, int len){ double minD = Double.MAX_VALUE; int index = pt.group; len = Math.min(others.length, len); double dist; for (int i = 0; i < len; i++) { if (minD > (dist = distance(pt, others[i]))) { minD = dist; index = i; } } return index; } private static double nearestDistance(Point pt, Point[] others, int len){ double minD = Double.MAX_VALUE; len = Math.min(others.length, len); double dist; for (int i = 0; i < len; i++) { if (minD > (dist = distance(pt, others[i]))) { minD = dist; } } return minD; } private void kpp(){ centroids[0] = points[rand.nextInt(n)]; double[] dist = new double[n]; double sum = 0; for (int i = 1; i < k; i++) { for (int j = 0; j < n; j++) { dist[j] = nearestDistance(points[j], centroids, i); sum += dist[j]; } sum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; for (int j = 0; j < n; j++) { if ((sum -= dist[j]) > 0) continue; centroids[i].x = points[j].x; centroids[i].y = points[j].y; } } for (int i = 0; i < n; i++) { points[i].group = nearest(points[i], centroids, k); } } public void kMeans(int maxTimes){ if (k == 1 || n <= 0) { return; } if(k >= n){ for(int i =0; i < n; i++){ points[i].group = i; } return; } maxTimes = Math.max(1, maxTimes); int changed; int bestPercent = n/1000; int minIndex; kpp(); do { for (Point c : centroids) { c.x = 0.0; c.y = 0.0; c.group = 0; } for (Point pt : points) { if(pt.group < 0 || pt.group > centroids.length){ pt.group = rand.nextInt(centroids.length); } centroids[pt.group].x += pt.x; centroids[pt.group].y = pt.y; centroids[pt.group].group++; } for (Point c : centroids) { c.x /= c.group; c.y /= c.group; } changed = 0; for (Point pt : points) { minIndex = nearest(pt, centroids, k); if (k != pt.group) { changed++; pt.group = minIndex; } } maxTimes--; } while (changed > bestPercent && maxTimes > 0); } } class Point{ public double x; public double y; public int group; Point(){ x = y = 0.0; group = 0; } public Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){ if (size <= 0) return null; double xdiff, ydiff; xdiff = maxX - minX; ydiff = maxY - minY; if (minX > maxX) { xdiff = minX - maxX; minX = maxX; } if (maxY < minY) { ydiff = minY - maxY; minY = maxY; } Point[] data = new Point[size]; Random rand = new Random(); for (int i = 0; i < size; i++) { data[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; data[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; } return data; } public Point[] getRandomPolarData(double radius, int size){ if (size <= 0) { return null; } Point[] data = new Point[size]; double radi, arg; Random rand = new Random(); for (int i = 0; i < size; i++) { radi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; arg = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE; data[i].x = radi * Math.cos(arg); data[i].y = radi * Math.sin(arg); } return data; } }
from math import pi, sin, cos from collections import namedtuple from random import random, choice from copy import copy try: import psyco psyco.full() except ImportError: pass FLOAT_MAX = 1e100 class Point: __slots__ = ["x", "y", "group"] def __init__(self, x=0.0, y=0.0, group=0): self.x, self.y, self.group = x, y, group def generate_points(npoints, radius): points = [Point() for _ in xrange(npoints)] for p in points: r = random() * radius ang = random() * 2 * pi p.x = r * cos(ang) p.y = r * sin(ang) return points def nearest_cluster_center(point, cluster_centers): def sqr_distance_2D(a, b): return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 min_index = point.group min_dist = FLOAT_MAX for i, cc in enumerate(cluster_centers): d = sqr_distance_2D(cc, point) if min_dist > d: min_dist = d min_index = i return (min_index, min_dist) def kpp(points, cluster_centers): cluster_centers[0] = copy(choice(points)) d = [0.0 for _ in xrange(len(points))] for i in xrange(1, len(cluster_centers)): sum = 0 for j, p in enumerate(points): d[j] = nearest_cluster_center(p, cluster_centers[:i])[1] sum += d[j] sum *= random() for j, di in enumerate(d): sum -= di if sum > 0: continue cluster_centers[i] = copy(points[j]) break for p in points: p.group = nearest_cluster_center(p, cluster_centers)[0] def lloyd(points, nclusters): cluster_centers = [Point() for _ in xrange(nclusters)] kpp(points, cluster_centers) lenpts10 = len(points) >> 10 changed = 0 while True: for cc in cluster_centers: cc.x = 0 cc.y = 0 cc.group = 0 for p in points: cluster_centers[p.group].group += 1 cluster_centers[p.group].x += p.x cluster_centers[p.group].y += p.y for cc in cluster_centers: cc.x /= cc.group cc.y /= cc.group changed = 0 for p in points: min_i = nearest_cluster_center(p, cluster_centers)[0] if min_i != p.group: changed += 1 p.group = min_i if changed <= lenpts10: break for i, cc in enumerate(cluster_centers): cc.group = i return cluster_centers def print_eps(points, cluster_centers, W=400, H=400): Color = namedtuple("Color", "r g b"); colors = [] for i in xrange(len(cluster_centers)): colors.append(Color((3 * (i + 1) % 11) / 11.0, (7 * i % 11) / 11.0, (9 * i % 11) / 11.0)) max_x = max_y = -FLOAT_MAX min_x = min_y = FLOAT_MAX for p in points: if max_x < p.x: max_x = p.x if min_x > p.x: min_x = p.x if max_y < p.y: max_y = p.y if min_y > p.y: min_y = p.y scale = min(W / (max_x - min_x), H / (max_y - min_y)) cx = (max_x + min_x) / 2 cy = (max_y + min_y) / 2 print "%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %d %d" % (W + 10, H + 10) print ("/l {rlineto} def /m {rmoveto} def\n" + "/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n" + "/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath " + " gsave 1 setgray fill grestore gsave 3 setlinewidth" + " 1 setgray stroke grestore 0 setgray stroke }def") for i, cc in enumerate(cluster_centers): print ("%g %g %g setrgbcolor" % (colors[i].r, colors[i].g, colors[i].b)) for p in points: if p.group != i: continue print ("%.3f %.3f c" % ((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2)) print ("\n0 setgray %g %g s" % ((cc.x - cx) * scale + W / 2, (cc.y - cy) * scale + H / 2)) print "\n%%%%EOF" def main(): npoints = 30000 k = 7 points = generate_points(npoints, 10) cluster_centers = lloyd(points, k) print_eps(points, cluster_centers) main()
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.io.*; import java.util.*; public class MazeSolver { private static String[] readLines (InputStream f) throws IOException { BufferedReader r = new BufferedReader (new InputStreamReader (f, "US-ASCII")); ArrayList<String> lines = new ArrayList<String>(); String line; while ((line = r.readLine()) != null) lines.add (line); return lines.toArray(new String[0]); } private static char[][] decimateHorizontally (String[] lines) { final int width = (lines[0].length() + 1) / 2; char[][] c = new char[lines.length][width]; for (int i = 0 ; i < lines.length ; i++) for (int j = 0 ; j < width ; j++) c[i][j] = lines[i].charAt (j * 2); return c; } private static boolean solveMazeRecursively (char[][] maze, int x, int y, int d) { boolean ok = false; for (int i = 0 ; i < 4 && !ok ; i++) if (i != d) switch (i) { case 0: if (maze[y-1][x] == ' ') ok = solveMazeRecursively (maze, x, y - 2, 2); break; case 1: if (maze[y][x+1] == ' ') ok = solveMazeRecursively (maze, x + 2, y, 3); break; case 2: if (maze[y+1][x] == ' ') ok = solveMazeRecursively (maze, x, y + 2, 0); break; case 3: if (maze[y][x-1] == ' ') ok = solveMazeRecursively (maze, x - 2, y, 1); break; } if (x == 1 && y == 1) ok = true; if (ok) { maze[y][x] = '*'; switch (d) { case 0: maze[y-1][x] = '*'; break; case 1: maze[y][x+1] = '*'; break; case 2: maze[y+1][x] = '*'; break; case 3: maze[y][x-1] = '*'; break; } } return ok; } private static void solveMaze (char[][] maze) { solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1); } private static String[] expandHorizontally (char[][] maze) { char[] tmp = new char[3]; String[] lines = new String[maze.length]; for (int i = 0 ; i < maze.length ; i++) { StringBuilder sb = new StringBuilder(maze[i].length * 2); for (int j = 0 ; j < maze[i].length ; j++) if (j % 2 == 0) sb.append (maze[i][j]); else { tmp[0] = tmp[1] = tmp[2] = maze[i][j]; if (tmp[1] == '*') tmp[0] = tmp[2] = ' '; sb.append (tmp); } lines[i] = sb.toString(); } return lines; } public static void main (String[] args) throws IOException { InputStream f = (args.length > 0 ? new FileInputStream (args[0]) : System.in); String[] lines = readLines (f); char[][] maze = decimateHorizontally (lines); solveMaze (maze); String[] solvedLines = expandHorizontally (maze); for (int i = 0 ; i < solvedLines.length ; i++) System.out.println (solvedLines[i]); } }
def Dijkstra(Graph, source): infinity = float('infinity') n = len(graph) dist = [infinity]*n previous = [infinity]*n dist[source] = 0 Q = list(range(n)) while Q: u = min(Q, key=lambda n:dist[n]) Q.remove(u) if dist[u] == infinity: break for v in range(n): if Graph[u][v] and (v in Q): alt = dist[u] + Graph[u][v] if alt < dist[v]: dist[v] = alt previous[v] = u return dist,previous def display_solution(predecessor): cell = len(predecessor)-1 while cell: print(cell,end='<') cell = predecessor[cell] print(0)
Can you help me rewrite this code in Python instead of Java, keeping it the same logically?
import java.util.*; public class RandomShuffle { public static void main(String[] args) { Random rand = new Random(); List<Integer> list = new ArrayList<>(); for (int j = 1; j <= 20; ++j) list.add(j); Collections.shuffle(list, rand); System.out.println(list); } }
import random print(random.sample(range(1, 21), 20))
Generate an equivalent Python version of this Java code.
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; public class IQPuzzle { public static void main(String[] args) { System.out.printf(" "); for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) { System.out.printf("  %,6d", start); } System.out.printf("%n"); for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) { System.out.printf("%2d", start); Map<Integer,Integer> solutions = solve(start); for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) { System.out.printf("  %,6d", solutions.containsKey(end) ? solutions.get(end) : 0); } System.out.printf("%n"); } int moveNum = 0; System.out.printf("%nOne Solution:%n"); for ( Move m : oneSolution ) { moveNum++; System.out.printf("Move %d = %s%n", moveNum, m); } } private static List<Move> oneSolution = null; private static Map<Integer, Integer> solve(int emptyPeg) { Puzzle puzzle = new Puzzle(emptyPeg); Map<Integer,Integer> solutions = new HashMap<>(); Stack<Puzzle> stack = new Stack<Puzzle>(); stack.push(puzzle); while ( ! stack.isEmpty() ) { Puzzle p = stack.pop(); if ( p.solved() ) { solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2); if ( oneSolution == null ) { oneSolution = p.moves; } continue; } for ( Move move : p.getValidMoves() ) { Puzzle pMove = p.move(move); stack.add(pMove); } } return solutions; } private static class Puzzle { public static int MAX_PEGS = 16; private boolean[] pegs = new boolean[MAX_PEGS]; private List<Move> moves; public Puzzle(int emptyPeg) { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { pegs[i] = true; } pegs[emptyPeg] = false; moves = new ArrayList<>(); } public Puzzle() { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { pegs[i] = true; } moves = new ArrayList<>(); } private static Map<Integer,List<Move>> validMoves = new HashMap<>(); static { validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6))); validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9))); validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10))); validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11))); validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14))); validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15))); validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9))); validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10))); validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7))); validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8))); validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13))); validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14))); validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15))); validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5))); validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6))); } public List<Move> getValidMoves() { List<Move> moves = new ArrayList<Move>(); for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { for ( Move testMove : validMoves.get(i) ) { if ( pegs[testMove.jump] && ! pegs[testMove.end] ) { moves.add(testMove); } } } } return moves; } public boolean solved() { boolean foundFirstPeg = false; for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { if ( foundFirstPeg ) { return false; } foundFirstPeg = true; } } return true; } public Puzzle move(Move move) { Puzzle p = new Puzzle(); if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) { throw new RuntimeException("Invalid move."); } for ( int i = 1 ; i < MAX_PEGS ; i++ ) { p.pegs[i] = pegs[i]; } p.pegs[move.start] = false; p.pegs[move.jump] = false; p.pegs[move.end] = true; for ( Move m : moves ) { p.moves.add(new Move(m.start, m.jump, m.end)); } p.moves.add(new Move(move.start, move.jump, move.end)); return p; } public int getLastPeg() { for ( int i = 1 ; i < MAX_PEGS ; i++ ) { if ( pegs[i] ) { return i; } } throw new RuntimeException("ERROR: Illegal position."); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for ( int i = 1 ; i < MAX_PEGS ; i++ ) { sb.append(pegs[i] ? 1 : 0); sb.append(","); } sb.setLength(sb.length()-1); sb.append("]"); return sb.toString(); } } private static class Move { int start; int jump; int end; public Move(int s, int j, int e) { start = s; jump = j; end = e; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("s=" + start); sb.append(", j=" + jump); sb.append(", e=" + end); sb.append("}"); return sb.toString(); } } }
def DrawBoard(board): peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for n in xrange(1,16): peg[n] = '.' if n in board: peg[n] = "%X" % n print " %s" % peg[1] print " %s %s" % (peg[2],peg[3]) print " %s %s %s" % (peg[4],peg[5],peg[6]) print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10]) print " %s %s %s %s %s" % (peg[11],peg[12],peg[13],peg[14],peg[15]) def RemovePeg(board,n): board.remove(n) def AddPeg(board,n): board.append(n) def IsPeg(board,n): return n in board JumpMoves = { 1: [ (2,4),(3,6) ], 2: [ (4,7),(5,9) ], 3: [ (5,8),(6,10) ], 4: [ (2,1),(5,6),(7,11),(8,13) ], 5: [ (8,12),(9,14) ], 6: [ (3,1),(5,4),(9,13),(10,15) ], 7: [ (4,2),(8,9) ], 8: [ (5,3),(9,10) ], 9: [ (5,2),(8,7) ], 10: [ (9,8) ], 11: [ (12,13) ], 12: [ (8,5),(13,14) ], 13: [ (8,4),(9,6),(12,11),(14,15) ], 14: [ (9,5),(13,12) ], 15: [ (10,6),(14,13) ] } Solution = [] def Solve(board): if len(board) == 1: return board for peg in xrange(1,16): if IsPeg(board,peg): movelist = JumpMoves[peg] for over,land in movelist: if IsPeg(board,over) and not IsPeg(board,land): saveboard = board[:] RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) Solution.append((peg,over,land)) board = Solve(board) if len(board) == 1: return board board = saveboard[:] del Solution[-1] return board def InitSolve(empty): board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) Solve(board) empty_start = 1 InitSolve(empty_start) board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) for peg,over,land in Solution: RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) DrawBoard(board) print "Peg %X jumped over %X to land on %X\n" % (peg,over,land)
Generate an equivalent Python version of this Java code.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { private static List<List<Integer>> fourFaceCombos() { List<List<Integer>> res = new ArrayList<>(); Set<Integer> found = new HashSet<>(); for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { for (int k = 1; k <= 4; k++) { for (int l = 1; l <= 4; l++) { List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList()); int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1); if (found.add(key)) { res.add(c); } } } } } return res; } private static int cmp(List<Integer> x, List<Integer> y) { int xw = 0; int yw = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x.get(i) > y.get(j)) { xw++; } else if (x.get(i) < y.get(j)) { yw++; } } } return Integer.compare(xw, yw); } private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) { int c = cs.size(); List<List<List<Integer>>> res = new ArrayList<>(); for (int i = 0; i < c; i++) { for (int j = 0; j < c; j++) { if (cmp(cs.get(i), cs.get(j)) == -1) { for (List<Integer> kl : cs) { if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) { res.add(List.of(cs.get(i), cs.get(j), kl)); } } } } } return res; } private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) { int c = cs.size(); List<List<List<Integer>>> res = new ArrayList<>(); for (int i = 0; i < c; i++) { for (int j = 0; j < c; j++) { if (cmp(cs.get(i), cs.get(j)) == -1) { for (int k = 0; k < cs.size(); k++) { if (cmp(cs.get(j), cs.get(k)) == -1) { for (List<Integer> ll : cs) { if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) { res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll)); } } } } } } } return res; } public static void main(String[] args) { List<List<Integer>> combos = fourFaceCombos(); System.out.printf("Number of eligible 4-faced dice: %d%n", combos.size()); System.out.println(); List<List<List<Integer>>> it3 = findIntransitive3(combos); System.out.printf("%d ordered lists of 3 non-transitive dice found, namely:%n", it3.size()); for (List<List<Integer>> a : it3) { System.out.println(a); } System.out.println(); List<List<List<Integer>>> it4 = findIntransitive4(combos); System.out.printf("%d ordered lists of 4 non-transitive dice found, namely:%n", it4.size()); for (List<List<Integer>> a : it4) { System.out.println(a); } } }
from itertools import combinations_with_replacement as cmbr from time import time def dice_gen(n, faces, m): dice = list(cmbr(faces, n)) succ = [set(j for j, b in enumerate(dice) if sum((x>y) - (x<y) for x in a for y in b) > 0) for a in dice] def loops(seq): s = succ[seq[-1]] if len(seq) == m: if seq[0] in s: yield seq return for d in (x for x in s if x > seq[0] and not x in seq): yield from loops(seq + (d,)) yield from (tuple(''.join(dice[s]) for s in x) for i, v in enumerate(succ) for x in loops((i,))) t = time() for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]: for i, x in enumerate(dice_gen(n, faces, loop_len)): pass print(f'{n}-sided, markings {faces}, loop length {loop_len}:') print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]') t, t0 = time(), t print(f'\ttime: {t - t0:.4f} seconds\n')
Preserve the algorithm and functionality while converting the code from Java to Python.
public class HistoryVariable { private Object value; public HistoryVariable(Object v) { value = v; } public void update(Object v) { value = v; } public Object undo() { return value; } @Override public String toString() { return value.toString(); } public void dispose() { } }
import sys HIST = {} def trace(frame, event, arg): for name,val in frame.f_locals.items(): if name not in HIST: HIST[name] = [] else: if HIST[name][-1] is val: continue HIST[name].append(val) return trace def undo(name): HIST[name].pop(-1) return HIST[name][-1] def main(): a = 10 a = 20 for i in range(5): c = i print "c:", c, "-> undo x3 ->", c = undo('c') c = undo('c') c = undo('c') print c print 'HIST:', HIST sys.settrace(trace) main()
Write the same algorithm in Python as shown in this Java implementation.
import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class Perceptron extends JPanel { class Trainer { double[] inputs; int answer; Trainer(double x, double y, int a) { inputs = new double[]{x, y, 1}; answer = a; } } Trainer[] training = new Trainer[2000]; double[] weights; double c = 0.00001; int count; public Perceptron(int n) { Random r = new Random(); Dimension dim = new Dimension(640, 360); setPreferredSize(dim); setBackground(Color.white); weights = new double[n]; for (int i = 0; i < weights.length; i++) { weights[i] = r.nextDouble() * 2 - 1; } for (int i = 0; i < training.length; i++) { double x = r.nextDouble() * dim.width; double y = r.nextDouble() * dim.height; int answer = y < f(x) ? -1 : 1; training[i] = new Trainer(x, y, answer); } new Timer(10, (ActionEvent e) -> { repaint(); }).start(); } private double f(double x) { return x * 0.7 + 40; } int feedForward(double[] inputs) { assert inputs.length == weights.length : "weights and input length mismatch"; double sum = 0; for (int i = 0; i < weights.length; i++) { sum += inputs[i] * weights[i]; } return activate(sum); } int activate(double s) { return s > 0 ? 1 : -1; } void train(double[] inputs, int desired) { int guess = feedForward(inputs); double error = desired - guess; for (int i = 0; i < weights.length; i++) { weights[i] += c * error * inputs[i]; } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int x = getWidth(); int y = (int) f(x); g.setStroke(new BasicStroke(2)); g.setColor(Color.orange); g.drawLine(0, (int) f(0), x, y); train(training[count].inputs, training[count].answer); count = (count + 1) % training.length; g.setStroke(new BasicStroke(1)); g.setColor(Color.black); for (int i = 0; i < count; i++) { int guess = feedForward(training[i].inputs); x = (int) training[i].inputs[0] - 4; y = (int) training[i].inputs[1] - 4; if (guess > 0) g.drawOval(x, y, 8, 8); else g.fillOval(x, y, 8, 8); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Perceptron"); f.setResizable(false); f.add(new Perceptron(3), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
import random TRAINING_LENGTH = 2000 class Perceptron: def __init__(self,n): self.c = .01 self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)] def feed_forward(self, inputs): vars = [] for i in range(len(inputs)): vars.append(inputs[i] * self.weights[i]) return self.activate(sum(vars)) def activate(self, value): return 1 if value > 0 else -1 def train(self, inputs, desired): guess = self.feed_forward(inputs) error = desired - guess for i in range(len(inputs)): self.weights[i] += self.c * error * inputs[i] class Trainer(): def __init__(self, x, y, a): self.inputs = [x, y, 1] self.answer = a def F(x): return 2 * x + 1 if __name__ == "__main__": ptron = Perceptron(3) training = [] for i in range(TRAINING_LENGTH): x = random.uniform(-10,10) y = random.uniform(-10,10) answer = 1 if y < F(x): answer = -1 training.append(Trainer(x,y,answer)) result = [] for y in range(-10,10): temp = [] for x in range(-10,10): if ptron.feed_forward([x,y,1]) == 1: temp.append('^') else: temp.append('.') result.append(temp) print('Untrained') for row in result: print(''.join(v for v in row)) for t in training: ptron.train(t.inputs, t.answer) result = [] for y in range(-10,10): temp = [] for x in range(-10,10): if ptron.feed_forward([x,y,1]) == 1: temp.append('^') else: temp.append('.') result.append(temp) print('Trained') for row in result: print(''.join(v for v in row))
Convert the following code from Java to Python, ensuring the logic remains intact.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; public class Evaluator{ public static void main(String[] args){ new Evaluator().eval( "SayHello", "public class SayHello{public void speak(){System.out.println(\"Hello world\");}}", "speak" ); } void eval(String className, String classCode, String methodName){ Map<String, ByteArrayOutputStream> classCache = new HashMap<>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if ( null == compiler ) throw new RuntimeException("Could not get a compiler."); StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null); ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){ @Override public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException{ if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind) return new SimpleJavaFileObject(URI.create("mem: @Override public OutputStream openOutputStream() throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); classCache.put(className, baos); return baos; } }; else throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind); } }; List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{ add( new SimpleJavaFileObject(URI.create("string: @Override public CharSequence getCharContent(boolean ignoreEncodingErrors){ return classCode; } } ); }}; compiler.getTask(null, fjfm, null, null, null, files).call(); try{ Class<?> clarse = new ClassLoader(){ @Override public Class<?> findClass(String name){ if (! name.startsWith(className)) throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"'); byte[] bytes = classCache.get(name).toByteArray(); return defineClass(name, bytes, 0, bytes.length); } }.loadClass(className); clarse.getMethod(methodName).invoke(clarse.newInstance()); }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){ throw new RuntimeException("Run failed: " + x, x); } } }
>>> exec 10
Write the same code in Python as shown below in Java.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; public class Evaluator{ public static void main(String[] args){ new Evaluator().eval( "SayHello", "public class SayHello{public void speak(){System.out.println(\"Hello world\");}}", "speak" ); } void eval(String className, String classCode, String methodName){ Map<String, ByteArrayOutputStream> classCache = new HashMap<>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if ( null == compiler ) throw new RuntimeException("Could not get a compiler."); StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null); ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){ @Override public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException{ if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind) return new SimpleJavaFileObject(URI.create("mem: @Override public OutputStream openOutputStream() throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); classCache.put(className, baos); return baos; } }; else throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind); } }; List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{ add( new SimpleJavaFileObject(URI.create("string: @Override public CharSequence getCharContent(boolean ignoreEncodingErrors){ return classCode; } } ); }}; compiler.getTask(null, fjfm, null, null, null, files).call(); try{ Class<?> clarse = new ClassLoader(){ @Override public Class<?> findClass(String name){ if (! name.startsWith(className)) throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"'); byte[] bytes = classCache.get(name).toByteArray(); return defineClass(name, bytes, 0, bytes.length); } }.loadClass(className); clarse.getMethod(methodName).invoke(clarse.newInstance()); }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){ throw new RuntimeException("Run failed: " + x, x); } } }
>>> exec 10
Preserve the algorithm and functionality while converting the code from Java to Python.
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class PisanoPeriod { public static void main(String[] args) { System.out.printf("Print pisano(p^2) for every prime p lower than 15%n"); for ( long i = 2 ; i < 15 ; i++ ) { if ( isPrime(i) ) { long n = i*i; System.out.printf("pisano(%d) = %d%n", n, pisano(n)); } } System.out.printf("%nPrint pisano(p) for every prime p lower than 180%n"); for ( long n = 2 ; n < 180 ; n++ ) { if ( isPrime(n) ) { System.out.printf("pisano(%d) = %d%n", n, pisano(n)); } } System.out.printf("%nPrint pisano(n) for every integer from 1 to 180%n"); for ( long n = 1 ; n <= 180 ; n++ ) { System.out.printf("%3d ", pisano(n)); if ( n % 10 == 0 ) { System.out.printf("%n"); } } } private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) { return false; } for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static Map<Long,Long> PERIOD_MEMO = new HashMap<>(); static { PERIOD_MEMO.put(2L, 3L); PERIOD_MEMO.put(3L, 8L); PERIOD_MEMO.put(5L, 20L); } private static long pisano(long n) { if ( PERIOD_MEMO.containsKey(n) ) { return PERIOD_MEMO.get(n); } if ( n == 1 ) { return 1; } Map<Long,Long> factors = getFactors(n); if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) { long result = 3 * n / 2; PERIOD_MEMO.put(n, result); return result; } if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) { long result = 4*n; PERIOD_MEMO.put(n, result); return result; } if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) { long result = 6*n; PERIOD_MEMO.put(n, result); return result; } List<Long> primes = new ArrayList<>(factors.keySet()); long prime = primes.get(0); if ( factors.size() == 1 && factors.get(prime) == 1 ) { List<Long> divisors = new ArrayList<>(); if ( n % 10 == 1 || n % 10 == 9 ) { for ( long divisor : getDivisors(prime-1) ) { if ( divisor % 2 == 0 ) { divisors.add(divisor); } } } else { List<Long> pPlus1Divisors = getDivisors(prime+1); for ( long divisor : getDivisors(2*prime+2) ) { if ( ! pPlus1Divisors.contains(divisor) ) { divisors.add(divisor); } } } Collections.sort(divisors); for ( long divisor : divisors ) { if ( fibModIdentity(divisor, prime) ) { PERIOD_MEMO.put(prime, divisor); return divisor; } } throw new RuntimeException("ERROR 144: Divisor not found."); } long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime); for ( int i = 1 ; i < primes.size() ; i++ ) { prime = primes.get(i); period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime)); } PERIOD_MEMO.put(n, period); return period; } private static boolean fibModIdentity(long n, long mod) { long aRes = 0; long bRes = 1; long cRes = 1; long aBase = 0; long bBase = 1; long cBase = 1; while ( n > 0 ) { if ( n % 2 == 1 ) { long temp1 = 0, temp2 = 0, temp3 = 0; if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) { temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod; temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod; temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod; } else { temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod; temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod; temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod; } aRes = temp1; bRes = temp2; cRes = temp3; } n >>= 1L; long temp1 = 0, temp2 = 0, temp3 = 0; if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) { temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod; temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod; temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod; } else { temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod; temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod; temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod; } aBase = temp1; bBase = temp2; cBase = temp3; } return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } private static final List<Long> getDivisors(long number) { List<Long> divisors = new ArrayList<>(); long sqrt = (long) Math.sqrt(number); for ( long i = 1 ; i <= sqrt ; i++ ) { if ( number % i == 0 ) { divisors.add(i); long div = number / i; if ( div != i ) { divisors.add(div); } } } return divisors; } public static long lcm(long a, long b) { return a*b/gcd(a,b); } public static long gcd(long a, long b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } private static final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>(); static { Map<Long,Long> factors = new TreeMap<Long,Long>(); factors.put(2L, 1L); allFactors.put(2L, factors); } public static Long MAX_ALL_FACTORS = 100000L; public static final Map<Long,Long> getFactors(Long number) { if ( allFactors.containsKey(number) ) { return allFactors.get(number); } Map<Long,Long> factors = new TreeMap<Long,Long>(); if ( number % 2 == 0 ) { Map<Long,Long> factorsdDivTwo = getFactors(number/2); factors.putAll(factorsdDivTwo); factors.merge(2L, 1L, (v1, v2) -> v1 + v2); if ( number < MAX_ALL_FACTORS ) { allFactors.put(number, factors); } return factors; } boolean prime = true; long sqrt = (long) Math.sqrt(number); for ( long i = 3 ; i <= sqrt ; i += 2 ) { if ( number % i == 0 ) { prime = false; factors.putAll(getFactors(number/i)); factors.merge(i, 1L, (v1, v2) -> v1 + v2); if ( number < MAX_ALL_FACTORS ) { allFactors.put(number, factors); } return factors; } } if ( prime ) { factors.put(number, 1L); if ( number < MAX_ALL_FACTORS ) { allFactors.put(number, factors); } } return factors; } }
from sympy import isprime, lcm, factorint, primerange from functools import reduce def pisano1(m): "Simple definition" if m < 2: return 1 lastn, n = 0, 1 for i in range(m ** 2): lastn, n = n, (lastn + n) % m if lastn == 0 and n == 1: return i + 1 return 1 def pisanoprime(p, k): "Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1" assert isprime(p) and k > 0 return p ** (k - 1) * pisano1(p) def pisano_mult(m, n): "pisano(m*n) where m and n assumed coprime integers" return lcm(pisano1(m), pisano1(n)) def pisano2(m): "Uses prime factorization of m" return reduce(lcm, (pisanoprime(prime, mult) for prime, mult in factorint(m).items()), 1) if __name__ == '__main__': for n in range(1, 181): assert pisano1(n) == pisano2(n), "Wall-Sun-Sun prime exists??!!" print("\nPisano period (p, 2) for primes less than 50\n ", [pisanoprime(prime, 2) for prime in primerange(1, 50)]) print("\nPisano period (p, 1) for primes less than 180\n ", [pisanoprime(prime, 1) for prime in primerange(1, 180)]) print("\nPisano period (p) for integers 1 to 180") for i in range(1, 181): print(" %3d" % pisano2(i), end="" if i % 10 else "\n")
Rewrite this program in Python while keeping its functionality equivalent to the Java version.
package railwaycircuit; import static java.util.Arrays.stream; import java.util.*; import static java.util.stream.IntStream.range; public class RailwayCircuit { final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0; static String normalize(int[] tracks) { char[] a = new char[tracks.length]; for (int i = 0; i < a.length; i++) a[i] = "abc".charAt(tracks[i] + 1); String norm = new String(a); for (int i = 0, len = a.length; i < len; i++) { String s = new String(a); if (s.compareTo(norm) < 0) norm = s; char tmp = a[0]; for (int j = 1; j < a.length; j++) a[j - 1] = a[j]; a[len - 1] = tmp; } return norm; } static boolean fullCircleStraight(int[] tracks, int nStraight) { if (nStraight == 0) return true; if (stream(tracks).filter(i -> i == STRAIGHT).count() != nStraight) return false; int[] straight = new int[12]; for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) { if (tracks[i] == STRAIGHT) straight[idx % 12]++; idx += tracks[i]; } return !(range(0, 6).anyMatch(i -> straight[i] != straight[i + 6]) && range(0, 8).anyMatch(i -> straight[i] != straight[i + 4])); } static boolean fullCircleRight(int[] tracks) { if (stream(tracks).map(i -> i * 30).sum() % 360 != 0) return false; int[] rTurns = new int[12]; for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) { if (tracks[i] == RIGHT) rTurns[idx % 12]++; idx += tracks[i]; } return !(range(0, 6).anyMatch(i -> rTurns[i] != rTurns[i + 6]) && range(0, 8).anyMatch(i -> rTurns[i] != rTurns[i + 4])); } static void circuits(int nCurved, int nStraight) { Map<String, int[]> solutions = new HashMap<>(); PermutationsGen gen = getPermutationsGen(nCurved, nStraight); while (gen.hasNext()) { int[] tracks = gen.next(); if (!fullCircleStraight(tracks, nStraight)) continue; if (!fullCircleRight(tracks)) continue; solutions.put(normalize(tracks), tracks.clone()); } report(solutions, nCurved, nStraight); } static PermutationsGen getPermutationsGen(int nCurved, int nStraight) { assert (nCurved + nStraight - 12) % 4 == 0 : "input must be 12 + k * 4"; int[] trackTypes = new int[]{RIGHT, LEFT}; if (nStraight != 0) { if (nCurved == 12) trackTypes = new int[]{RIGHT, STRAIGHT}; else trackTypes = new int[]{RIGHT, LEFT, STRAIGHT}; } return new PermutationsGen(nCurved + nStraight, trackTypes); } static void report(Map<String, int[]> sol, int numC, int numS) { int size = sol.size(); System.out.printf("%n%d solution(s) for C%d,%d %n", size, numC, numS); if (size < 10) sol.values().stream().forEach(tracks -> { stream(tracks).forEach(i -> System.out.printf("%2d ", i)); System.out.println(); }); } public static void main(String[] args) { circuits(12, 0); circuits(16, 0); circuits(20, 0); circuits(24, 0); circuits(12, 4); } } class PermutationsGen { private int[] indices; private int[] choices; private int[] sequence; private int carry; PermutationsGen(int numPositions, int[] choices) { indices = new int[numPositions]; sequence = new int[numPositions]; this.choices = choices; } int[] next() { carry = 1; for (int i = 1; i < indices.length && carry > 0; i++) { indices[i] += carry; carry = 0; if (indices[i] == choices.length) { carry = 1; indices[i] = 0; } } for (int i = 0; i < indices.length; i++) sequence[i] = choices[indices[i]]; return sequence; } boolean hasNext() { return carry != 1; } }
from itertools import count, islice import numpy as np from numpy import sin, cos, pi ANGDIV = 12 ANG = 2*pi/ANGDIV def draw_all(sols): import matplotlib.pyplot as plt def draw_track(ax, s): turn, xend, yend = 0, [0], [0] for d in s: x0, y0 = xend[-1], yend[-1] a = turn*ANG cs, sn = cos(a), sin(a) ang = a + d*pi/2 cx, cy = x0 + cos(ang), y0 + sin(ang) da = np.linspace(ang, ang + d*ANG, 10) xs = cx - cos(da) ys = cy - sin(da) ax.plot(xs, ys, 'green' if d == -1 else 'orange') xend.append(xs[-1]) yend.append(ys[-1]) turn += d ax.plot(xend, yend, 'k.', markersize=1) ax.set_aspect(1) ls = len(sols) if ls == 0: return w, h = min((abs(w*2 - h*3) + w*h - ls, w, h) for w, h in ((w, (ls + w - 1)//w) for w in range(1, ls + 1)))[1:] fig, ax = plt.subplots(h, w, squeeze=False) for a in ax.ravel(): a.set_axis_off() for i, s in enumerate(sols): draw_track(ax[i//w, i%w], s) plt.show() def match_up(this, that, equal_lr, seen): if not this or not that: return n = len(this[0][-1]) n2 = n*2 l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0 def record(m): for _ in range(n2): seen[m] = True m = (m&1) << (n2 - 1) | (m >> 1) if equal_lr: m ^= (1<<n2) - 1 for _ in range(n2): seen[m] = True m = (m&1) << (n2 - 1) | (m >> 1) l_n, r_n = len(this), len(that) tol = 1e-3 while l_lo < l_n: while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol: l_hi += 1 while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol: r_lo += 1 r_hi = r_lo while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol: r_hi += 1 for a in this[l_lo:l_hi]: m_left = a[-2]<<n for b in that[r_lo:r_hi]: if (m := m_left | b[-2]) not in seen: if np.abs(a[1] + b[2]) < tol: record(m) record(int(f'{m:b}'[::-1], base=2)) yield(a[-1] + b[-1]) l_lo, r_lo = l_hi, r_hi def track_combo(left, right): n = (left + right)//2 n1 = left + right - n alphas = np.exp(1j*ANG*np.arange(ANGDIV)) def half_track(m, n): turns = tuple(1 - 2*(m>>i & 1) for i in range(n)) rcnt = np.cumsum(turns)%ANGDIV asum = np.sum(alphas[rcnt]) want = asum/alphas[rcnt[-1]] return np.abs(asum), asum, want, m, turns res = [[] for _ in range(right + 1)] for i in range(1<<n): b = i.bit_count() if b <= right: res[b].append(half_track(i, n)) for v in res: v.sort() if n1 == n: return res, res res1 = [[] for _ in range(right + 1)] for i in range(1<<n1): b = i.bit_count() if b <= right: res1[b].append(half_track(i, n1)) for v in res: v.sort() return res, res1 def railway(n): seen = {} for l in range(n//2, n + 1): r = n - l if not l >= r: continue if (l - r)%ANGDIV == 0: res_l, res_r = track_combo(l, r) for i, this in enumerate(res_l): if 2*i < r: continue that = res_r[r - i] for s in match_up(this, that, l == r, seen): yield s sols = [] for i, s in enumerate(railway(30)): print(i + 1, s) sols.append(s) draw_all(sols[:40])
Produce a language-to-language conversion: from Java to Python, same semantics.
package distanceAndBearing; public class Airport { private String airport; private String country; private String icao; private double lat; private double lon; public String getAirportName() { return this.airport; } public void setAirportName(String airport) { this.airport = airport; } public String getCountry() { return this.country; } public void setCountry(String country) { this.country = country; } public String getIcao() { return this.icao; } public void setIcao(String icao) { this.icao = icao; } public double getLat() { return this.lat; } public void setLat(double lat) { this.lat = lat; } public double getLon() { return this.lon; } public void setLon(double lon) { this.lon = lon; } @Override public String toString() {return "Airport: " + getAirportName() + ": ICAO: " + getIcao();} } package distanceAndBearing; import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; public class DistanceAndBearing { private final double earthRadius = 6371; private File datFile; private List<Airport> airports; public DistanceAndBearing() { this.airports = new ArrayList<Airport>(); } public boolean readFile(String filename) { this.datFile = new File(filename); try { Scanner fileScanner = new Scanner(datFile); String line; while (fileScanner.hasNextLine()) { line = fileScanner.nextLine(); line = line.replace(", ", "; "); line = line.replace(",\",\"", "\",\""); String[] parts = line.split(","); Airport airport = new Airport(); airport.setAirportName(parts[1].replace("\"", "")); airport.setCountry(parts[3].replace("\"", "")); airport.setIcao(parts[5].replace("\"", "")); airport.setLat(Double.valueOf(parts[6])); airport.setLon(Double.valueOf(parts[7])); this.airports.add(airport); } fileScanner.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; }} public double[] calculate(double lat1, double lon1, double lat2, double lon2) { double[] results = new double[2]; double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double rlat1 = Math.toRadians(lat1); double rlat2 = Math.toRadians(lat2); double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2); double c = 2 * Math.asin(Math.sqrt(a)); double distance = earthRadius * c; DecimalFormat df = new DecimalFormat("#0.00"); distance = Double.valueOf(df.format(distance)); results[0] = distance; double X = Math.cos(rlat2) * Math.sin(dLon); double Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon); double heading = Math.atan2(X, Y); heading = Math.toDegrees(heading); results[1] = heading; return results; } public Airport searchByName(final String name) { Airport airport = new Airport(); List<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name)) .collect(Collectors.toList()); airport = results.get(0); return airport; } public List<Airport> findClosestAirports(double lat, double lon) { Map<Double, Airport> airportDistances = new HashMap<>(); Map<Double, Airport> airportHeading = new HashMap<>(); List<Airport> closestAirports = new ArrayList<Airport>(); for (Airport ap : this.airports) { double[] result = calculate(lat, lon, ap.getLat(), ap.getLon()); airportDistances.put(result[0], ap); airportHeading.put(result[1], ap); } ArrayList<Double> distances = new ArrayList<>(airportDistances.keySet()); Collections.sort(distances); for (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));} Map<String, Double> distanceMap = new HashMap<>(); for (Double d : airportDistances.keySet()) { distanceMap.put(airportDistances.get(d).getAirportName(), d);} Map<String, Double> headingMap = new HashMap<>(); for (Double d : airportHeading.keySet()) { double d2 = d; if(d2<0){d2+=360'} headingMap.put(airportHeading.get(d).getAirportName(), d2); } System.out.printf("%-4s %-40s %-25s %-6s %12s %15s\n", "Num", "Airport", "Country", "ICAO", "Distance", "Bearing"); System.out.println("-----------------------------------------------------------------------------------------------------------"); int i = 0; for (Airport a : closestAirports) { System.out.printf("%-4s %-40s %-25s %-6s %12.1f %15.0f\n", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName())); } return closestAirports; } }
from math import radians, degrees, sin, cos, asin, atan2, sqrt from pandas import read_csv EARTH_RADIUS_KM = 6372.8 TASK_CONVERT_NM = 0.0094174 AIRPORT_DATA_FILE = 'airports.dat.txt' QUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581 def haversine(lat1, lon1, lat2, lon2): rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]] dlat = rlat2 - rlat1 dlon = rlon2 - rlon1 arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2 clen = 2.0 * degrees(asin(sqrt(arc))) theta = atan2(sin(dlon) * cos(rlat2), cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon)) theta = (degrees(theta) + 360) % 360 return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta def find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE): airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[ 'Name', 'Country', 'ICAO', 'Latitude', 'Longitude']) airports['Distance'] = 0.0 airports['Bearing'] = 0 for (idx, row) in enumerate(airports.itertuples()): distance, bearing = haversine( latitude, longitude, row.Latitude, row.Longitude) airports.at[idx, 'Distance'] = round(distance, ndigits=1) airports.at[idx, 'Bearing'] = int(round(bearing)) airports.sort_values(by=['Distance'], ignore_index=True, inplace=True) return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']] print(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))
Write the same algorithm in Python as shown in this Java implementation.
package distanceAndBearing; public class Airport { private String airport; private String country; private String icao; private double lat; private double lon; public String getAirportName() { return this.airport; } public void setAirportName(String airport) { this.airport = airport; } public String getCountry() { return this.country; } public void setCountry(String country) { this.country = country; } public String getIcao() { return this.icao; } public void setIcao(String icao) { this.icao = icao; } public double getLat() { return this.lat; } public void setLat(double lat) { this.lat = lat; } public double getLon() { return this.lon; } public void setLon(double lon) { this.lon = lon; } @Override public String toString() {return "Airport: " + getAirportName() + ": ICAO: " + getIcao();} } package distanceAndBearing; import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; public class DistanceAndBearing { private final double earthRadius = 6371; private File datFile; private List<Airport> airports; public DistanceAndBearing() { this.airports = new ArrayList<Airport>(); } public boolean readFile(String filename) { this.datFile = new File(filename); try { Scanner fileScanner = new Scanner(datFile); String line; while (fileScanner.hasNextLine()) { line = fileScanner.nextLine(); line = line.replace(", ", "; "); line = line.replace(",\",\"", "\",\""); String[] parts = line.split(","); Airport airport = new Airport(); airport.setAirportName(parts[1].replace("\"", "")); airport.setCountry(parts[3].replace("\"", "")); airport.setIcao(parts[5].replace("\"", "")); airport.setLat(Double.valueOf(parts[6])); airport.setLon(Double.valueOf(parts[7])); this.airports.add(airport); } fileScanner.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; }} public double[] calculate(double lat1, double lon1, double lat2, double lon2) { double[] results = new double[2]; double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double rlat1 = Math.toRadians(lat1); double rlat2 = Math.toRadians(lat2); double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2); double c = 2 * Math.asin(Math.sqrt(a)); double distance = earthRadius * c; DecimalFormat df = new DecimalFormat("#0.00"); distance = Double.valueOf(df.format(distance)); results[0] = distance; double X = Math.cos(rlat2) * Math.sin(dLon); double Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon); double heading = Math.atan2(X, Y); heading = Math.toDegrees(heading); results[1] = heading; return results; } public Airport searchByName(final String name) { Airport airport = new Airport(); List<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name)) .collect(Collectors.toList()); airport = results.get(0); return airport; } public List<Airport> findClosestAirports(double lat, double lon) { Map<Double, Airport> airportDistances = new HashMap<>(); Map<Double, Airport> airportHeading = new HashMap<>(); List<Airport> closestAirports = new ArrayList<Airport>(); for (Airport ap : this.airports) { double[] result = calculate(lat, lon, ap.getLat(), ap.getLon()); airportDistances.put(result[0], ap); airportHeading.put(result[1], ap); } ArrayList<Double> distances = new ArrayList<>(airportDistances.keySet()); Collections.sort(distances); for (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));} Map<String, Double> distanceMap = new HashMap<>(); for (Double d : airportDistances.keySet()) { distanceMap.put(airportDistances.get(d).getAirportName(), d);} Map<String, Double> headingMap = new HashMap<>(); for (Double d : airportHeading.keySet()) { double d2 = d; if(d2<0){d2+=360'} headingMap.put(airportHeading.get(d).getAirportName(), d2); } System.out.printf("%-4s %-40s %-25s %-6s %12s %15s\n", "Num", "Airport", "Country", "ICAO", "Distance", "Bearing"); System.out.println("-----------------------------------------------------------------------------------------------------------"); int i = 0; for (Airport a : closestAirports) { System.out.printf("%-4s %-40s %-25s %-6s %12.1f %15.0f\n", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName())); } return closestAirports; } }
from math import radians, degrees, sin, cos, asin, atan2, sqrt from pandas import read_csv EARTH_RADIUS_KM = 6372.8 TASK_CONVERT_NM = 0.0094174 AIRPORT_DATA_FILE = 'airports.dat.txt' QUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581 def haversine(lat1, lon1, lat2, lon2): rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]] dlat = rlat2 - rlat1 dlon = rlon2 - rlon1 arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2 clen = 2.0 * degrees(asin(sqrt(arc))) theta = atan2(sin(dlon) * cos(rlat2), cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon)) theta = (degrees(theta) + 360) % 360 return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta def find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE): airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[ 'Name', 'Country', 'ICAO', 'Latitude', 'Longitude']) airports['Distance'] = 0.0 airports['Bearing'] = 0 for (idx, row) in enumerate(airports.itertuples()): distance, bearing = haversine( latitude, longitude, row.Latitude, row.Longitude) airports.at[idx, 'Distance'] = round(distance, ndigits=1) airports.at[idx, 'Bearing'] = int(round(bearing)) airports.sort_values(by=['Distance'], ignore_index=True, inplace=True) return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']] print(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))
Write the same algorithm in Python as shown in this Java implementation.
import java.awt.Point; import java.util.*; import static java.util.Arrays.asList; import java.util.function.Function; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toList; public class FreePolyominoesEnum { static final List<Function<Point, Point>> transforms = new ArrayList<>(); static { transforms.add(p -> new Point(p.y, -p.x)); transforms.add(p -> new Point(-p.x, -p.y)); transforms.add(p -> new Point(-p.y, p.x)); transforms.add(p -> new Point(-p.x, p.y)); transforms.add(p -> new Point(-p.y, -p.x)); transforms.add(p -> new Point(p.x, -p.y)); transforms.add(p -> new Point(p.y, p.x)); } static Point findMinima(List<Point> poly) { return new Point( poly.stream().mapToInt(a -> a.x).min().getAsInt(), poly.stream().mapToInt(a -> a.y).min().getAsInt()); } static List<Point> translateToOrigin(List<Point> poly) { final Point min = findMinima(poly); poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y)); return poly; } static List<List<Point>> rotationsAndReflections(List<Point> poly) { List<List<Point>> lst = new ArrayList<>(); lst.add(poly); for (Function<Point, Point> t : transforms) lst.add(poly.stream().map(t).collect(toList())); return lst; } static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x) .thenComparingInt(p -> p.y); static List<Point> normalize(List<Point> poly) { return rotationsAndReflections(poly).stream() .map(lst -> translateToOrigin(lst)) .map(lst -> lst.stream().sorted(byCoords).collect(toList())) .min(comparing(Object::toString)) .get(); } static List<Point> neighborhoods(Point p) { return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y), new Point(p.x, p.y - 1), new Point(p.x, p.y + 1)); } static List<Point> concat(List<Point> lst, Point pt) { List<Point> r = new ArrayList<>(); r.addAll(lst); r.add(pt); return r; } static List<Point> newPoints(List<Point> poly) { return poly.stream() .flatMap(p -> neighborhoods(p).stream()) .filter(p -> !poly.contains(p)) .distinct() .collect(toList()); } static List<List<Point>> constructNextRank(List<Point> poly) { return newPoints(poly).stream() .map(p -> normalize(concat(poly, p))) .distinct() .collect(toList()); } static List<List<Point>> rank(int n) { if (n < 0) throw new IllegalArgumentException("n cannot be negative"); if (n < 2) { List<List<Point>> r = new ArrayList<>(); if (n == 1) r.add(asList(new Point(0, 0))); return r; } return rank(n - 1).stream() .parallel() .flatMap(lst -> constructNextRank(lst).stream()) .distinct() .collect(toList()); } public static void main(String[] args) { for (List<Point> poly : rank(5)) { for (Point p : poly) System.out.printf("(%d,%d) ", p.x, p.y); System.out.println(); } } }
from itertools import imap, imap, groupby, chain, imap from operator import itemgetter from sys import argv from array import array def concat_map(func, it): return list(chain.from_iterable(imap(func, it))) def minima(poly): return (min(pt[0] for pt in poly), min(pt[1] for pt in poly)) def translate_to_origin(poly): (minx, miny) = minima(poly) return [(x - minx, y - miny) for (x, y) in poly] rotate90 = lambda (x, y): ( y, -x) rotate180 = lambda (x, y): (-x, -y) rotate270 = lambda (x, y): (-y, x) reflect = lambda (x, y): (-x, y) def rotations_and_reflections(poly): return (poly, map(rotate90, poly), map(rotate180, poly), map(rotate270, poly), map(reflect, poly), [reflect(rotate90(pt)) for pt in poly], [reflect(rotate180(pt)) for pt in poly], [reflect(rotate270(pt)) for pt in poly]) def canonical(poly): return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly)) def unique(lst): lst.sort() return map(next, imap(itemgetter(1), groupby(lst))) contiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] def new_points(poly): return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly]) def new_polys(poly): return unique([canonical(poly + [pt]) for pt in new_points(poly)]) monomino = [(0, 0)] monominoes = [monomino] def rank(n): assert n >= 0 if n == 0: return [] if n == 1: return monominoes return unique(concat_map(new_polys, rank(n - 1))) def text_representation(poly): min_pt = minima(poly) max_pt = (max(p[0] for p in poly), max(p[1] for p in poly)) table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1) for _ in xrange(max_pt[0] - min_pt[0] + 1)] for pt in poly: table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = ' return "\n".join(row.tostring() for row in table) def main(): print [len(rank(n)) for n in xrange(1, 11)] n = int(argv[1]) if (len(argv) == 2) else 5 print "\nAll free polyominoes of rank %d:" % n for poly in rank(n): print text_representation(poly), "\n" main()
Can you help me rewrite this code in Python instead of Java, keeping it the same logically?
package src; import java.io.BufferedReader; import java.io.FileReader; import java.net.URI; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class EventGetter { String city = ""; String topic = ""; public String getEvent(String path_code,String key) throws Exception{ String responseString = ""; URI request = new URIBuilder() .setScheme("http") .setHost("api.meetup.com") .setPath(path_code) .setParameter("topic", topic) .setParameter("city", city) .setParameter("key", key) .build(); HttpGet get = new HttpGet(request); System.out.println("Get request : "+get.toString()); CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(get); responseString = EntityUtils.toString(response.getEntity()); return responseString; } public String getApiKey(String key_path){ String key = ""; try{ BufferedReader reader = new BufferedReader(new FileReader(key_path)); key = reader.readLine().toString(); reader.close(); } catch(Exception e){System.out.println(e.toString());} return key; } }
import requests import json city = None topic = None def getEvent(url_path, key) : responseString = "" params = {'city':city, 'key':key,'topic':topic} r = requests.get(url_path, params = params) print(r.url) responseString = r.text return responseString def getApiKey(key_path): key = "" f = open(key_path, 'r') key = f.read() return key def submitEvent(url_path,params): r = requests.post(url_path, data=json.dumps(params)) print(r.text+" : Event Submitted")
Transform the following Java implementation into Python, maintaining the same output and logic.
public class LogicPuzzle { boolean S[] = new boolean[13]; int Count = 0; public boolean check2 () { int count = 0; for (int k = 7; k <= 12; k++) if (S[k]) count++; return S[2] == (count == 3); } public boolean check3 () { int count = 0; for (int k = 2; k <= 12; k += 2) if (S[k]) count++; return S[3] == (count == 2); } public boolean check4 () { return S[4] == ( !S[5] || S[6] && S[7]); } public boolean check5 () { return S[5] == ( !S[2] && !S[3] && !S[4]); } public boolean check6 () { int count = 0; for (int k = 1; k <= 11; k += 2) if (S[k]) count++; return S[6] == (count == 4); } public boolean check7 () { return S[7] == ((S[2] || S[3]) && !(S[2] && S[3])); } public boolean check8 () { return S[8] == ( !S[7] || S[5] && S[6]); } public boolean check9 () { int count = 0; for (int k = 1; k <= 6; k++) if (S[k]) count++; return S[9] == (count == 3); } public boolean check10 () { return S[10] == (S[11] && S[12]); } public boolean check11 () { int count = 0; for (int k = 7; k <= 9; k++) if (S[k]) count++; return S[11] == (count == 1); } public boolean check12 () { int count = 0; for (int k = 1; k <= 11; k++) if (S[k]) count++; return S[12] == (count == 4); } public void check () { if (check2() && check3() && check4() && check5() && check6() && check7() && check8() && check9() && check10() && check11() && check12()) { for (int k = 1; k <= 12; k++) if (S[k]) System.out.print(k + " "); System.out.println(); Count++; } } public void recurseAll (int k) { if (k == 13) check(); else { S[k] = false; recurseAll(k + 1); S[k] = true; recurseAll(k + 1); } } public static void main (String args[]) { LogicPuzzle P = new LogicPuzzle(); P.S[1] = true; P.recurseAll(2); System.out.println(); System.out.println(P.Count + " Solutions found."); } }
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
Port the following code from Java to Python with equivalent syntax and logic.
import static java.lang.Math.*; import java.util.Arrays; import java.util.function.BiFunction; public class DemingsFunnel { public static void main(String[] args) { double[] dxs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087}; double[] dys = { 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032}; experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0); experiment("Rule 2:", dxs, dys, (z, dz) -> -dz); experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz)); experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz); } static void experiment(String label, double[] dxs, double[] dys, BiFunction<Double, Double, Double> rule) { double[] resx = funnel(dxs, rule); double[] resy = funnel(dys, rule); System.out.println(label); System.out.printf("Mean x, y:  %.4f, %.4f%n", mean(resx), mean(resy)); System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy)); System.out.println(); } static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) { double x = 0; double[] result = new double[input.length]; for (int i = 0; i < input.length; i++) { double rx = x + input[i]; x = rule.apply(x, input[i]); result[i] = rx; } return result; } static double mean(double[] xs) { return Arrays.stream(xs).sum() / xs.length; } static double stdDev(double[] xs) { double m = mean(xs); return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length); } }
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y  : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
Port the following code from Java to Python with equivalent syntax and logic.
import static java.lang.Math.*; import java.util.Arrays; import java.util.function.BiFunction; public class DemingsFunnel { public static void main(String[] args) { double[] dxs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087}; double[] dys = { 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032}; experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0); experiment("Rule 2:", dxs, dys, (z, dz) -> -dz); experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz)); experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz); } static void experiment(String label, double[] dxs, double[] dys, BiFunction<Double, Double, Double> rule) { double[] resx = funnel(dxs, rule); double[] resy = funnel(dys, rule); System.out.println(label); System.out.printf("Mean x, y:  %.4f, %.4f%n", mean(resx), mean(resy)); System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy)); System.out.println(); } static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) { double x = 0; double[] result = new double[input.length]; for (int i = 0; i < input.length; i++) { double rx = x + input[i]; x = rule.apply(x, input[i]); result[i] = rx; } return result; } static double mean(double[] xs) { return Arrays.stream(xs).sum() / xs.length; } static double stdDev(double[] xs) { double m = mean(xs); return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length); } }
import math dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915, 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087] dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032] def funnel(dxs, rule): x, rxs = 0, [] for dx in dxs: rxs.append(x + dx) x = rule(x, dx) return rxs def mean(xs): return sum(xs) / len(xs) def stddev(xs): m = mean(xs) return math.sqrt(sum((x-m)**2 for x in xs) / len(xs)) def experiment(label, rule): rxs, rys = funnel(dxs, rule), funnel(dys, rule) print label print 'Mean x, y  : %.4f, %.4f' % (mean(rxs), mean(rys)) print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys)) print experiment('Rule 1:', lambda z, dz: 0) experiment('Rule 2:', lambda z, dz: -dz) experiment('Rule 3:', lambda z, dz: -(z+dz)) experiment('Rule 4:', lambda z, dz: z+dz)
Keep all operations the same but rewrite the snippet in Python.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; public class FixCodeTags { public static void main(String[] args) { String sourcefile=args[0]; String convertedfile=args[1]; convert(sourcefile,convertedfile); } static String[] languages = {"abap", "actionscript", "actionscript3", "ada", "apache", "applescript", "apt_sources", "asm", "asp", "autoit", "avisynth", "bar", "bash", "basic4gl", "bf", "blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg", "cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css", "d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email", "foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml", "gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict", "idl", "ini", "inno", "intercal", "io", "java", "java5", "javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp", "lolcode", "lotusformulas", "lotusscript", "lscript", "lua", "m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml", "mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas", "oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief", "pic16", "pixelbender", "plsql", "povray", "powershell", "progress", "prolog", "providex", "python", "qbasic", "rails", "reg", "robots", "ruby", "sas", "scala", "scheme", "scilab", "sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm", "text", "thinbasic", "tsql", "typoscript", "vb", "vbnet", "verilog", "vhdl", "vim", "visualfoxpro", "visualprolog", "whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"}; static void convert(String sourcefile,String convertedfile) { try { BufferedReader br=new BufferedReader(new FileReader(sourcefile)); StringBuffer sb=new StringBuffer(""); String line; while((line=br.readLine())!=null) { for(int i=0;i<languages.length;i++) { String lang=languages[i]; line=line.replaceAll("<"+lang+">", "<lang "+lang+">"); line=line.replaceAll("</"+lang+">", "</"+"lang>"); line=line.replaceAll("<code "+lang+">", "<lang "+lang+">"); line=line.replaceAll("</code>", "</"+"lang>"); } sb.append(line); } br.close(); FileWriter fw=new FileWriter(new File(convertedfile)); fw.write(sb.toString()); fw.close(); } catch (Exception e) { System.out.println("Something went horribly wrong: "+e.getMessage()); } } }
from re import sub testtexts = [ , , ] for txt in testtexts: text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt) text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2) text2 = sub(r'</lang\s*>', r'
Convert the following code from Java to Python, ensuring the logic remains intact.
import java.util.function.Predicate; public class PermutationsWithRepetitions { public static void main(String[] args) { char[] chars = {'a', 'b', 'c', 'd'}; permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0); } static void permute(char[] a, int k, Predicate<int[]> decider) { int n = a.length; if (k < 1 || k > n) throw new IllegalArgumentException("Illegal number of positions."); int[] indexes = new int[n]; int total = (int) Math.pow(n, k); while (total-- > 0) { for (int i = 0; i < n - (n - k); i++) System.out.print(a[indexes[i]]); System.out.println(); if (decider.test(indexes)) break; for (int i = 0; i < n; i++) { if (indexes[i] >= n - 1) { indexes[i] = 0; } else { indexes[i]++; break; } } } } }
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ + ':\n')(repr)(showList)( replicateM(2) )([[1, 2, 3], 'abc']) ) def liftA2List(f): return lambda xs: lambda ys: [ f(*xy) for xy in product(xs, ys) ] def fTable(s): def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def showList(xs): return '[' + ','.join( showList(x) if isinstance(x, list) else repr(x) for x in xs ) + ']' if __name__ == '__main__': main()
Preserve the algorithm and functionality while converting the code from Java to Python.
import java.util.function.Predicate; public class PermutationsWithRepetitions { public static void main(String[] args) { char[] chars = {'a', 'b', 'c', 'd'}; permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0); } static void permute(char[] a, int k, Predicate<int[]> decider) { int n = a.length; if (k < 1 || k > n) throw new IllegalArgumentException("Illegal number of positions."); int[] indexes = new int[n]; int total = (int) Math.pow(n, k); while (total-- > 0) { for (int i = 0; i < n - (n - k); i++) System.out.print(a[indexes[i]]); System.out.println(); if (decider.test(indexes)) break; for (int i = 0; i < n; i++) { if (indexes[i] >= n - 1) { indexes[i] = 0; } else { indexes[i]++; break; } } } } }
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ + ':\n')(repr)(showList)( replicateM(2) )([[1, 2, 3], 'abc']) ) def liftA2List(f): return lambda xs: lambda ys: [ f(*xy) for xy in product(xs, ys) ] def fTable(s): def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def showList(xs): return '[' + ','.join( showList(x) if isinstance(x, list) else repr(x) for x in xs ) + ']' if __name__ == '__main__': main()
Port the provided Java code into Python while preserving the original functionality.
import java.util.function.Predicate; public class PermutationsWithRepetitions { public static void main(String[] args) { char[] chars = {'a', 'b', 'c', 'd'}; permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0); } static void permute(char[] a, int k, Predicate<int[]> decider) { int n = a.length; if (k < 1 || k > n) throw new IllegalArgumentException("Illegal number of positions."); int[] indexes = new int[n]; int total = (int) Math.pow(n, k); while (total-- > 0) { for (int i = 0; i < n - (n - k); i++) System.out.print(a[indexes[i]]); System.out.println(); if (decider.test(indexes)) break; for (int i = 0; i < n; i++) { if (indexes[i] >= n - 1) { indexes[i] = 0; } else { indexes[i]++; break; } } } } }
from itertools import product def replicateM(n): def rep(m): def go(x): return [[]] if 1 > x else ( liftA2List(lambda a, b: [a] + b)(m)(go(x - 1)) ) return go(n) return lambda m: rep(m) def main(): print( fTable(main.__doc__ + ':\n')(repr)(showList)( replicateM(2) )([[1, 2, 3], 'abc']) ) def liftA2List(f): return lambda xs: lambda ys: [ f(*xy) for xy in product(xs, ys) ] def fTable(s): def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) def showList(xs): return '[' + ','.join( showList(x) if isinstance(x, list) else repr(x) for x in xs ) + ']' if __name__ == '__main__': main()
Produce a language-to-language conversion: from Java to Python, same semantics.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OneTimePad { public static void main(String[] args) { String controlName = "AtomicBlonde"; generatePad(controlName, 5, 60, 65, 90); String text = "IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES"; String encrypted = parse(true, controlName, text.replaceAll(" ", "")); String decrypted = parse(false, controlName, encrypted); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted); controlName = "AtomicBlondeCaseSensitive"; generatePad(controlName, 5, 60, 32, 126); text = "It was the best of times, it was the worst of times."; encrypted = parse(true, controlName, text); decrypted = parse(false, controlName, encrypted); System.out.println(); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted); } private static String parse(boolean encryptText, String controlName, String text) { StringBuilder sb = new StringBuilder(); int minCh = 0; int maxCh = 0; Pattern minChPattern = Pattern.compile("^# MIN_CH = ([\\d]+)$"); Pattern maxChPattern = Pattern.compile("^# MAX_CH = ([\\d]+)$"); boolean validated = false; try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) { String inLine = null; while ( (inLine = in.readLine()) != null ) { Matcher minMatcher = minChPattern.matcher(inLine); if ( minMatcher.matches() ) { minCh = Integer.parseInt(minMatcher.group(1)); continue; } Matcher maxMatcher = maxChPattern.matcher(inLine); if ( maxMatcher.matches() ) { maxCh = Integer.parseInt(maxMatcher.group(1)); continue; } if ( ! validated && minCh > 0 && maxCh > 0 ) { validateText(text, minCh, maxCh); validated = true; } if ( inLine.startsWith("#") || inLine.startsWith("-") ) { continue; } String key = inLine; if ( encryptText ) { for ( int i = 0 ; i < text.length(); i++) { sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh)); } } else { for ( int i = 0 ; i < text.length(); i++) { int decrypt = text.charAt(i) - key.charAt(i); if ( decrypt < 0 ) { decrypt += maxCh - minCh + 1; } decrypt += minCh; sb.append((char) decrypt); } } break; } } catch (IOException e) { throw new RuntimeException(e); } return sb.toString(); } private static void validateText(String text, int minCh, int maxCh) { for ( char ch : text.toCharArray() ) { if ( ch != ' ' && (ch < minCh || ch > maxCh) ) { throw new IllegalArgumentException("ERROR 103: Invalid text."); } } } private static String getFileName(String controlName) { return controlName + ".1tp"; } private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) { Random random = new Random(); try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) { writer.write("# Lines starting with '#' are ignored."); writer.newLine(); writer.write("# Lines starting with '-' are previously used."); writer.newLine(); writer.write("# MIN_CH = " + minCh); writer.newLine(); writer.write("# MAX_CH = " + maxCh); writer.newLine(); for ( int line = 0 ; line < keys ; line++ ) { StringBuilder sb = new StringBuilder(); for ( int ch = 0 ; ch < keyLength ; ch++ ) { sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh)); } writer.write(sb.toString()); writer.newLine(); } writer.write("# EOF"); writer.newLine(); } catch (Exception e) { throw new RuntimeException(e); } } }
import argparse import itertools import pathlib import re import secrets import sys MAGIC = " def make_keys(n, size): return (secrets.token_hex(size) for _ in range(n)) def make_pad(name, pad_size, key_size): pad = [ MAGIC, f" f" *make_keys(pad_size, key_size), ] return "\n".join(pad) def xor(message, key): return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key))) def use_key(pad): match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE) if not match: error("pad is all used up") key = match.group() pos = match.start() return (f"{pad[:pos]}-{pad[pos:]}", key) def log(msg): sys.stderr.write(msg) sys.stderr.write("\n") def error(msg): sys.stderr.write(msg) sys.stderr.write("\n") sys.exit(1) def write_pad(path, pad_size, key_size): if path.exists(): error(f"pad '{path}' already exists") with path.open("w") as fd: fd.write(make_pad(path.name, pad_size, key_size)) log(f"New one-time pad written to {path}") def main(pad, message, outfile): if not pad.exists(): error(f"no such pad '{pad}'") with pad.open("r") as fd: if fd.readline().strip() != MAGIC: error(f"file '{pad}' does not look like a one-time pad") with pad.open("r+") as fd: updated, key = use_key(fd.read()) fd.seek(0) fd.write(updated) outfile.write(xor(message, bytes.fromhex(key))) if __name__ == "__main__": parser = argparse.ArgumentParser(description="One-time pad.") parser.add_argument( "pad", help=( "Path to one-time pad. If neither --encrypt or --decrypt " "are given, will create a new pad." ), ) parser.add_argument( "--length", type=int, default=10, help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.", ) parser.add_argument( "--key-size", type=int, default=64, help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.", ) parser.add_argument( "-o", "--outfile", type=argparse.FileType("wb"), default=sys.stdout.buffer, help=( "Write encoded/decoded message to a file. Ignored if --encrypt or " "--decrypt is not given. Defaults to stdout." ), ) group = parser.add_mutually_exclusive_group() group.add_argument( "--encrypt", metavar="FILE", type=argparse.FileType("rb"), help="Encrypt FILE using the next available key from pad.", ) group.add_argument( "--decrypt", metavar="FILE", type=argparse.FileType("rb"), help="Decrypt FILE using the next available key from pad.", ) args = parser.parse_args() if args.encrypt: message = args.encrypt.read() elif args.decrypt: message = args.decrypt.read() else: message = None if isinstance(message, str): message = message.encode() pad = pathlib.Path(args.pad).with_suffix(".1tp") if message: main(pad, message, args.outfile) else: write_pad(pad, args.length, args.key_size)
Rewrite the snippet below in Python so it works the same as the original Java code.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OneTimePad { public static void main(String[] args) { String controlName = "AtomicBlonde"; generatePad(controlName, 5, 60, 65, 90); String text = "IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES"; String encrypted = parse(true, controlName, text.replaceAll(" ", "")); String decrypted = parse(false, controlName, encrypted); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted); controlName = "AtomicBlondeCaseSensitive"; generatePad(controlName, 5, 60, 32, 126); text = "It was the best of times, it was the worst of times."; encrypted = parse(true, controlName, text); decrypted = parse(false, controlName, encrypted); System.out.println(); System.out.println("Input text = " + text); System.out.println("Encrypted text = " + encrypted); System.out.println("Decrypted text = " + decrypted); } private static String parse(boolean encryptText, String controlName, String text) { StringBuilder sb = new StringBuilder(); int minCh = 0; int maxCh = 0; Pattern minChPattern = Pattern.compile("^# MIN_CH = ([\\d]+)$"); Pattern maxChPattern = Pattern.compile("^# MAX_CH = ([\\d]+)$"); boolean validated = false; try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) { String inLine = null; while ( (inLine = in.readLine()) != null ) { Matcher minMatcher = minChPattern.matcher(inLine); if ( minMatcher.matches() ) { minCh = Integer.parseInt(minMatcher.group(1)); continue; } Matcher maxMatcher = maxChPattern.matcher(inLine); if ( maxMatcher.matches() ) { maxCh = Integer.parseInt(maxMatcher.group(1)); continue; } if ( ! validated && minCh > 0 && maxCh > 0 ) { validateText(text, minCh, maxCh); validated = true; } if ( inLine.startsWith("#") || inLine.startsWith("-") ) { continue; } String key = inLine; if ( encryptText ) { for ( int i = 0 ; i < text.length(); i++) { sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh)); } } else { for ( int i = 0 ; i < text.length(); i++) { int decrypt = text.charAt(i) - key.charAt(i); if ( decrypt < 0 ) { decrypt += maxCh - minCh + 1; } decrypt += minCh; sb.append((char) decrypt); } } break; } } catch (IOException e) { throw new RuntimeException(e); } return sb.toString(); } private static void validateText(String text, int minCh, int maxCh) { for ( char ch : text.toCharArray() ) { if ( ch != ' ' && (ch < minCh || ch > maxCh) ) { throw new IllegalArgumentException("ERROR 103: Invalid text."); } } } private static String getFileName(String controlName) { return controlName + ".1tp"; } private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) { Random random = new Random(); try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) { writer.write("# Lines starting with '#' are ignored."); writer.newLine(); writer.write("# Lines starting with '-' are previously used."); writer.newLine(); writer.write("# MIN_CH = " + minCh); writer.newLine(); writer.write("# MAX_CH = " + maxCh); writer.newLine(); for ( int line = 0 ; line < keys ; line++ ) { StringBuilder sb = new StringBuilder(); for ( int ch = 0 ; ch < keyLength ; ch++ ) { sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh)); } writer.write(sb.toString()); writer.newLine(); } writer.write("# EOF"); writer.newLine(); } catch (Exception e) { throw new RuntimeException(e); } } }
import argparse import itertools import pathlib import re import secrets import sys MAGIC = " def make_keys(n, size): return (secrets.token_hex(size) for _ in range(n)) def make_pad(name, pad_size, key_size): pad = [ MAGIC, f" f" *make_keys(pad_size, key_size), ] return "\n".join(pad) def xor(message, key): return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key))) def use_key(pad): match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE) if not match: error("pad is all used up") key = match.group() pos = match.start() return (f"{pad[:pos]}-{pad[pos:]}", key) def log(msg): sys.stderr.write(msg) sys.stderr.write("\n") def error(msg): sys.stderr.write(msg) sys.stderr.write("\n") sys.exit(1) def write_pad(path, pad_size, key_size): if path.exists(): error(f"pad '{path}' already exists") with path.open("w") as fd: fd.write(make_pad(path.name, pad_size, key_size)) log(f"New one-time pad written to {path}") def main(pad, message, outfile): if not pad.exists(): error(f"no such pad '{pad}'") with pad.open("r") as fd: if fd.readline().strip() != MAGIC: error(f"file '{pad}' does not look like a one-time pad") with pad.open("r+") as fd: updated, key = use_key(fd.read()) fd.seek(0) fd.write(updated) outfile.write(xor(message, bytes.fromhex(key))) if __name__ == "__main__": parser = argparse.ArgumentParser(description="One-time pad.") parser.add_argument( "pad", help=( "Path to one-time pad. If neither --encrypt or --decrypt " "are given, will create a new pad." ), ) parser.add_argument( "--length", type=int, default=10, help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.", ) parser.add_argument( "--key-size", type=int, default=64, help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.", ) parser.add_argument( "-o", "--outfile", type=argparse.FileType("wb"), default=sys.stdout.buffer, help=( "Write encoded/decoded message to a file. Ignored if --encrypt or " "--decrypt is not given. Defaults to stdout." ), ) group = parser.add_mutually_exclusive_group() group.add_argument( "--encrypt", metavar="FILE", type=argparse.FileType("rb"), help="Encrypt FILE using the next available key from pad.", ) group.add_argument( "--decrypt", metavar="FILE", type=argparse.FileType("rb"), help="Decrypt FILE using the next available key from pad.", ) args = parser.parse_args() if args.encrypt: message = args.encrypt.read() elif args.decrypt: message = args.decrypt.read() else: message = None if isinstance(message, str): message = message.encode() pad = pathlib.Path(args.pad).with_suffix(".1tp") if message: main(pad, message, args.outfile) else: write_pad(pad, args.length, args.key_size)
Write the same code in Java as shown below in PHP.
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
String original = "Mary had a X lamb"; String little = "little"; String replaced = original.replace("X", little); System.out.println(replaced); System.out.printf("Mary had a %s lamb.", little); String formatted = String.format("Mary had a %s lamb.", little); System.out.println(formatted);
Ensure the translated Java code behaves exactly like the original PHP snippet.
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
import java.util.*; public class PatienceSort { public static <E extends Comparable<? super E>> void sort (E[] n) { List<Pile<E>> piles = new ArrayList<Pile<E>>(); for (E x : n) { Pile<E> newPile = new Pile<E>(); newPile.push(x); int i = Collections.binarySearch(piles, newPile); if (i < 0) i = ~i; if (i != piles.size()) piles.get(i).push(x); else piles.add(newPile); } PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles); for (int c = 0; c < n.length; c++) { Pile<E> smallPile = heap.poll(); n[c] = smallPile.pop(); if (!smallPile.isEmpty()) heap.offer(smallPile); } assert(heap.isEmpty()); } private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> { public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); } } public static void main(String[] args) { Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1}; sort(a); System.out.println(Arrays.toString(a)); } }
Please provide an equivalent version of this PHP code in Java.
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
import java.util.*; public class PatienceSort { public static <E extends Comparable<? super E>> void sort (E[] n) { List<Pile<E>> piles = new ArrayList<Pile<E>>(); for (E x : n) { Pile<E> newPile = new Pile<E>(); newPile.push(x); int i = Collections.binarySearch(piles, newPile); if (i < 0) i = ~i; if (i != piles.size()) piles.get(i).push(x); else piles.add(newPile); } PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles); for (int c = 0; c < n.length; c++) { Pile<E> smallPile = heap.poll(); n[c] = smallPile.pop(); if (!smallPile.isEmpty()) heap.offer(smallPile); } assert(heap.isEmpty()); } private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> { public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); } } public static void main(String[] args) { Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1}; sort(a); System.out.println(Arrays.toString(a)); } }
Transform the following PHP implementation into Java, maintaining the same output and logic.
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
import static java.lang.Math.*; public class RayCasting { static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P); if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
Maintain the same structure and functionality when rewriting this code in Java.
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
import static java.lang.Math.*; public class RayCasting { static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P); if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
Preserve the algorithm and functionality while converting the code from PHP to Java.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
public class CountSubstring { public static int countSubstring(String subStr, String str){ return (str.length() - str.replace(subStr, "").length()) / subStr.length(); } public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("abab", "ababababab")); System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); } }
Generate a Java translation of this PHP snippet without changing its computational steps.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
public class CountSubstring { public static int countSubstring(String subStr, String str){ return (str.length() - str.replace(subStr, "").length()) / subStr.length(); } public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("abab", "ababababab")); System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); } }
Write the same code in Java as shown below in PHP.
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
Produce a functionally identical Java code for the snippet given in PHP.
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
Change the following PHP code into Java without altering its purpose.
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
Ensure the translated Java code behaves exactly like the original PHP snippet.
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
Keep all operations the same but rewrite the snippet in Java.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Ensure the translated Java code behaves exactly like the original PHP snippet.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Preserve the algorithm and functionality while converting the code from PHP to Java.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Rewrite the snippet below in Java so it works the same as the original PHP code.
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Keep all operations the same but rewrite the snippet in Java.
<?php const BOARD_NUM = 9; const ROW_NUM = 3; $EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM); function isGameOver($board, $pin) { $pat = '/X{3}|' . //Horz 'X..X..X..|' . //Vert Left '.X..X..X.|' . //Vert Middle '..X..X..X|' . //Vert Right '..X.X.X..|' . //Diag TL->BR 'X...X...X|' . //Diag TR->BL '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); } $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn); echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p]; echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; } echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Hashtable; public class TicTacToe { public static void main(String[] args) { TicTacToe now=new TicTacToe(); now.startMatch(); } private int[][] marks; private int[][] wins; private int[] weights; private char[][] grid; private final int knotcount=3; private final int crosscount=4; private final int totalcount=5; private final int playerid=0; private final int compid=1; private final int truceid=2; private final int playingid=3; private String movesPlayer; private byte override; private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}}; private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}}; private Hashtable<Integer,Integer> crossbank; private Hashtable<Integer,Integer> knotbank; public void startMatch() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Start?(y/n):"); char choice='y'; try { choice=br.readLine().charAt(0); } catch(Exception e) { System.out.println(e.getMessage()); } if(choice=='n'||choice=='N') { return; } System.out.println("Use a standard numpad as an entry grid, as so:\n "); display(numpad); System.out.println("Begin"); int playerscore=0; int compscore=0; do { int result=startGame(); if(result==playerid) playerscore++; else if(result==compid) compscore++; System.out.println("Score: Player-"+playerscore+" AI-"+compscore); System.out.print("Another?(y/n):"); try { choice=br.readLine().charAt(0); } catch(Exception e) { System.out.println(e.getMessage()); } }while(choice!='n'||choice=='N'); System.out.println("Game over."); } private void put(int cell,int player) { int i=-1,j=-1;; switch(cell) { case 1:i=2;j=0;break; case 2:i=2;j=1;break; case 3:i=2;j=2;break; case 4:i=1;j=0;break; case 5:i=1;j=1;break; case 6:i=1;j=2;break; case 7:i=0;j=0;break; case 8:i=0;j=1;break; case 9:i=0;j=2;break; default:display(overridegrid);return; } char mark='x'; if(player==0) mark='o'; grid[i][j]=mark; display(grid); } private int startGame() { init(); display(grid); int status=playingid; while(status==playingid) { put(playerMove(),0); if(override==1) { System.out.println("O wins."); return playerid; } status=checkForWin(); if(status!=playingid) break; try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());} put(compMove(),1); status=checkForWin(); } return status; } private void init() { movesPlayer=""; override=0; marks=new int[8][6]; wins=new int[][] { {7,8,9}, {4,5,6}, {1,2,3}, {7,4,1}, {8,5,2}, {9,6,3}, {7,5,3}, {9,5,1} }; weights=new int[]{3,2,3,2,4,2,3,2,3}; grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}}; crossbank=new Hashtable<Integer,Integer>(); knotbank=new Hashtable<Integer,Integer>(); } private void mark(int m,int player) { for(int i=0;i<wins.length;i++) for(int j=0;j<wins[i].length;j++) if(wins[i][j]==m) { marks[i][j]=1; if(player==playerid) marks[i][knotcount]++; else marks[i][crosscount]++; marks[i][totalcount]++; } } private void fixWeights() { for(int i=0;i<3;i++) for(int j=0;j<3;j++) if(marks[i][j]==1) if(weights[wins[i][j]-1]!=Integer.MIN_VALUE) weights[wins[i][j]-1]=Integer.MIN_VALUE; for(int i=0;i<8;i++) { if(marks[i][totalcount]!=2) continue; if(marks[i][crosscount]==2) { int p=i,q=-1; if(marks[i][0]==0) q=0; else if(marks[i][1]==0) q=1; else if(marks[i][2]==0) q=2; if(weights[wins[p][q]-1]!=Integer.MIN_VALUE) { weights[wins[p][q]-1]=6; } } if(marks[i][knotcount]==2) { int p=i,q=-1; if(marks[i][0]==0) q=0; else if(marks[i][1]==0) q=1; else if(marks[i][2]==0) q=2; if(weights[wins[p][q]-1]!=Integer.MIN_VALUE) { weights[wins[p][q]-1]=5; } } } } private int compMove() { int cell=move(); System.out.println("Computer plays: "+cell); return cell; } private int move() { int max=Integer.MIN_VALUE; int cell=0; for(int i=0;i<weights.length;i++) if(weights[i]>max) { max=weights[i]; cell=i+1; } if(movesPlayer.equals("76")||movesPlayer.equals("67")) cell=9; else if(movesPlayer.equals("92")||movesPlayer.equals("29")) cell=3; else if (movesPlayer.equals("18")||movesPlayer.equals("81")) cell=7; else if(movesPlayer.equals("73")||movesPlayer.equals("37")) cell=4*((int)(Math.random()*2)+1); else if(movesPlayer.equals("19")||movesPlayer.equals("91")) cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2))); mark(cell,1); fixWeights(); crossbank.put(cell, 0); return cell; } private int playerMove() { System.out.print("What's your move?: "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int cell=0; int okay=0; while(okay==0) { try { cell=Integer.parseInt(br.readLine()); } catch(Exception e) { System.out.println(e.getMessage()); } if(cell==7494) { override=1; return -1; } if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE) System.out.print("Invalid move. Try again:"); else okay=1; } playerMoved(cell); System.out.println(); return cell; } private void playerMoved(int cell) { movesPlayer+=cell; mark(cell,0); fixWeights(); knotbank.put(cell, 0); } private int checkForWin() { int crossflag=0,knotflag=0; for(int i=0;i<wins.length;i++) { if(crossbank.containsKey(wins[i][0])) if(crossbank.containsKey(wins[i][1])) if(crossbank.containsKey(wins[i][2])) { crossflag=1; break; } if(knotbank.containsKey(wins[i][0])) if(knotbank.containsKey(wins[i][1])) if(knotbank.containsKey(wins[i][2])) { knotflag=1; break; } } if(knotflag==1) { display(grid); System.out.println("O wins."); return playerid; } else if(crossflag==1) { display(grid); System.out.println("X wins."); return compid; } for(int i=0;i<weights.length;i++) if(weights[i]!=Integer.MIN_VALUE) return playingid; System.out.println("Truce"); return truceid; } private void display(char[][] grid) { for(int i=0;i<3;i++) { System.out.println("\n-------"); System.out.print("|"); for(int j=0;j<3;j++) System.out.print(grid[i][j]+"|"); } System.out.println("\n-------"); } }
Maintain the same structure and functionality when rewriting this code in Java.
<?php const BOARD_NUM = 9; const ROW_NUM = 3; $EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM); function isGameOver($board, $pin) { $pat = '/X{3}|' . //Horz 'X..X..X..|' . //Vert Left '.X..X..X.|' . //Vert Middle '..X..X..X|' . //Vert Right '..X.X.X..|' . //Diag TL->BR 'X...X...X|' . //Diag TR->BL '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); } $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn); echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p]; echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; } echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Hashtable; public class TicTacToe { public static void main(String[] args) { TicTacToe now=new TicTacToe(); now.startMatch(); } private int[][] marks; private int[][] wins; private int[] weights; private char[][] grid; private final int knotcount=3; private final int crosscount=4; private final int totalcount=5; private final int playerid=0; private final int compid=1; private final int truceid=2; private final int playingid=3; private String movesPlayer; private byte override; private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}}; private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}}; private Hashtable<Integer,Integer> crossbank; private Hashtable<Integer,Integer> knotbank; public void startMatch() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Start?(y/n):"); char choice='y'; try { choice=br.readLine().charAt(0); } catch(Exception e) { System.out.println(e.getMessage()); } if(choice=='n'||choice=='N') { return; } System.out.println("Use a standard numpad as an entry grid, as so:\n "); display(numpad); System.out.println("Begin"); int playerscore=0; int compscore=0; do { int result=startGame(); if(result==playerid) playerscore++; else if(result==compid) compscore++; System.out.println("Score: Player-"+playerscore+" AI-"+compscore); System.out.print("Another?(y/n):"); try { choice=br.readLine().charAt(0); } catch(Exception e) { System.out.println(e.getMessage()); } }while(choice!='n'||choice=='N'); System.out.println("Game over."); } private void put(int cell,int player) { int i=-1,j=-1;; switch(cell) { case 1:i=2;j=0;break; case 2:i=2;j=1;break; case 3:i=2;j=2;break; case 4:i=1;j=0;break; case 5:i=1;j=1;break; case 6:i=1;j=2;break; case 7:i=0;j=0;break; case 8:i=0;j=1;break; case 9:i=0;j=2;break; default:display(overridegrid);return; } char mark='x'; if(player==0) mark='o'; grid[i][j]=mark; display(grid); } private int startGame() { init(); display(grid); int status=playingid; while(status==playingid) { put(playerMove(),0); if(override==1) { System.out.println("O wins."); return playerid; } status=checkForWin(); if(status!=playingid) break; try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());} put(compMove(),1); status=checkForWin(); } return status; } private void init() { movesPlayer=""; override=0; marks=new int[8][6]; wins=new int[][] { {7,8,9}, {4,5,6}, {1,2,3}, {7,4,1}, {8,5,2}, {9,6,3}, {7,5,3}, {9,5,1} }; weights=new int[]{3,2,3,2,4,2,3,2,3}; grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}}; crossbank=new Hashtable<Integer,Integer>(); knotbank=new Hashtable<Integer,Integer>(); } private void mark(int m,int player) { for(int i=0;i<wins.length;i++) for(int j=0;j<wins[i].length;j++) if(wins[i][j]==m) { marks[i][j]=1; if(player==playerid) marks[i][knotcount]++; else marks[i][crosscount]++; marks[i][totalcount]++; } } private void fixWeights() { for(int i=0;i<3;i++) for(int j=0;j<3;j++) if(marks[i][j]==1) if(weights[wins[i][j]-1]!=Integer.MIN_VALUE) weights[wins[i][j]-1]=Integer.MIN_VALUE; for(int i=0;i<8;i++) { if(marks[i][totalcount]!=2) continue; if(marks[i][crosscount]==2) { int p=i,q=-1; if(marks[i][0]==0) q=0; else if(marks[i][1]==0) q=1; else if(marks[i][2]==0) q=2; if(weights[wins[p][q]-1]!=Integer.MIN_VALUE) { weights[wins[p][q]-1]=6; } } if(marks[i][knotcount]==2) { int p=i,q=-1; if(marks[i][0]==0) q=0; else if(marks[i][1]==0) q=1; else if(marks[i][2]==0) q=2; if(weights[wins[p][q]-1]!=Integer.MIN_VALUE) { weights[wins[p][q]-1]=5; } } } } private int compMove() { int cell=move(); System.out.println("Computer plays: "+cell); return cell; } private int move() { int max=Integer.MIN_VALUE; int cell=0; for(int i=0;i<weights.length;i++) if(weights[i]>max) { max=weights[i]; cell=i+1; } if(movesPlayer.equals("76")||movesPlayer.equals("67")) cell=9; else if(movesPlayer.equals("92")||movesPlayer.equals("29")) cell=3; else if (movesPlayer.equals("18")||movesPlayer.equals("81")) cell=7; else if(movesPlayer.equals("73")||movesPlayer.equals("37")) cell=4*((int)(Math.random()*2)+1); else if(movesPlayer.equals("19")||movesPlayer.equals("91")) cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2))); mark(cell,1); fixWeights(); crossbank.put(cell, 0); return cell; } private int playerMove() { System.out.print("What's your move?: "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int cell=0; int okay=0; while(okay==0) { try { cell=Integer.parseInt(br.readLine()); } catch(Exception e) { System.out.println(e.getMessage()); } if(cell==7494) { override=1; return -1; } if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE) System.out.print("Invalid move. Try again:"); else okay=1; } playerMoved(cell); System.out.println(); return cell; } private void playerMoved(int cell) { movesPlayer+=cell; mark(cell,0); fixWeights(); knotbank.put(cell, 0); } private int checkForWin() { int crossflag=0,knotflag=0; for(int i=0;i<wins.length;i++) { if(crossbank.containsKey(wins[i][0])) if(crossbank.containsKey(wins[i][1])) if(crossbank.containsKey(wins[i][2])) { crossflag=1; break; } if(knotbank.containsKey(wins[i][0])) if(knotbank.containsKey(wins[i][1])) if(knotbank.containsKey(wins[i][2])) { knotflag=1; break; } } if(knotflag==1) { display(grid); System.out.println("O wins."); return playerid; } else if(crossflag==1) { display(grid); System.out.println("X wins."); return compid; } for(int i=0;i<weights.length;i++) if(weights[i]!=Integer.MIN_VALUE) return playingid; System.out.println("Truce"); return truceid; } private void display(char[][] grid) { for(int i=0;i<3;i++) { System.out.println("\n-------"); System.out.print("|"); for(int j=0;j<3;j++) System.out.print(grid[i][j]+"|"); } System.out.println("\n-------"); } }
Translate this program into Java but keep the logic exactly as in PHP.
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Please provide an equivalent version of this PHP code in Java.
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Maintain the same structure and functionality when rewriting this code in Java.
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Change the following PHP code into Java without altering its purpose.
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Port the following code from PHP to Java with equivalent syntax and logic.
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Please provide an equivalent version of this PHP code in Java.
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Port the provided PHP code into Java while preserving the original functionality.
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>"; echo "<br>"; echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>"; $results = ""; if ($player == $a_i){ $results = "Draw"; } else if($wins[$a_i] == $player ){ $results = "A.I wins"; } else { $results = "Player wins"; } echo "<br>" . $results; ?>
import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Random; public class RPS { public enum Item{ ROCK, PAPER, SCISSORS, ; public List<Item> losesToList; public boolean losesTo(Item other) { return losesToList.contains(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK); ROCK.losesToList = Arrays.asList(PAPER); PAPER.losesToList = Arrays.asList(SCISSORS); } } public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{ for(Item item:Item.values()) put(item, 1); }}; private int totalThrows = Item.values().length; public static void main(String[] args){ RPS rps = new RPS(); rps.run(); } public void run() { Scanner in = new Scanner(System.in); System.out.print("Make your choice: "); while(in.hasNextLine()){ Item aiChoice = getAIChoice(); String input = in.nextLine(); Item choice; try{ choice = Item.valueOf(input.toUpperCase()); }catch (IllegalArgumentException ex){ System.out.println("Invalid choice"); continue; } counts.put(choice, counts.get(choice) + 1); totalThrows++; System.out.println("Computer chose: " + aiChoice); if(aiChoice == choice){ System.out.println("Tie!"); }else if(aiChoice.losesTo(choice)){ System.out.println("You chose...wisely. You win!"); }else{ System.out.println("You chose...poorly. You lose!"); } System.out.print("Make your choice: "); } } private static final Random rng = new Random(); private Item getAIChoice() { int rand = rng.nextInt(totalThrows); for(Map.Entry<Item, Integer> entry:counts.entrySet()){ Item item = entry.getKey(); int count = entry.getValue(); if(rand < count){ List<Item> losesTo = item.losesToList; return losesTo.get(rng.nextInt(losesTo.size())); } rand -= count; } return null; } }
Convert this PHP snippet to Java and keep its semantics consistent.
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>"; echo "<br>"; echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>"; $results = ""; if ($player == $a_i){ $results = "Draw"; } else if($wins[$a_i] == $player ){ $results = "A.I wins"; } else { $results = "Player wins"; } echo "<br>" . $results; ?>
import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Random; public class RPS { public enum Item{ ROCK, PAPER, SCISSORS, ; public List<Item> losesToList; public boolean losesTo(Item other) { return losesToList.contains(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK); ROCK.losesToList = Arrays.asList(PAPER); PAPER.losesToList = Arrays.asList(SCISSORS); } } public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{ for(Item item:Item.values()) put(item, 1); }}; private int totalThrows = Item.values().length; public static void main(String[] args){ RPS rps = new RPS(); rps.run(); } public void run() { Scanner in = new Scanner(System.in); System.out.print("Make your choice: "); while(in.hasNextLine()){ Item aiChoice = getAIChoice(); String input = in.nextLine(); Item choice; try{ choice = Item.valueOf(input.toUpperCase()); }catch (IllegalArgumentException ex){ System.out.println("Invalid choice"); continue; } counts.put(choice, counts.get(choice) + 1); totalThrows++; System.out.println("Computer chose: " + aiChoice); if(aiChoice == choice){ System.out.println("Tie!"); }else if(aiChoice.losesTo(choice)){ System.out.println("You chose...wisely. You win!"); }else{ System.out.println("You chose...poorly. You lose!"); } System.out.print("Make your choice: "); } } private static final Random rng = new Random(); private Item getAIChoice() { int rand = rng.nextInt(totalThrows); for(Map.Entry<Item, Integer> entry:counts.entrySet()){ Item item = entry.getKey(); int count = entry.getValue(); if(rand < count){ List<Item> losesTo = item.losesToList; return losesTo.get(rng.nextInt(losesTo.size())); } rand -= count; } return null; } }
Maintain the same structure and functionality when rewriting this code in Java.
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "\n"; $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; }); echo $factorial(10), "\n"; ?>
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Please provide an equivalent version of this PHP code in Java.
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "\n"; $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; }); echo $factorial(10), "\n"; ?>
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Produce a functionally identical Java code for the snippet given in PHP.
function addsub($x, $y) { return array($x + $y, $x - $y); }
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
Write the same code in Java as shown below in PHP.
function addsub($x, $y) { return array($x + $y, $x - $y); }
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
Generate an equivalent Java version of this PHP code.
$server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com"; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } else{ echo 'connected successfully'.PHP_EOL; $directory = ftp_nlist($conn,''); print_r($directory); } if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) { echo "Successfully downloaded file".PHP_EOL; } else { echo "failed to download file"; }
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "ftptest@example.com"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
Generate a Java translation of this PHP snippet without changing its computational steps.
$server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com"; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } else{ echo 'connected successfully'.PHP_EOL; $directory = ftp_nlist($conn,''); print_r($directory); } if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) { echo "Successfully downloaded file".PHP_EOL; } else { echo "failed to download file"; }
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "ftptest@example.com"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
Convert this PHP snippet to Java and keep its semantics consistent.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Ensure the translated Java code behaves exactly like the original PHP snippet.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Keep all operations the same but rewrite the snippet in Java.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Change the programming language of this snippet from PHP to Java without modifying what it does.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Maintain the same structure and functionality when rewriting this code in Java.
for ($i = 1; $i <= 10; $i++) { echo $i; if ($i % 5 == 0) { echo "\n"; continue; } echo ', '; }
for(int i = 1;i <= 10; i++){ System.out.print(i); if(i % 5 == 0){ System.out.println(); continue; } System.out.print(", "); }
Translate this program into Java but keep the logic exactly as in PHP.
for ($i = 1; $i <= 10; $i++) { echo $i; if ($i % 5 == 0) { echo "\n"; continue; } echo ', '; }
for(int i = 1;i <= 10; i++){ System.out.print(i); if(i % 5 == 0){ System.out.println(); continue; } System.out.print(", "); }
Maintain the same structure and functionality when rewriting this code in Java.
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
Convert this PHP snippet to Java and keep its semantics consistent.
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
Rewrite this program in Java while keeping its functionality equivalent to the PHP version.
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
Write the same code in Java as shown below in PHP.
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
Keep all operations the same but rewrite the snippet in Java.
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; } ?>
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
Change the programming language of this snippet from PHP to Java without modifying what it does.
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; } ?>
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
Write a version of this PHP function in Java with identical behavior.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
Keep all operations the same but rewrite the snippet in Java.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
Port the following code from PHP to Java with equivalent syntax and logic.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
Convert this PHP snippet to Java and keep its semantics consistent.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
Ensure the translated Java code behaves exactly like the original PHP snippet.
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
Please provide an equivalent version of this PHP code in Java.
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
Rewrite this program in Java while keeping its functionality equivalent to the PHP version.
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
Translate this program into Java but keep the logic exactly as in PHP.
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
Rewrite this program in Java while keeping its functionality equivalent to the PHP version.
$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("äàâáçñßæεбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
Port the following code from PHP to Java with equivalent syntax and logic.
$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("äàâáçñßæεбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
Keep all operations the same but rewrite the snippet in Java.
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digester { public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); } static String hexDigest(String str, String digestName) { try { MessageDigest md = MessageDigest.getInstance(digestName); byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8)); char[] hex = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4); hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f); } return new String(hex); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
Ensure the translated Java code behaves exactly like the original PHP snippet.
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digester { public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); } static String hexDigest(String str, String digestName) { try { MessageDigest md = MessageDigest.getInstance(digestName); byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8)); char[] hex = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4); hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f); } return new String(hex); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
Translate the given PHP code snippet into Java without altering its behavior.
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
import java.time.*; import java.time.format.*; class Main { public static void main(String args[]) { String dateStr = "March 7 2009 7:30pm EST"; DateTimeFormatter df = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("MMMM d yyyy h:mma zzz") .toFormatter(); ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12); System.out.println("Date: " + dateStr); System.out.println("+12h: " + after12Hours.format(df)); ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET")); System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df)); } }
Rewrite the snippet below in Java so it works the same as the original PHP code.
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
import java.time.*; import java.time.format.*; class Main { public static void main(String args[]) { String dateStr = "March 7 2009 7:30pm EST"; DateTimeFormatter df = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("MMMM d yyyy h:mma zzz") .toFormatter(); ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12); System.out.println("Date: " + dateStr); System.out.println("+12h: " + after12Hours.format(df)); ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET")); System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df)); } }
Generate an equivalent Java version of this PHP code.
<?php $buffer = 1; $pids = []; for ($i = 1; $i < $argc; $i++) { $pid = pcntl_fork(); if ($pid < 0) { die("failed to start child process"); } if ($pid === 0) { sleep($argv[$i] + $buffer); echo $argv[$i] . "\n"; exit(); } $pids[] = $pid; } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); }
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await(); Thread.sleep(num * 1000); System.out.println(num); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { int[] nums = new int[args.length]; for (int i = 0; i < args.length; i++) nums[i] = Integer.parseInt(args[i]); sleepSortAndPrint(nums); } }
Change the following PHP code into Java without altering its purpose.
<?php $buffer = 1; $pids = []; for ($i = 1; $i < $argc; $i++) { $pid = pcntl_fork(); if ($pid < 0) { die("failed to start child process"); } if ($pid === 0) { sleep($argv[$i] + $buffer); echo $argv[$i] . "\n"; exit(); } $pids[] = $pid; } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); }
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await(); Thread.sleep(num * 1000); System.out.println(num); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { int[] nums = new int[args.length]; for (int i = 0; i < args.length; i++) nums[i] = Integer.parseInt(args[i]); sleepSortAndPrint(nums); } }
Preserve the algorithm and functionality while converting the code from PHP to Java.
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\n"; ?>
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
Convert this PHP block to Java, preserving its control flow and logic.
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\n"; ?>
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
Ensure the translated Java code behaves exactly like the original PHP snippet.
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Produce a functionally identical Java code for the snippet given in PHP.
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Produce a functionally identical Java code for the snippet given in PHP.
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Convert this PHP snippet to Java and keep its semantics consistent.
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
Write the same algorithm in Java as shown in this PHP implementation.
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
Keep all operations the same but rewrite the snippet in Java.
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
Translate the given PHP code snippet into Java without altering its behavior.
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
Transform the following PHP implementation into Java, maintaining the same output and logic.
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
Produce a functionally identical Java code for the snippet given in PHP.
$stack = array(); empty( $stack ); // true array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2; empty( $stack ); // false echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
Keep all operations the same but rewrite the snippet in Java.
$stack = array(); empty( $stack ); // true array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2; empty( $stack ); // false echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
Keep all operations the same but rewrite the snippet in Java.
<?php $foo = 3; if ($foo == 2) if ($foo == 3) else if ($foo != 0) { } else { } ?>
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
Preserve the algorithm and functionality while converting the code from PHP to Java.
<?php $foo = 3; if ($foo == 2) if ($foo == 3) else if ($foo != 0) { } else { } ?>
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
Produce a functionally identical Java code for the snippet given in PHP.
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
import java.util.Arrays; public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); } public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1); } public static void stoogeSort(int[] L, int i, int j) { if (L[j] < L[i]) { int tmp = L[i]; L[i] = L[j]; L[j] = tmp; } if (j - i > 1) { int t = (j - i + 1) / 3; stoogeSort(L, i, j - t); stoogeSort(L, i + t, j); stoogeSort(L, i, j - t); } } }