Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this Python code in Java.
def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else []
public class NonContinuousSubsequences { public static void main(String args[]) { seqR("1234", "", 0, 0); } private static void seqR(String s, String c, int i, int added) { if (i == s.length()) { if (c.trim().length() > added) System.out.println(c); } else { seqR(s, c + s.charAt(i), i + 1, added + 1); seqR(s, c + ' ', i + 1, added); } } }
Maintain the same structure and functionality when rewriting this code in Java.
from functools import wraps from turtle import * def memoize(obj): cache = obj.cache = {} @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer @memoize def fibonacci_word(n): assert n > 0 if n == 1: return "1" if n == 2: return "0" return fibonacci_word(n - 1) + fibonacci_word(n - 2) def draw_fractal(word, step): for i, c in enumerate(word, 1): forward(step) if c == "0": if i % 2 == 0: left(90) else: right(90) def main(): n = 25 step = 1 width = 1050 height = 1050 w = fibonacci_word(n) setup(width=width, height=height) speed(0) setheading(90) left(90) penup() forward(500) right(90) backward(500) pendown() tracer(10000) hideturtle() draw_fractal(w, step) getscreen().getcanvas().postscript(file="fibonacci_word_fractal.eps") exitonclick() if __name__ == '__main__': main()
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n) { if (n < 2) return n == 1 ? "1" : ""; StringBuilder f1 = new StringBuilder("1"); StringBuilder f2 = new StringBuilder("0"); for (n = n - 2; n > 0; n--) { String tmp = f2.toString(); f2.append(f1); f1.setLength(0); f1.append(tmp); } return f2.toString(); } void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) { for (int n = 0; n < wordFractal.length(); n++) { g.drawLine(x, y, x + dx, y + dy); x += dx; y += dy; if (wordFractal.charAt(n) == '0') { int tx = dx; dx = (n % 2 == 0) ? -dy : dy; dy = (n % 2 == 0) ? tx : -tx; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawWordFractal(g, 20, 20, 1, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Fibonacci Word Fractal"); f.setResizable(false); f.add(new FibonacciWordFractal(23), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Rewrite the snippet below in Java so it works the same as the original Python code.
primes = [2, 3, 5, 7, 11, 13, 17, 19] def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1 while reasonable_limit < limit: ram_limit = primes[-1] + 90000000 - len(primes) if ram_limit > primes[-1]: reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) else: reasonable_limit = min(limit, primes[-1] ** 2) sieve = list({x for prime in primes for x in range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)}) primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit] count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y]) return count def test(limit: int): count = count_twin_primes(limit) print(f"Number of twin prime pairs less than {limit} is {count}\n") test(10) test(100) test(1000) test(10000) test(100000) test(1000000) test(10000000) test(100000000)
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
Maintain the same structure and functionality when rewriting this code in Java.
import cmath class Complex(complex): def __repr__(self): rp = '%7.5f' % self.real if not self.pureImag() else '' ip = '%7.5fj' % self.imag if not self.pureReal() else '' conj = '' if ( self.pureImag() or self.pureReal() or self.imag < 0.0 ) else '+' return '0.0' if ( self.pureImag() and self.pureReal() ) else rp + conj + ip def pureImag(self): return abs(self.real) < 0.000005 def pureReal(self): return abs(self.imag) < 0.000005 def croots(n): if n <= 0: return None return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n)) for nr in range(2, 11): print(nr, list(croots(nr)))
import java.util.Locale; public class Test { public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); } public static void unity(int n) { System.out.printf("%n%d: ", n); for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) { double real = Math.cos(angle); if (Math.abs(real) < 1.0E-3) real = 0.0; double imag = Math.sin(angle); if (Math.abs(imag) < 1.0E-3) imag = 0.0; System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
Produce a functionally identical Java code for the snippet given in Python.
print 2**64*2**64
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
Rewrite the snippet below in Java so it works the same as the original Python code.
import math def solvePell(n): x = int(math.sqrt(n)) y, z, r = x, 1, x << 1 e1, e2 = 1, 0 f1, f2 = 0, 1 while True: y = r * z - y z = (n - y * y) // z r = (x + y) // z e1, e2 = e2, e1 + e2 * r f1, f2 = f2, f1 + f2 * r a, b = f2 * x + e2, f2 if a * a - n * b * b == 1: return a, b for n in [61, 109, 181, 277]: x, y = solvePell(n) print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PellsEquation { public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } } private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } } private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b; while ( true ) { int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; } private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; } }
Please provide an equivalent version of this Python code in Java.
import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) print % (size, size) guesses = 0 while True: guesses += 1 while True: guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen: print '\nCongratulations you guessed correctly in',guesses,'attempts' break bulls = cows = 0 for i in range(size): if guess[i] == chosen[i]: bulls += 1 elif guess[i] in chosen: cows += 1 print ' %i Bulls\n %i Cows' % (bulls, cows)
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); } public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
Rewrite this program in Java while keeping its functionality equivalent to the Python version.
def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return seq if __name__ == "__main__": from random import shuffle testset = [_ for _ in range(100)] testcase = testset.copy() shuffle(testcase) assert testcase != testset bubble_sort(testcase) assert testcase == testset
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
Maintain the same structure and functionality when rewriting this code in Java.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for n in range(1,51)])
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
Write the same code in Java as shown below in Python.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for n in range(1,51)])
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
Change the following Python code into Java without altering its purpose.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for n in range(1,51)])
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
Preserve the algorithm and functionality while converting the code from Python to Java.
import shutil shutil.copyfile('input.txt', 'output.txt')
import java.io.*; public class FileIODemo { public static void main(String[] args) { try { FileInputStream in = new FileInputStream("input.txt"); FileOutputStream out = new FileOutputStream("ouput.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } }
Can you help me rewrite this code in Java instead of Python, keeping it the same logically?
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: ")) print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) print "Remainder: %d" % (x % y) print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y raw_input( )
import java.util.Scanner; public class IntegerArithmetic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int sum = a + b; int difference = a - b; int product = a * b; int division = a / b; int remainder = a % b; System.out.println("a + b = " + sum); System.out.println("a - b = " + difference); System.out.println("a * b = " + product); System.out.println("quotient of a / b = " + division); System.out.println("remainder of a / b = " + remainder); } }
Write the same algorithm in Java as shown in this Python implementation.
m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625)) print(zip(*m))
import java.util.Arrays; public class Transpose{ public static void main(String[] args){ double[][] m = {{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}, {5, 25, 125, 625}}; double[][] ans = new double[m[0].length][m.length]; for(int rows = 0; rows < m.length; rows++){ for(int cols = 0; cols < m[0].length; cols++){ ans[cols][rows] = m[rows][cols]; } } for(double[] i:ans){ System.out.println(Arrays.toString(i)); } } }
Write the same code in Java as shown below in Python.
import sys sys.setrecursionlimit(1025) def a(in_k, x1, x2, x3, x4, x5): k = [in_k] def b(): k[0] -= 1 return a(k[0], b, x1, x2, x3, x4) return x4() + x5() if k[0] <= 0 else b() x = lambda i: lambda: i print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
import java.util.function.DoubleSupplier; public class ManOrBoy { static double A(int k, DoubleSupplier x1, DoubleSupplier x2, DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) { DoubleSupplier B = new DoubleSupplier() { int m = k; public double getAsDouble() { return A(--m, this, x1, x2, x3, x4); } }; return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble(); } public static void main(String[] args) { System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0)); } }
Please provide an equivalent version of this Python code in Java.
>>> def a(answer): print(" return answer >>> def b(answer): print(" return answer >>> for i in (False, True): for j in (False, True): print ("\nCalculating: x = a(i) and b(j)") x = a(i) and b(j) print ("Calculating: y = a(i) or b(j)") y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j)
module test { @Inject Console console; static Boolean show(String name, Boolean value) { console.print($"{name}()={value}"); return value; } void run() { val a = show("a", _); val b = show("b", _); for (Boolean v1 : False..True) { for (Boolean v2 : False..True) { console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}"); console.print(); console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}"); console.print(); } } } }
Write a version of this Python function in Java with identical behavior.
>>> def a(answer): print(" return answer >>> def b(answer): print(" return answer >>> for i in (False, True): for j in (False, True): print ("\nCalculating: x = a(i) and b(j)") x = a(i) and b(j) print ("Calculating: y = a(i) or b(j)") y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j)
module test { @Inject Console console; static Boolean show(String name, Boolean value) { console.print($"{name}()={value}"); return value; } void run() { val a = show("a", _); val b = show("b", _); for (Boolean v1 : False..True) { for (Boolean v2 : False..True) { console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}"); console.print(); console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}"); console.print(); } } } }
Write the same algorithm in Java as shown in this Python implementation.
import sys print(sys.getrecursionlimit())
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
Port the following code from Python to Java with equivalent syntax and logic.
import sys print(sys.getrecursionlimit())
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
Please provide an equivalent version of this Python code in Java.
class Isprime(): multiples = {2} primes = [2] nmax = 2 def __init__(self, nmax): if nmax > self.nmax: self.check(nmax) def check(self, n): if type(n) == float: if not n.is_integer(): return False n = int(n) multiples = self.multiples if n <= self.nmax: return n not in multiples else: primes, nmax = self.primes, self.nmax newmax = max(nmax*2, n) for p in primes: multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p)) for i in range(nmax+1, newmax+1): if i not in multiples: primes.append(i) multiples.update(range(i*2, newmax+1, i)) self.nmax = newmax return n not in multiples __call__ = check def carmichael(p1): ans = [] if isprime(p1): for h3 in range(2, p1): g = h3 + p1 for d in range(1, g): if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3: p2 = 1 + ((p1 - 1)* g // d) if isprime(p2): p3 = 1 + (p1 * p2 // h3) if isprime(p3): if (p2 * p3) % (p1 - 1) == 1: ans += [tuple(sorted((p1, p2, p3)))] return ans isprime = Isprime(2) ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), [])) print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
public class Test { static int mod(int n, int m) { return ((n % m) + m) % m; } static boolean isPrime(int n) { if (n == 2 || n == 3) return true; else if (n < 2 || n % 2 == 0 || n % 3 == 0) return false; for (int div = 5, inc = 2; Math.pow(div, 2) <= n; div += inc, inc = 6 - inc) if (n % div == 0) return false; return true; } public static void main(String[] args) { for (int p = 2; p < 62; p++) { if (!isPrime(p)) continue; for (int h3 = 2; h3 < p; h3++) { int g = h3 + p; for (int d = 1; d < g; d++) { if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3) continue; int q = 1 + (p - 1) * g / d; if (!isPrime(q)) continue; int r = 1 + (p * q / h3); if (!isPrime(r) || (q * r) % (p - 1) != 1) continue; System.out.printf("%d x %d x %d%n", p, q, r); } } } } }
Change the following Python code into Java without altering its purpose.
black = color(0) white = color(255) def setup(): size(320, 240) def draw(): loadPixels() for i in range(len(pixels)): if random(1) < 0.5: pixels[i] = black else: pixels[i] = white updatePixels() fill(0, 128) rect(0, 0, 60, 20) fill(255) text(frameRate, 5, 15)
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.util.Arrays; import java.util.Random; import javax.swing.*; public class ImageNoise { int framecount = 0; int fps = 0; BufferedImage image; Kernel kernel; ConvolveOp cop; JFrame frame = new JFrame("Java Image Noise"); JPanel panel = new JPanel() { private int show_fps = 0; private MouseAdapter ma = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { show_fps = (show_fps + 1) % 3; } }; {addMouseListener(ma);} @Override public Dimension getPreferredSize() { return new Dimension(320, 240); } @Override @SuppressWarnings("fallthrough") public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; drawNoise(); g.drawImage(image, 0, 0, null); switch (show_fps) { case 0: int xblur = getWidth() - 130, yblur = getHeight() - 32; BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32); BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(), BufferedImage.TYPE_BYTE_GRAY); cop.filter(bc, bs); g.drawImage(bs, xblur, yblur , null); case 1: g.setColor(Color.RED); g.setFont(new Font("Monospaced", Font.BOLD, 20)); g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10); } framecount++; } }; Timer repainter = new Timer(1, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.repaint(); } }); Timer framerateChecker = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fps = framecount; framecount = 0; } }); public ImageNoise() { float[] vals = new float[121]; Arrays.fill(vals, 1/121f); kernel = new Kernel(11, 11, vals); cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); repainter.start(); framerateChecker.start(); } void drawNoise() { int w = panel.getWidth(), h = panel.getHeight(); if (null == image || image.getWidth() != w || image.getHeight() != h) { image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); } Random rand = new Random(); int[] data = new int[w * h]; for (int x = 0; x < w * h / 32; x++) { int r = rand.nextInt(); for (int i = 0; i < 32; i++) { data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE; r >>>= 1; } } image.getRaster().setPixels(0, 0, w, h, data); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ImageNoise i = new ImageNoise(); } }); } }
Convert this Python snippet to Java and keep its semantics consistent.
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
public static boolean perf(int n){ int sum= 0; for(int i= 1;i < n;i++){ if(n % i == 0){ sum+= i; } } return sum == n; }
Convert this Python snippet to Java and keep its semantics consistent.
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
public class BeadSort { public static void main(String[] args) { BeadSort now=new BeadSort(); int[] arr=new int[(int)(Math.random()*11)+5]; for(int i=0;i<arr.length;i++) arr[i]=(int)(Math.random()*10); System.out.print("Unsorted: "); now.display1D(arr); int[] sort=now.beadSort(arr); System.out.print("Sorted: "); now.display1D(sort); } int[] beadSort(int[] arr) { int max=a[0]; for(int i=1;i<arr.length;i++) if(arr[i]>max) max=arr[i]; char[][] grid=new char[arr.length][max]; int[] levelcount=new int[max]; for(int i=0;i<max;i++) { levelcount[i]=0; for(int j=0;j<arr.length;j++) grid[j][i]='_'; } for(int i=0;i<arr.length;i++) { int num=arr[i]; for(int j=0;num>0;j++) { grid[levelcount[j]++][j]='*'; num--; } } System.out.println(); display2D(grid); int[] sorted=new int[arr.length]; for(int i=0;i<arr.length;i++) { int putt=0; for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++) putt++; sorted[i]=putt; } return sorted; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display1D(char[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display2D(char[][] arr) { for(int i=0;i<arr.length;i++) display1D(arr[i]); System.out.println(); } }
Preserve the algorithm and functionality while converting the code from Python to Java.
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
Please provide an equivalent version of this Python code in Java.
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
Translate the given Python code snippet into Java without altering its behavior.
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
import java.math.BigInteger; class IntegerPower { public static void main(String[] args) { BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact()); String str = power.toString(); int len = str.length(); System.out.printf("5**4**3**2 = %s...%s and has %d digits%n", str.substring(0, 20), str.substring(len - 20), len); } }
Produce a language-to-language conversion: from Python to Java, same semantics.
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
Convert this Python snippet to Java and keep its semantics consistent.
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
Write the same code in Java as shown below in Python.
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
package org.rosettacode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class InvertedIndex { List<String> stopwords = Arrays.asList("a", "able", "about", "across", "after", "all", "almost", "also", "am", "among", "an", "and", "any", "are", "as", "at", "be", "because", "been", "but", "by", "can", "cannot", "could", "dear", "did", "do", "does", "either", "else", "ever", "every", "for", "from", "get", "got", "had", "has", "have", "he", "her", "hers", "him", "his", "how", "however", "i", "if", "in", "into", "is", "it", "its", "just", "least", "let", "like", "likely", "may", "me", "might", "most", "must", "my", "neither", "no", "nor", "not", "of", "off", "often", "on", "only", "or", "other", "our", "own", "rather", "said", "say", "says", "she", "should", "since", "so", "some", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "tis", "to", "too", "twas", "us", "wants", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "would", "yet", "you", "your"); Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>(); List<String> files = new ArrayList<String>(); public void indexFile(File file) throws IOException { int fileno = files.indexOf(file.getPath()); if (fileno == -1) { files.add(file.getPath()); fileno = files.size() - 1; } int pos = 0; BufferedReader reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader .readLine()) { for (String _word : line.split("\\W+")) { String word = _word.toLowerCase(); pos++; if (stopwords.contains(word)) continue; List<Tuple> idx = index.get(word); if (idx == null) { idx = new LinkedList<Tuple>(); index.put(word, idx); } idx.add(new Tuple(fileno, pos)); } } System.out.println("indexed " + file.getPath() + " " + pos + " words"); } public void search(List<String> words) { for (String _word : words) { Set<String> answer = new HashSet<String>(); String word = _word.toLowerCase(); List<Tuple> idx = index.get(word); if (idx != null) { for (Tuple t : idx) { answer.add(files.get(t.fileno)); } } System.out.print(word); for (String f : answer) { System.out.print(" " + f); } System.out.println(""); } } public static void main(String[] args) { try { InvertedIndex idx = new InvertedIndex(); for (int i = 1; i < args.length; i++) { idx.indexFile(new File(args[i])); } idx.search(Arrays.asList(args[0].split(","))); } catch (Exception e) { e.printStackTrace(); } } private class Tuple { private int fileno; private int position; public Tuple(int fileno, int position) { this.fileno = fileno; this.position = position; } } }
Ensure the translated Java code behaves exactly like the original Python snippet.
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Produce a language-to-language conversion: from Python to Java, same semantics.
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Write the same algorithm in Java as shown in this Python implementation.
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print("First 10 Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 print("F{} = {}".format(chr(i + 0x2080) , fermat)) print("\nFactors of first few Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 fac = factors(fermat) if len(fac) == 1: print("F{} -> IS PRIME".format(chr(i + 0x2080))) else: print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac))
import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class FermatNumbers { public static void main(String[] args) { System.out.println("First 10 Fermat numbers:"); for ( int i = 0 ; i < 10 ; i++ ) { System.out.printf("F[%d] = %s\n", i, fermat(i)); } System.out.printf("%nFirst 12 Fermat numbers factored:%n"); for ( int i = 0 ; i < 13 ; i++ ) { System.out.printf("F[%d] = %s\n", i, getString(getFactors(i, fermat(i)))); } } private static String getString(List<BigInteger> factors) { if ( factors.size() == 1 ) { return factors.get(0) + " (PRIME)"; } return factors.stream().map(v -> v.toString()).map(v -> v.startsWith("-") ? "(C" + v.replace("-", "") + ")" : v).collect(Collectors.joining(" * ")); } private static Map<Integer, String> COMPOSITE = new HashMap<>(); static { COMPOSITE.put(9, "5529"); COMPOSITE.put(10, "6078"); COMPOSITE.put(11, "1037"); COMPOSITE.put(12, "5488"); COMPOSITE.put(13, "2884"); } private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) { List<BigInteger> factors = new ArrayList<>(); BigInteger factor = BigInteger.ONE; while ( true ) { if ( n.isProbablePrime(100) ) { factors.add(n); break; } else { if ( COMPOSITE.containsKey(fermatIndex) ) { String stop = COMPOSITE.get(fermatIndex); if ( n.toString().startsWith(stop) ) { factors.add(new BigInteger("-" + n.toString().length())); break; } } factor = pollardRhoFast(n); if ( factor.compareTo(BigInteger.ZERO) == 0 ) { factors.add(n); break; } else { factors.add(factor); n = n.divide(factor); } } } return factors; } private static final BigInteger TWO = BigInteger.valueOf(2); private static BigInteger fermat(int n) { return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE); } @SuppressWarnings("unused") private static BigInteger pollardRho(BigInteger n) { BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; while ( d.compareTo(BigInteger.ONE) == 0 ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs().gcd(n); } if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoFast(BigInteger n) { long start = System.currentTimeMillis(); BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; int count = 0; BigInteger z = BigInteger.ONE; while ( true ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs(); z = z.multiply(d).mod(n); count++; if ( count == 100 ) { d = z.gcd(n); if ( d.compareTo(BigInteger.ONE) != 0 ) { break; } z = BigInteger.ONE; count = 0; } } long end = System.currentTimeMillis(); System.out.printf(" Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n", n, (end-start), d); if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoG(BigInteger x, BigInteger n) { return x.multiply(x).add(BigInteger.ONE).mod(n); } }
Change the following Python code into Java without altering its purpose.
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
import java.util.Random; Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
Translate the given Python code snippet into Java without altering its behavior.
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Rewrite this program in Java while keeping its functionality equivalent to the Python version.
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Port the following code from Python to Java with equivalent syntax and logic.
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print("highest_left: ", highest_left) print("highest_right: ", highest_right) print("water_level: ", water_level) print("tower_level: ", tower) print("total_water: ", sum(water_level)) print("") return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
public class WaterBetweenTowers { public static void main(String[] args) { int i = 1; int[][] tba = new int[][]{ new int[]{1, 5, 3, 7, 2}, new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, new int[]{5, 5, 5, 5}, new int[]{5, 6, 7, 8}, new int[]{8, 7, 7, 6}, new int[]{6, 7, 10, 7, 6} }; for (int[] tea : tba) { int rht, wu = 0, bof; do { for (rht = tea.length - 1; rht >= 0; rht--) { if (tea[rht] > 0) { break; } } if (rht < 0) { break; } bof = 0; for (int col = 0; col <= rht; col++) { if (tea[col] > 0) { tea[col]--; bof += 1; } else if (bof > 0) { wu++; } } if (bof < 2) { break; } } while (true); System.out.printf("Block %d", i++); if (wu == 0) { System.out.print(" does not hold any"); } else { System.out.printf(" holds %d", wu); } System.out.println(" water units."); } } }
Maintain the same structure and functionality when rewriting this code in Java.
import math def SquareFree ( _number ) : max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number % ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( "{}\t".format(i), end="" ) count += 1 print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count)) ListSquareFrees( 1, 100 ) ListSquareFrees( 1000000000000, 1000000000145 )
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long p2 = p * p; if (p2 > limit) break; for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true; for (;;) { p += 2; if (!c[(int)p]) break; } } for (long i = 3; i <= limit; i += 2) { if (!c[(int)i]) primes.add(i); } return primes; } private static List<Long> squareFree(long from, long to) { long limit = (long)Math.sqrt((double)to); List<Long> primes = sieve(limit); List<Long> results = new ArrayList<Long>(); outer: for (long i = from; i <= to; i++) { for (long p : primes) { long p2 = p * p; if (p2 > i) break; if (i % p2 == 0) continue outer; } results.add(i); } return results; } private final static long TRILLION = 1000000000000L; public static void main(String[] args) { System.out.println("Square-free integers from 1 to 145:"); List<Long> sf = squareFree(1, 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 20 == 0) { System.out.println(); } System.out.printf("%4d", sf.get(i)); } System.out.print("\n\nSquare-free integers"); System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145); sf = squareFree(TRILLION, TRILLION + 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 5 == 0) System.out.println(); System.out.printf("%14d", sf.get(i)); } System.out.println("\n\nNumber of square-free integers:\n"); long[] tos = {100, 1000, 10000, 100000, 1000000}; for (long to : tos) { System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size()); } } }
Convert the following code from Python to Java, ensuring the logic remains intact.
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in range(s_len): start = max(0, i - match_distance) end = min(i + match_distance + 1, t_len) for j in range(start, end): if t_matches[j]: continue if s[i] != t[j]: continue s_matches[i] = True t_matches[j] = True matches += 1 break if matches == 0: return 0 k = 0 for i in range(s_len): if not s_matches[i]: continue while not t_matches[k]: k += 1 if s[i] != t[k]: transpositions += 1 k += 1 return ((matches / s_len) + (matches / t_len) + ((matches - transpositions / 2) / matches)) / 3 def main(): for s, t in [('MARTHA', 'MARHTA'), ('DIXON', 'DICKSONX'), ('JELLYFISH', 'SMELLYFISH')]: print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t))) if __name__ == '__main__': main()
public class JaroDistance { public static double jaro(String s, String t) { int s_len = s.length(); int t_len = t.length(); if (s_len == 0 && t_len == 0) return 1; int match_distance = Integer.max(s_len, t_len) / 2 - 1; boolean[] s_matches = new boolean[s_len]; boolean[] t_matches = new boolean[t_len]; int matches = 0; int transpositions = 0; for (int i = 0; i < s_len; i++) { int start = Integer.max(0, i-match_distance); int end = Integer.min(i+match_distance+1, t_len); for (int j = start; j < end; j++) { if (t_matches[j]) continue; if (s.charAt(i) != t.charAt(j)) continue; s_matches[i] = true; t_matches[j] = true; matches++; break; } } if (matches == 0) return 0; int k = 0; for (int i = 0; i < s_len; i++) { if (!s_matches[i]) continue; while (!t_matches[k]) k++; if (s.charAt(i) != t.charAt(k)) transpositions++; k++; } return (((double)matches / s_len) + ((double)matches / t_len) + (((double)matches - transpositions/2.0) / matches)) / 3.0; } public static void main(String[] args) { System.out.println(jaro( "MARTHA", "MARHTA")); System.out.println(jaro( "DIXON", "DICKSONX")); System.out.println(jaro("JELLYFISH", "SMELLYFISH")); } }
Produce a functionally identical Java code for the snippet given in Python.
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))] product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1] sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1] print(final_pairs)
package org.rosettacode; import java.util.ArrayList; import java.util.List; public class SumAndProductPuzzle { private final long beginning; private final int maxSum; private static final int MIN_VALUE = 2; private List<int[]> firstConditionExcludes = new ArrayList<>(); private List<int[]> secondConditionExcludes = new ArrayList<>(); public static void main(String... args){ if (args.length == 0){ new SumAndProductPuzzle(100).run(); new SumAndProductPuzzle(1684).run(); new SumAndProductPuzzle(1685).run(); } else { for (String arg : args){ try{ new SumAndProductPuzzle(Integer.valueOf(arg)).run(); } catch (NumberFormatException e){ System.out.println("Please provide only integer arguments. " + "Provided argument " + arg + " was not an integer. " + "Alternatively, calling the program with no arguments " + "will run the puzzle where maximum sum equals 100, 1684, and 1865."); } } } } public SumAndProductPuzzle(int maxSum){ this.beginning = System.currentTimeMillis(); this.maxSum = maxSum; System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " started at " + String.valueOf(beginning) + "."); } public void run(){ for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){ for (int y = x + 1; y < maxSum - MIN_VALUE; y++){ if (isSumNoGreaterThanMax(x,y) && isSKnowsPCannotKnow(x,y) && isPKnowsNow(x,y) && isSKnowsNow(x,y) ){ System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) + " in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } } } System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } public boolean isSumNoGreaterThanMax(int x, int y){ return x + y <= maxSum; } public boolean isSKnowsPCannotKnow(int x, int y){ if (firstConditionExcludes.contains(new int[] {x, y})){ return false; } for (int[] addends : sumAddends(x, y)){ if ( !(productFactors(addends[0], addends[1]).size() > 1) ) { firstConditionExcludes.add(new int[] {x, y}); return false; } } return true; } public boolean isPKnowsNow(int x, int y){ if (secondConditionExcludes.contains(new int[] {x, y})){ return false; } int countSolutions = 0; for (int[] factors : productFactors(x, y)){ if (isSKnowsPCannotKnow(factors[0], factors[1])){ countSolutions++; } } if (countSolutions == 1){ return true; } else { secondConditionExcludes.add(new int[] {x, y}); return false; } } public boolean isSKnowsNow(int x, int y){ int countSolutions = 0; for (int[] addends : sumAddends(x, y)){ if (isPKnowsNow(addends[0], addends[1])){ countSolutions++; } } return countSolutions == 1; } public List<int[]> sumAddends(int x, int y){ List<int[]> list = new ArrayList<>(); int sum = x + y; for (int addend = MIN_VALUE; addend < sum - addend; addend++){ if (isSumNoGreaterThanMax(addend, sum - addend)){ list.add(new int[]{addend, sum - addend}); } } return list; } public List<int[]> productFactors(int x, int y){ List<int[]> list = new ArrayList<>(); int product = x * y; for (int factor = MIN_VALUE; factor < product / factor; factor++){ if (product % factor == 0){ if (isSumNoGreaterThanMax(factor, product / factor)){ list.add(new int[]{factor, product / factor}); } } } return list; } }
Translate the given Python code snippet into Java without altering its behavior.
from itertools import count, islice def _basechange_int(num, b): if num == 0: return [0] result = [] while num != 0: num, d = divmod(num, b) result.append(d) return result[::-1] def fairshare(b=2): for i in count(): yield sum(_basechange_int(i, b)) % b if __name__ == '__main__': for b in (2, 3, 5, 11): print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } } private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) { sum += n % base; n /= base; } sequence.add(sum % base); } return sequence; } }
Preserve the algorithm and functionality while converting the code from Python to Java.
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) sb.append(ops.charAt(s.pop())).append(' '); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); } else { sb.append(token).append(' '); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())).append(' '); return sb.toString(); } }
Rewrite this program in Java while keeping its functionality equivalent to the Python version.
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
import java.util.*; import java.io.*; public class TPKA { public static void main(String... args) { double[] input = new double[11]; double userInput = 0.0; Scanner in = new Scanner(System.in); for(int i = 0; i < 11; i++) { System.out.print("Please enter a number: "); String s = in.nextLine(); try { userInput = Double.parseDouble(s); } catch (NumberFormatException e) { System.out.println("You entered invalid input, exiting"); System.exit(1); } input[i] = userInput; } for(int j = 10; j >= 0; j--) { double x = input[j]; double y = f(x); if( y < 400.0) { System.out.printf("f( %.2f ) = %.2f\n", x, y); } else { System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE"); } } } private static double f(double x) { return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3))); } }
Convert the following code from Python to Java, ensuring the logic remains intact.
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
public class MiddleThreeDigits { public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE}; final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}; for (long n : passing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); for (int n : failing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); } public static <T> String middleThreeDigits(T n) { String s = String.valueOf(n); if (s.charAt(0) == '-') s = s.substring(1); int len = s.length(); if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; int mid = len / 2; return s.substring(mid - 1, mid + 2); } }
Convert the following code from Python to Java, ensuring the logic remains intact.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def primes(): ii = 1 while True: ii += 1 if is_prime(ii): yield ii def prime(n): generator = primes() for ii in range(n - 1): generator.__next__() return generator.__next__() def n_divisors(n): ii = 0 while True: ii += 1 if len(divisors(ii)) == n: yield ii def sequence(max_n=None): if max_n is not None: for ii in range(1, max_n + 1): if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() else: ii = 1 while True: ii += 1 if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() if __name__ == '__main__': for item in sequence(15): print(item)
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class SequenceNthNumberWithExactlyNDivisors { public static void main(String[] args) { int max = 45; smallPrimes(max); for ( int n = 1; n <= max ; n++ ) { System.out.printf("A073916(%d) = %s%n", n, OEISA073916(n)); } } private static List<Integer> smallPrimes = new ArrayList<>(); private static void smallPrimes(int numPrimes) { smallPrimes.add(2); for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) { if ( isPrime(n) ) { smallPrimes.add(n); count++; } } } private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) { return false; } for ( long d = 3 ; d*d <= test ; d += 2 ) { if ( test % d == 0 ) { return false; } } return true; } private static int getDivisorCount(long n) { int count = 1; while ( n % 2 == 0 ) { n /= 2; count += 1; } for ( long d = 3 ; d*d <= n ; d += 2 ) { long q = n / d; long r = n % d; int dc = 0; while ( r == 0 ) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if ( n != 1 ) { count *= 2; } return count; } private static BigInteger OEISA073916(int n) { if ( isPrime(n) ) { return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1); } int count = 0; int result = 0; for ( int i = 1 ; count < n ; i++ ) { if ( n % 2 == 1 ) { int sqrt = (int) Math.sqrt(i); if ( sqrt*sqrt != i ) { continue; } } if ( getDivisorCount(i) == n ) { count++; result = i; } } return BigInteger.valueOf(result); } }
Write a version of this Python function in Java with identical behavior.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break if __name__ == '__main__': for item in sequence(15): print(item)
import java.util.Arrays; public class OEIS_A005179 { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; int[] seq = new int[max]; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, n = 0; n < max; ++i) { int k = count_divisors(i); if (k <= max && seq[k - 1] == 0) { seq[k- 1] = i; n++; } } System.out.println(Arrays.toString(seq)); } }
Convert this Python block to Java, preserving its control flow and logic.
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: init_stack = tuple(range(1, n + 1)) stack_flips = {init_stack: 0} queue = deque([init_stack]) while queue: stack = queue.popleft() flips = stack_flips[stack] + 1 for i in range(2, n + 1): flipped = flip(stack, i) if flipped not in stack_flips: stack_flips[flipped] = flips queue.append(flipped) return max(stack_flips.items(), key=itemgetter(1)) if __name__ == "__main__": start = time.time() for n in range(1, 10): pancakes, p = pancake(n) print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}") print(f"\nTook {time.time() - start:.3} seconds.")
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; } public static void main(String[] args) { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = 5 * i + j; System.out.printf("p(%2d) = %2d ", n, pancake(n)); } System.out.println(); } } }
Translate this program into Java but keep the logic exactly as in Python.
import random board = [[" " for x in range(8)] for y in range(8)] piece_list = ["R", "N", "B", "Q", "P"] def place_kings(brd): while True: rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7) diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)] if sum(diff_list) > 2 or set(diff_list) == set([0, 2]): brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k" break def populate_board(brd, wp, bp): for x in range(2): if x == 0: piece_amount = wp pieces = piece_list else: piece_amount = bp pieces = [s.lower() for s in piece_list] while piece_amount != 0: piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7) piece = random.choice(pieces) if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False: brd[piece_rank][piece_file] = piece piece_amount -= 1 def fen_from_board(brd): fen = "" for x in brd: n = 0 for y in x: if y == " ": n += 1 else: if n != 0: fen += str(n) fen += y n = 0 if n != 0: fen += str(n) fen += "/" if fen.count("/") < 7 else "" fen += " w - - 0 1\n" return fen def pawn_on_promotion_square(pc, pr): if pc == "P" and pr == 0: return True elif pc == "p" and pr == 7: return True return False def start(): piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15) place_kings(board) populate_board(board, piece_amount_white, piece_amount_black) print(fen_from_board(board)) for x in board: print(x) start()
import static java.lang.Math.abs; import java.util.Random; public class Fen { static Random rand = new Random(); public static void main(String[] args) { System.out.println(createFen()); } static String createFen() { char[][] grid = new char[8][8]; placeKings(grid); placePieces(grid, "PPPPPPPP", true); placePieces(grid, "pppppppp", true); placePieces(grid, "RNBQBNR", false); placePieces(grid, "rnbqbnr", false); return toFen(grid); } static void placeKings(char[][] grid) { int r1, c1, r2, c2; while (true) { r1 = rand.nextInt(8); c1 = rand.nextInt(8); r2 = rand.nextInt(8); c2 = rand.nextInt(8); if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) break; } grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; } static void placePieces(char[][] grid, String pieces, boolean isPawn) { int numToPlace = rand.nextInt(pieces.length()); for (int n = 0; n < numToPlace; n++) { int r, c; do { r = rand.nextInt(8); c = rand.nextInt(8); } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces.charAt(n); } } static String toFen(char[][] grid) { StringBuilder fen = new StringBuilder(); int countEmpty = 0; for (int r = 0; r < 8; r++) { for (int c = 0; c < 8; c++) { char ch = grid[r][c]; System.out.printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append(ch); } } if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append("/"); System.out.println(); } return fen.append(" w - - 0 1").toString(); } }
Generate a Java translation of this Python snippet without changing its computational steps.
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str def esthetic_nums(base: int) -> Iterator[int]: queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) while True: num, lsd = queue.pop() yield num new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base) num *= base queue.extendleft((num + d, d) for d in new_lsds) def to_digits(num: int, base: int) -> Digits: digits: list[str] = [] while num: num, d = divmod(num, base) digits.append("0123456789abcdef"[d]) return "".join(reversed(digits)) if digits else "0" def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None: joined = ", ".join(it) lines = wrap(joined, width=width - indent) for line in lines: print(f"{indent*' '}{line}") print() def task_2() -> None: nums: Iterator[int] for base in range(2, 16 + 1): start, stop = 4 * base, 6 * base nums = esthetic_nums(base) nums = islice(nums, start - 1, stop) print( f"Base-{base} esthetic numbers from " f"index {start} through index {stop} inclusive:\n" ) pprint_it(to_digits(num, base) for num in nums) def task_3(lower: int, upper: int, base: int = 10) -> None: nums: Iterator[int] = esthetic_nums(base) nums = dropwhile(lambda num: num < lower, nums) nums = takewhile(lambda num: num <= upper, nums) print( f"Base-{base} esthetic numbers with " f"magnitude between {lower:,} and {upper:,}:\n" ) pprint_it(to_digits(num, base) for num in nums) if __name__ == "__main__": print("======\nTask 2\n======\n") task_2() print("======\nTask 3\n======\n") task_3(1_000, 9_999) print("======\nTask 4\n======\n") task_3(100_000_000, 130_000_000)
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream; public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); } private static boolean isEsthetic(long n, long b) { if (n == 0) { return false; } var i = n % b; var n2 = n / b; while (n2 > 0) { var j = n2 % b; if (Math.abs(i - j) != 1) { return false; } n2 /= b; i = j; } return true; } private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) { var esths = new ArrayList<Long>(); var dfs = new RecTriConsumer<Long, Long, Long>() { public void accept(Long n, Long m, Long i) { accept(this, n, m, i); } @Override public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) { if (n <= i && i <= m) { esths.add(i); } if (i == 0 || i > m) { return; } var d = i % 10; var i1 = i * 10 + d - 1; var i2 = i1 + 2; if (d == 0) { f.accept(f, n, m, i2); } else if (d == 9) { f.accept(f, n, m, i1); } else { f.accept(f, n, m, i1); f.accept(f, n, m, i2); } } }; LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i)); var le = esths.size(); System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m); if (all) { for (int i = 0; i < esths.size(); i++) { System.out.printf("%d ", esths.get(i)); if ((i + 1) % perLine == 0) { System.out.println(); } } } else { for (int i = 0; i < perLine; i++) { System.out.printf("%d ", esths.get(i)); } System.out.println(); System.out.println("............"); for (int i = le - perLine; i < le; i++) { System.out.printf("%d ", esths.get(i)); } } System.out.println(); System.out.println(); } public static void main(String[] args) { IntStream.rangeClosed(2, 16).forEach(b -> { System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b); var n = 1L; var c = 0L; while (c < 6 * b) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { System.out.printf("%s ", Long.toString(n, b)); } } n++; } System.out.println(); }); System.out.println(); listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true); listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false); listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false); listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false); } }
Please provide an equivalent version of this Python code in Java.
>>> from itertools import permutations >>> def f1(p): i = 0 while True: p0 = p[0] if p0 == 1: break p[:p0] = p[:p0][::-1] i += 1 return i >>> def fannkuch(n): return max(f1(list(p)) for p in permutations(range(1, n+1))) >>> for n in range(1, 11): print(n,fannkuch(n)) 1 0 2 1 3 2 4 4 5 7 6 10 7 16 8 22 9 30 10 38 >>>
public class Topswops { static final int maxBest = 32; static int[] best; static private void trySwaps(int[] deck, int f, int d, int n) { if (d > best[n]) best[n] = d; for (int i = n - 1; i >= 0; i--) { if (deck[i] == -1 || deck[i] == i) break; if (d + best[i] <= best[n]) return; } int[] deck2 = deck.clone(); for (int i = 1; i < n; i++) { final int k = 1 << i; if (deck2[i] == -1) { if ((f & k) != 0) continue; } else if (deck2[i] != i) continue; deck2[0] = i; for (int j = i - 1; j >= 0; j--) deck2[i - j] = deck[j]; trySwaps(deck2, f | k, d + 1, n); } } static int topswops(int n) { assert(n > 0 && n < maxBest); best[n] = 0; int[] deck0 = new int[n + 1]; for (int i = 1; i < n; i++) deck0[i] = -1; trySwaps(deck0, 1, 0, n); return best[n]; } public static void main(String[] args) { best = new int[maxBest]; for (int i = 1; i < 11; i++) System.out.println(i + ": " + topswops(i)); } }
Translate the given Python code snippet into Java without altering its behavior.
from sys import argv unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445, "versta": 1066.8} if __name__ == '__main__': assert len(argv) == 3, 'ERROR. Need two arguments - number then units' try: value = float(argv[1]) except: print('ERROR. First argument must be a (float) number') raise unit = argv[2] assert unit in unit2mult, ( 'ERROR. Only know the following units: ' + ' '.join(unit2mult.keys()) ) print("%g %s to:" % (value, unit)) for unt, mlt in sorted(unit2mult.items()): print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt))
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0, 1066.8, 7467.6}; public static void main(String[] a) { if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) { double inputVal = lookup(a[1]); if (!Double.isNaN(inputVal)) { double magnitude = Double.parseDouble(a[0]); double meters = magnitude * inputVal; System.out.printf("%s %s to: %n%n", a[0], a[1]); for (String k: keys) System.out.printf("%10s: %g%n", k, meters / lookup(k)); return; } } System.out.println("Please provide a number and unit"); } public static double lookup(String key) { for (int i = 0; i < keys.length; i++) if (keys[i].equals(key)) return values[i]; return Double.NaN; } }
Preserve the algorithm and functionality while converting the code from Python to Java.
import subprocess import time class Tlogger(object): def __init__(self): self.counts = 0 self.tottime = 0.0 self.laststart = 0.0 self.lastreport = time.time() def logstart(self): self.laststart = time.time() def logend(self): self.counts +=1 self.tottime += (time.time()-self.laststart) if (time.time()-self.lastreport)>5.0: self.report() def report(self): if ( self.counts > 4*self.tottime): print "Subtask execution rate: %f times/second"% (self.counts/self.tottime); else: print "Average execution time: %f seconds"%(self.tottime/self.counts); self.lastreport = time.time() def taskTimer( n, subproc_args ): logger = Tlogger() for x in range(n): logger.logstart() p = subprocess.Popen(subproc_args) p.wait() logger.logend() logger.report() import timeit import sys def main( ): s = timer = timeit.Timer(s) rzlts = timer.repeat(5, 5000) for t in rzlts: print "Time for 5000 executions of statement = ",t print " print "Command:",sys.argv[2:] print "" for k in range(3): taskTimer( int(sys.argv[1]), sys.argv[2:]) main()
import java.util.function.Consumer; public class RateCounter { public static void main(String[] args) { for (double d : benchmark(10, x -> System.out.print(""), 10)) System.out.println(d); } static double[] benchmark(int n, Consumer<Integer> f, int arg) { double[] timings = new double[n]; for (int i = 0; i < n; i++) { long time = System.nanoTime(); f.accept(arg); timings[i] = System.nanoTime() - time; } return timings; } }
Maintain the same structure and functionality when rewriting this code in Java.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii previous = ii break if __name__ == '__main__': for item in sequence(15): print(item)
public class AntiPrimesPlus { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, next = 1; next <= max; ++i) { if (next == count_divisors(i)) { System.out.printf("%d ", i); next++; } } System.out.println(); } }
Change the following Python code into Java without altering its purpose.
def setup(): size(800, 400) background(255) stroke(0, 255, 0) tree(width / 2.3, height, width / 1.8, height, 10) def tree(x1, y1, x2, y2, depth): if depth <= 0: return dx = (x2 - x1) dy = (y1 - y2) x3 = (x2 - dy) y3 = (y2 - dx) x4 = (x1 - dy) y4 = (y1 - dx) x5 = (x4 + 0.5 * (dx - dy)) y5 = (y4 - 0.5 * (dx + dy)) beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x1, y1) vertex(x2, y2) vertex(x3, y3) vertex(x4, y4) vertex(x1, y1) endShape() beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x3, y3) vertex(x4, y4) vertex(x5, y5) vertex(x3, y3) endShape() tree(x4, y4, x5, y5, depth - 1) tree(x5, y5, x3, y3, depth - 1)
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class PythagorasTree extends JPanel { final int depthLimit = 7; float hue = 0.15f; public PythagorasTree() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2, int depth) { if (depth == depthLimit) return; float dx = x2 - x1; float dy = y1 - y2; float x3 = x2 - dy; float y3 = y2 - dx; float x4 = x1 - dy; float y4 = y1 - dx; float x5 = x4 + 0.5F * (dx - dy); float y5 = y4 - 0.5F * (dx + dy); Path2D square = new Path2D.Float(); square.moveTo(x1, y1); square.lineTo(x2, y2); square.lineTo(x3, y3); square.lineTo(x4, y4); square.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1)); g.fill(square); g.setColor(Color.lightGray); g.draw(square); Path2D triangle = new Path2D.Float(); triangle.moveTo(x3, y3); triangle.lineTo(x4, y4); triangle.lineTo(x5, y5); triangle.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1)); g.fill(triangle); g.setColor(Color.lightGray); g.draw(triangle); drawTree(g, x4, y4, x5, y5, depth + 1); drawTree(g, x5, y5, x3, y3, depth + 1); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); drawTree((Graphics2D) g, 275, 500, 375, 500, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pythagoras Tree"); f.setResizable(false); f.add(new PythagorasTree(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
Write the same algorithm in Java as shown in this Python implementation.
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
public class OddWord { interface CharHandler { CharHandler handle(char c) throws Exception; } final CharHandler fwd = new CharHandler() { public CharHandler handle(char c) { System.out.print(c); return (Character.isLetter(c) ? fwd : rev); } }; class Reverser extends Thread implements CharHandler { Reverser() { setDaemon(true); start(); } private Character ch; private char recur() throws Exception { notify(); while (ch == null) wait(); char c = ch, ret = c; ch = null; if (Character.isLetter(c)) { ret = recur(); System.out.print(c); } return ret; } public synchronized void run() { try { while (true) { System.out.print(recur()); notify(); } } catch (Exception e) {} } public synchronized CharHandler handle(char c) throws Exception { while (ch != null) wait(); ch = c; notify(); while (ch != null) wait(); return (Character.isLetter(c) ? rev : fwd); } } final CharHandler rev = new Reverser(); public void loop() throws Exception { CharHandler handler = fwd; int c; while ((c = System.in.read()) >= 0) { handler = handler.handle((char) c); } } public static void main(String[] args) throws Exception { new OddWord().loop(); } }
Can you help me rewrite this code in Java instead of Python, keeping it the same logically?
a1 = [0, 1403580, -810728] m1 = 2**32 - 209 a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a(): def __init__(self, seed_state=123): self.seed(seed_state) def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 = [seed_state, 0, 0] self.x2 = [seed_state, 0, 0] def next_int(self): "return random int in range 0..d" x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1 x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2 self.x1 = [x1i] + self.x1[:2] self.x2 = [x2i] + self.x2[:2] z = (x1i - x2i) % m1 answer = (z + 1) return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / d if __name__ == '__main__': random_gen = MRG32k3a() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
public class App { private static long mod(long x, long y) { long m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } public static class RNG { private final long[] a1 = {0, 1403580, -810728}; private static final long m1 = (1L << 32) - 209; private long[] x1; private final long[] a2 = {527612, 0, -1370589}; private static final long m2 = (1L << 32) - 22853; private long[] x2; private static final long d = m1 + 1; public void seed(long state) { x1 = new long[]{state, 0, 0}; x2 = new long[]{state, 0, 0}; } public long nextInt() { long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1); long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2); long z = mod(x1i - x2i, m1); x1 = new long[]{x1i, x1[0], x1[1]}; x2 = new long[]{x2i, x2[0], x2[1]}; return z + 1; } public double nextFloat() { return 1.0 * nextInt() / d; } } public static void main(String[] args) { RNG rng = new RNG(); rng.seed(1234567); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; rng.seed(987654321); for (int i = 0; i < 100_000; i++) { int value = (int) Math.floor(rng.nextFloat() * 5.0); counts[value]++; } for (int i = 0; i < counts.length; i++) { System.out.printf("%d: %d%n", i, counts[i]); } } }
Convert the following code from Python to Java, ensuring the logic remains intact.
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (isColorful(n)) System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } ColorfulNumbers c = new ColorfulNumbers(); System.out.printf("\n\nLargest colorful number: %,d\n", c.largest); System.out.printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { System.out.printf("%d  %,d\n", d + 1, c.count[d]); total += c.count[d]; } System.out.printf("\nTotal: %,d\n", total); } private ColorfulNumbers() { countColorful(0, 0, 0); } public static boolean isColorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[] = new int[10]; int digits[] = new int[8]; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[] = new int[36]; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } private void countColorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; countColorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (isColorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; countColorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } }
Write the same algorithm in Java as shown in this Python implementation.
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (isColorful(n)) System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } ColorfulNumbers c = new ColorfulNumbers(); System.out.printf("\n\nLargest colorful number: %,d\n", c.largest); System.out.printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { System.out.printf("%d  %,d\n", d + 1, c.count[d]); total += c.count[d]; } System.out.printf("\nTotal: %,d\n", total); } private ColorfulNumbers() { countColorful(0, 0, 0); } public static boolean isColorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[] = new int[10]; int digits[] = new int[8]; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[] = new int[36]; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } private void countColorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; countColorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (isColorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; countColorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } }
Produce a functionally identical Java code for the snippet given in Python.
from math import prod largest = [0] def iscolorful(n): if 0 <= n < 10: return True dig = [int(c) for c in str(n)] if 1 in dig or 0 in dig or len(dig) > len(set(dig)): return False products = list(set(dig)) for i in range(len(dig)): for j in range(i+2, len(dig)+1): p = prod(dig[i:j]) if p in products: return False products.append(p) largest[0] = max(n, largest[0]) return True print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:') for i in range(1, 101, 25): for j in range(25): if iscolorful(i + j): print(f'{i + j: 5,}', end='') print() csum = 0 for i in range(8): j = 0 if i == 0 else 10**i k = 10**(i+1) - 1 n = sum(iscolorful(x) for x in range(j, k+1)) csum += n print(f'The count of colorful numbers between {j} and {k} is {n}.') print(f'The largest possible colorful number is {largest[0]}.') print(f'The total number of colorful numbers is {csum}.')
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0; public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if (isColorful(n)) System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' '); } ColorfulNumbers c = new ColorfulNumbers(); System.out.printf("\n\nLargest colorful number: %,d\n", c.largest); System.out.printf("\nCount of colorful numbers by number of digits:\n"); int total = 0; for (int d = 0; d < 8; ++d) { System.out.printf("%d  %,d\n", d + 1, c.count[d]); total += c.count[d]; } System.out.printf("\nTotal: %,d\n", total); } private ColorfulNumbers() { countColorful(0, 0, 0); } public static boolean isColorful(int n) { if (n < 0 || n > 98765432) return false; int digit_count[] = new int[10]; int digits[] = new int[8]; int num_digits = 0; for (int m = n; m > 0; m /= 10) { int d = m % 10; if (n > 9 && (d == 0 || d == 1)) return false; if (++digit_count[d] > 1) return false; digits[num_digits++] = d; } int products[] = new int[36]; for (int i = 0, product_count = 0; i < num_digits; ++i) { for (int j = i, p = 1; j < num_digits; ++j) { p *= digits[j]; for (int k = 0; k < product_count; ++k) { if (products[k] == p) return false; } products[product_count++] = p; } } return true; } private void countColorful(int taken, int n, int digits) { if (taken == 0) { for (int d = 0; d < 10; ++d) { used[d] = true; countColorful(d < 2 ? 9 : 1, d, 1); used[d] = false; } } else { if (isColorful(n)) { ++count[digits - 1]; if (n > largest) largest = n; } if (taken < 9) { for (int d = 2; d < 10; ++d) { if (!used[d]) { used[d] = true; countColorful(taken + 1, n * 10 + d, digits + 1); used[d] = false; } } } } } }
Produce a functionally identical Java code for the snippet given in Python.
import os from math import pi, sin au_header = bytearray( [46, 115, 110, 100, 0, 0, 0, 24, 255, 255, 255, 255, 0, 0, 0, 3, 0, 0, 172, 68, 0, 0, 0, 1]) def f(x, freq): "Compute sine wave as 16-bit integer" return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536 def play_sine(freq=440, duration=5, oname="pysine.au"): "Play a sine wave for `duration` seconds" out = open(oname, 'wb') out.write(au_header) v = [f(x, freq) for x in range(duration * 44100 + 1)] s = [] for i in v: s.append(i >> 8) s.append(i % 256) out.write(bytearray(s)) out.close() os.system("vlc " + oname) play_sine()
import processing.sound.*; SinOsc sine; size(500,500); sine = new SinOsc(this); sine.freq(500); sine.play(); delay(5000);
Please provide an equivalent version of this Python code in Java.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
package codegenerator; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class CodeGenerator { final static int WORDSIZE = 4; static byte[] code = {}; static Map<String, NodeType> str_to_nodes = new HashMap<>(); static List<String> string_pool = new ArrayList<>(); static List<String> variables = new ArrayList<>(); static int string_count = 0; static int var_count = 0; static Scanner s; static NodeType[] unary_ops = { NodeType.nd_Negate, NodeType.nd_Not }; static NodeType[] operators = { NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub, NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq, NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or }; static enum Mnemonic { NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE), nd_If("If", Mnemonic.NONE), nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE), nd_Assign("Assign", Mnemonic.NONE), nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD), nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE), nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ), nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR); private final String name; private final Mnemonic m; NodeType(String name, Mnemonic m) { this.name = name; this.m = m; } Mnemonic getMnemonic() { return this.m; } @Override public String toString() { return this.name; } } static void appendToCode(int b) { code = Arrays.copyOf(code, code.length + 1); code[code.length - 1] = (byte) b; } static void emit_byte(Mnemonic m) { appendToCode(m.ordinal()); } static void emit_word(int n) { appendToCode(n >> 24); appendToCode(n >> 16); appendToCode(n >> 8); appendToCode(n); } static void emit_word_at(int pos, int n) { code[pos] = (byte) (n >> 24); code[pos + 1] = (byte) (n >> 16); code[pos + 2] = (byte) (n >> 8); code[pos + 3] = (byte) n; } static int get_word(int pos) { int result; result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ; return result; } static int fetch_var_offset(String name) { int n; n = variables.indexOf(name); if (n == -1) { variables.add(name); n = var_count++; } return n; } static int fetch_string_offset(String str) { int n; n = string_pool.indexOf(str); if (n == -1) { string_pool.add(str); n = string_count++; } return n; } static int hole() { int t = code.length; emit_word(0); return t; } static boolean arrayContains(NodeType[] a, NodeType n) { boolean result = false; for (NodeType test: a) { if (test.equals(n)) { result = true; break; } } return result; } static void code_gen(Node x) throws Exception { int n, p1, p2; if (x == null) return; switch (x.nt) { case nd_None: return; case nd_Ident: emit_byte(Mnemonic.FETCH); n = fetch_var_offset(x.value); emit_word(n); break; case nd_Integer: emit_byte(Mnemonic.PUSH); emit_word(Integer.parseInt(x.value)); break; case nd_String: emit_byte(Mnemonic.PUSH); n = fetch_string_offset(x.value); emit_word(n); break; case nd_Assign: n = fetch_var_offset(x.left.value); code_gen(x.right); emit_byte(Mnemonic.STORE); emit_word(n); break; case nd_If: p2 = 0; code_gen(x.left); emit_byte(Mnemonic.JZ); p1 = hole(); code_gen(x.right.left); if (x.right.right != null) { emit_byte(Mnemonic.JMP); p2 = hole(); } emit_word_at(p1, code.length - p1); if (x.right.right != null) { code_gen(x.right.right); emit_word_at(p2, code.length - p2); } break; case nd_While: p1 = code.length; code_gen(x.left); emit_byte(Mnemonic.JZ); p2 = hole(); code_gen(x.right); emit_byte(Mnemonic.JMP); emit_word(p1 - code.length); emit_word_at(p2, code.length - p2); break; case nd_Sequence: code_gen(x.left); code_gen(x.right); break; case nd_Prtc: code_gen(x.left); emit_byte(Mnemonic.PRTC); break; case nd_Prti: code_gen(x.left); emit_byte(Mnemonic.PRTI); break; case nd_Prts: code_gen(x.left); emit_byte(Mnemonic.PRTS); break; default: if (arrayContains(operators, x.nt)) { code_gen(x.left); code_gen(x.right); emit_byte(x.nt.getMnemonic()); } else if (arrayContains(unary_ops, x.nt)) { code_gen(x.left); emit_byte(x.nt.getMnemonic()); } else { throw new Exception("Error in code generator! Found " + x.nt + ", expecting operator."); } } } static void list_code() throws Exception { int pc = 0, x; Mnemonic op; System.out.println("Datasize: " + var_count + " Strings: " + string_count); for (String s: string_pool) { System.out.println(s); } while (pc < code.length) { System.out.printf("%4d ", pc); op = Mnemonic.values()[code[pc++]]; switch (op) { case FETCH: x = get_word(pc); System.out.printf("fetch [%d]", x); pc += WORDSIZE; break; case STORE: x = get_word(pc); System.out.printf("store [%d]", x); pc += WORDSIZE; break; case PUSH: x = get_word(pc); System.out.printf("push %d", x); pc += WORDSIZE; break; case ADD: case SUB: case MUL: case DIV: case MOD: case LT: case GT: case LE: case GE: case EQ: case NE: case AND: case OR: case NEG: case NOT: case PRTC: case PRTI: case PRTS: case HALT: System.out.print(op.toString().toLowerCase()); break; case JMP: x = get_word(pc); System.out.printf("jmp (%d) %d", x, pc + x); pc += WORDSIZE; break; case JZ: x = get_word(pc); System.out.printf("jz (%d) %d", x, pc + x); pc += WORDSIZE; break; default: throw new Exception("Unknown opcode " + code[pc] + "@" + (pc - 1)); } System.out.println(); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); code_gen(n); emit_byte(Mnemonic.HALT); list_code(); } catch (Exception e) { System.out.println("Ex: "+e); } } } }
Generate a Java translation of this Python snippet without changing its computational steps.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
package codegenerator; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class CodeGenerator { final static int WORDSIZE = 4; static byte[] code = {}; static Map<String, NodeType> str_to_nodes = new HashMap<>(); static List<String> string_pool = new ArrayList<>(); static List<String> variables = new ArrayList<>(); static int string_count = 0; static int var_count = 0; static Scanner s; static NodeType[] unary_ops = { NodeType.nd_Negate, NodeType.nd_Not }; static NodeType[] operators = { NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub, NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq, NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or }; static enum Mnemonic { NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE), nd_If("If", Mnemonic.NONE), nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE), nd_Assign("Assign", Mnemonic.NONE), nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD), nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE), nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ), nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR); private final String name; private final Mnemonic m; NodeType(String name, Mnemonic m) { this.name = name; this.m = m; } Mnemonic getMnemonic() { return this.m; } @Override public String toString() { return this.name; } } static void appendToCode(int b) { code = Arrays.copyOf(code, code.length + 1); code[code.length - 1] = (byte) b; } static void emit_byte(Mnemonic m) { appendToCode(m.ordinal()); } static void emit_word(int n) { appendToCode(n >> 24); appendToCode(n >> 16); appendToCode(n >> 8); appendToCode(n); } static void emit_word_at(int pos, int n) { code[pos] = (byte) (n >> 24); code[pos + 1] = (byte) (n >> 16); code[pos + 2] = (byte) (n >> 8); code[pos + 3] = (byte) n; } static int get_word(int pos) { int result; result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ; return result; } static int fetch_var_offset(String name) { int n; n = variables.indexOf(name); if (n == -1) { variables.add(name); n = var_count++; } return n; } static int fetch_string_offset(String str) { int n; n = string_pool.indexOf(str); if (n == -1) { string_pool.add(str); n = string_count++; } return n; } static int hole() { int t = code.length; emit_word(0); return t; } static boolean arrayContains(NodeType[] a, NodeType n) { boolean result = false; for (NodeType test: a) { if (test.equals(n)) { result = true; break; } } return result; } static void code_gen(Node x) throws Exception { int n, p1, p2; if (x == null) return; switch (x.nt) { case nd_None: return; case nd_Ident: emit_byte(Mnemonic.FETCH); n = fetch_var_offset(x.value); emit_word(n); break; case nd_Integer: emit_byte(Mnemonic.PUSH); emit_word(Integer.parseInt(x.value)); break; case nd_String: emit_byte(Mnemonic.PUSH); n = fetch_string_offset(x.value); emit_word(n); break; case nd_Assign: n = fetch_var_offset(x.left.value); code_gen(x.right); emit_byte(Mnemonic.STORE); emit_word(n); break; case nd_If: p2 = 0; code_gen(x.left); emit_byte(Mnemonic.JZ); p1 = hole(); code_gen(x.right.left); if (x.right.right != null) { emit_byte(Mnemonic.JMP); p2 = hole(); } emit_word_at(p1, code.length - p1); if (x.right.right != null) { code_gen(x.right.right); emit_word_at(p2, code.length - p2); } break; case nd_While: p1 = code.length; code_gen(x.left); emit_byte(Mnemonic.JZ); p2 = hole(); code_gen(x.right); emit_byte(Mnemonic.JMP); emit_word(p1 - code.length); emit_word_at(p2, code.length - p2); break; case nd_Sequence: code_gen(x.left); code_gen(x.right); break; case nd_Prtc: code_gen(x.left); emit_byte(Mnemonic.PRTC); break; case nd_Prti: code_gen(x.left); emit_byte(Mnemonic.PRTI); break; case nd_Prts: code_gen(x.left); emit_byte(Mnemonic.PRTS); break; default: if (arrayContains(operators, x.nt)) { code_gen(x.left); code_gen(x.right); emit_byte(x.nt.getMnemonic()); } else if (arrayContains(unary_ops, x.nt)) { code_gen(x.left); emit_byte(x.nt.getMnemonic()); } else { throw new Exception("Error in code generator! Found " + x.nt + ", expecting operator."); } } } static void list_code() throws Exception { int pc = 0, x; Mnemonic op; System.out.println("Datasize: " + var_count + " Strings: " + string_count); for (String s: string_pool) { System.out.println(s); } while (pc < code.length) { System.out.printf("%4d ", pc); op = Mnemonic.values()[code[pc++]]; switch (op) { case FETCH: x = get_word(pc); System.out.printf("fetch [%d]", x); pc += WORDSIZE; break; case STORE: x = get_word(pc); System.out.printf("store [%d]", x); pc += WORDSIZE; break; case PUSH: x = get_word(pc); System.out.printf("push %d", x); pc += WORDSIZE; break; case ADD: case SUB: case MUL: case DIV: case MOD: case LT: case GT: case LE: case GE: case EQ: case NE: case AND: case OR: case NEG: case NOT: case PRTC: case PRTI: case PRTS: case HALT: System.out.print(op.toString().toLowerCase()); break; case JMP: x = get_word(pc); System.out.printf("jmp (%d) %d", x, pc + x); pc += WORDSIZE; break; case JZ: x = get_word(pc); System.out.printf("jz (%d) %d", x, pc + x); pc += WORDSIZE; break; default: throw new Exception("Unknown opcode " + code[pc] + "@" + (pc - 1)); } System.out.println(); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); code_gen(n); emit_byte(Mnemonic.HALT); list_code(); } catch (Exception e) { System.out.println("Ex: "+e); } } } }
Keep all operations the same but rewrite the snippet in Java.
def load_ast() line = readline() line_list = tokenize the line, respecting double quotes text = line_list[0] if text == ";" return None node_type = text if len(line_list) > 1 return make_leaf(node_type, line_list[1]) left = load_ast() right = load_ast() return make_node(node_type, left, right)
package codegenerator; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class CodeGenerator { final static int WORDSIZE = 4; static byte[] code = {}; static Map<String, NodeType> str_to_nodes = new HashMap<>(); static List<String> string_pool = new ArrayList<>(); static List<String> variables = new ArrayList<>(); static int string_count = 0; static int var_count = 0; static Scanner s; static NodeType[] unary_ops = { NodeType.nd_Negate, NodeType.nd_Not }; static NodeType[] operators = { NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub, NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq, NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or }; static enum Mnemonic { NONE, FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT } static class Node { public NodeType nt; public Node left, right; public String value; Node() { this.nt = null; this.left = null; this.right = null; this.value = null; } Node(NodeType node_type, Node left, Node right, String value) { this.nt = node_type; this.left = left; this.right = right; this.value = value; } public static Node make_node(NodeType nodetype, Node left, Node right) { return new Node(nodetype, left, right, ""); } public static Node make_node(NodeType nodetype, Node left) { return new Node(nodetype, left, null, ""); } public static Node make_leaf(NodeType nodetype, String value) { return new Node(nodetype, null, null, value); } } static enum NodeType { nd_None("", Mnemonic.NONE), nd_Ident("Identifier", Mnemonic.NONE), nd_String("String", Mnemonic.NONE), nd_Integer("Integer", Mnemonic.NONE), nd_Sequence("Sequence", Mnemonic.NONE), nd_If("If", Mnemonic.NONE), nd_Prtc("Prtc", Mnemonic.NONE), nd_Prts("Prts", Mnemonic.NONE), nd_Prti("Prti", Mnemonic.NONE), nd_While("While", Mnemonic.NONE), nd_Assign("Assign", Mnemonic.NONE), nd_Negate("Negate", Mnemonic.NEG), nd_Not("Not", Mnemonic.NOT), nd_Mul("Multiply", Mnemonic.MUL), nd_Div("Divide", Mnemonic.DIV), nd_Mod("Mod", Mnemonic.MOD), nd_Add("Add", Mnemonic.ADD), nd_Sub("Subtract", Mnemonic.SUB), nd_Lss("Less", Mnemonic.LT), nd_Leq("LessEqual", Mnemonic.LE), nd_Gtr("Greater", Mnemonic.GT), nd_Geq("GreaterEqual", Mnemonic.GE), nd_Eql("Equal", Mnemonic.EQ), nd_Neq("NotEqual", Mnemonic.NE), nd_And("And", Mnemonic.AND), nd_Or("Or", Mnemonic.OR); private final String name; private final Mnemonic m; NodeType(String name, Mnemonic m) { this.name = name; this.m = m; } Mnemonic getMnemonic() { return this.m; } @Override public String toString() { return this.name; } } static void appendToCode(int b) { code = Arrays.copyOf(code, code.length + 1); code[code.length - 1] = (byte) b; } static void emit_byte(Mnemonic m) { appendToCode(m.ordinal()); } static void emit_word(int n) { appendToCode(n >> 24); appendToCode(n >> 16); appendToCode(n >> 8); appendToCode(n); } static void emit_word_at(int pos, int n) { code[pos] = (byte) (n >> 24); code[pos + 1] = (byte) (n >> 16); code[pos + 2] = (byte) (n >> 8); code[pos + 3] = (byte) n; } static int get_word(int pos) { int result; result = ((code[pos] & 0xff) << 24) + ((code[pos + 1] & 0xff) << 16) + ((code[pos + 2] & 0xff) << 8) + (code[pos + 3] & 0xff) ; return result; } static int fetch_var_offset(String name) { int n; n = variables.indexOf(name); if (n == -1) { variables.add(name); n = var_count++; } return n; } static int fetch_string_offset(String str) { int n; n = string_pool.indexOf(str); if (n == -1) { string_pool.add(str); n = string_count++; } return n; } static int hole() { int t = code.length; emit_word(0); return t; } static boolean arrayContains(NodeType[] a, NodeType n) { boolean result = false; for (NodeType test: a) { if (test.equals(n)) { result = true; break; } } return result; } static void code_gen(Node x) throws Exception { int n, p1, p2; if (x == null) return; switch (x.nt) { case nd_None: return; case nd_Ident: emit_byte(Mnemonic.FETCH); n = fetch_var_offset(x.value); emit_word(n); break; case nd_Integer: emit_byte(Mnemonic.PUSH); emit_word(Integer.parseInt(x.value)); break; case nd_String: emit_byte(Mnemonic.PUSH); n = fetch_string_offset(x.value); emit_word(n); break; case nd_Assign: n = fetch_var_offset(x.left.value); code_gen(x.right); emit_byte(Mnemonic.STORE); emit_word(n); break; case nd_If: p2 = 0; code_gen(x.left); emit_byte(Mnemonic.JZ); p1 = hole(); code_gen(x.right.left); if (x.right.right != null) { emit_byte(Mnemonic.JMP); p2 = hole(); } emit_word_at(p1, code.length - p1); if (x.right.right != null) { code_gen(x.right.right); emit_word_at(p2, code.length - p2); } break; case nd_While: p1 = code.length; code_gen(x.left); emit_byte(Mnemonic.JZ); p2 = hole(); code_gen(x.right); emit_byte(Mnemonic.JMP); emit_word(p1 - code.length); emit_word_at(p2, code.length - p2); break; case nd_Sequence: code_gen(x.left); code_gen(x.right); break; case nd_Prtc: code_gen(x.left); emit_byte(Mnemonic.PRTC); break; case nd_Prti: code_gen(x.left); emit_byte(Mnemonic.PRTI); break; case nd_Prts: code_gen(x.left); emit_byte(Mnemonic.PRTS); break; default: if (arrayContains(operators, x.nt)) { code_gen(x.left); code_gen(x.right); emit_byte(x.nt.getMnemonic()); } else if (arrayContains(unary_ops, x.nt)) { code_gen(x.left); emit_byte(x.nt.getMnemonic()); } else { throw new Exception("Error in code generator! Found " + x.nt + ", expecting operator."); } } } static void list_code() throws Exception { int pc = 0, x; Mnemonic op; System.out.println("Datasize: " + var_count + " Strings: " + string_count); for (String s: string_pool) { System.out.println(s); } while (pc < code.length) { System.out.printf("%4d ", pc); op = Mnemonic.values()[code[pc++]]; switch (op) { case FETCH: x = get_word(pc); System.out.printf("fetch [%d]", x); pc += WORDSIZE; break; case STORE: x = get_word(pc); System.out.printf("store [%d]", x); pc += WORDSIZE; break; case PUSH: x = get_word(pc); System.out.printf("push %d", x); pc += WORDSIZE; break; case ADD: case SUB: case MUL: case DIV: case MOD: case LT: case GT: case LE: case GE: case EQ: case NE: case AND: case OR: case NEG: case NOT: case PRTC: case PRTI: case PRTS: case HALT: System.out.print(op.toString().toLowerCase()); break; case JMP: x = get_word(pc); System.out.printf("jmp (%d) %d", x, pc + x); pc += WORDSIZE; break; case JZ: x = get_word(pc); System.out.printf("jz (%d) %d", x, pc + x); pc += WORDSIZE; break; default: throw new Exception("Unknown opcode " + code[pc] + "@" + (pc - 1)); } System.out.println(); } } static Node load_ast() throws Exception { String command, value; String line; Node left, right; while (s.hasNext()) { line = s.nextLine(); value = null; if (line.length() > 16) { command = line.substring(0, 15).trim(); value = line.substring(15).trim(); } else { command = line.trim(); } if (command.equals(";")) { return null; } if (!str_to_nodes.containsKey(command)) { throw new Exception("Command not found: '" + command + "'"); } if (value != null) { return Node.make_leaf(str_to_nodes.get(command), value); } left = load_ast(); right = load_ast(); return Node.make_node(str_to_nodes.get(command), left, right); } return null; } public static void main(String[] args) { Node n; str_to_nodes.put(";", NodeType.nd_None); str_to_nodes.put("Sequence", NodeType.nd_Sequence); str_to_nodes.put("Identifier", NodeType.nd_Ident); str_to_nodes.put("String", NodeType.nd_String); str_to_nodes.put("Integer", NodeType.nd_Integer); str_to_nodes.put("If", NodeType.nd_If); str_to_nodes.put("While", NodeType.nd_While); str_to_nodes.put("Prtc", NodeType.nd_Prtc); str_to_nodes.put("Prts", NodeType.nd_Prts); str_to_nodes.put("Prti", NodeType.nd_Prti); str_to_nodes.put("Assign", NodeType.nd_Assign); str_to_nodes.put("Negate", NodeType.nd_Negate); str_to_nodes.put("Not", NodeType.nd_Not); str_to_nodes.put("Multiply", NodeType.nd_Mul); str_to_nodes.put("Divide", NodeType.nd_Div); str_to_nodes.put("Mod", NodeType.nd_Mod); str_to_nodes.put("Add", NodeType.nd_Add); str_to_nodes.put("Subtract", NodeType.nd_Sub); str_to_nodes.put("Less", NodeType.nd_Lss); str_to_nodes.put("LessEqual", NodeType.nd_Leq); str_to_nodes.put("Greater", NodeType.nd_Gtr); str_to_nodes.put("GreaterEqual", NodeType.nd_Geq); str_to_nodes.put("Equal", NodeType.nd_Eql); str_to_nodes.put("NotEqual", NodeType.nd_Neq); str_to_nodes.put("And", NodeType.nd_And); str_to_nodes.put("Or", NodeType.nd_Or); if (args.length > 0) { try { s = new Scanner(new File(args[0])); n = load_ast(); code_gen(n); emit_byte(Mnemonic.HALT); list_code(); } catch (Exception e) { System.out.println("Ex: "+e); } } } }
Write the same algorithm in Java as shown in this Python implementation.
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
import java.math.BigInteger; import java.util.LinkedList; public class SternBrocot { static LinkedList<Integer> sequence = new LinkedList<Integer>(){{ add(1); add(1); }}; private static void genSeq(int n){ for(int conIdx = 1; sequence.size() < n; conIdx++){ int consider = sequence.get(conIdx); int pre = sequence.get(conIdx - 1); sequence.add(consider + pre); sequence.add(consider); } } public static void main(String[] args){ genSeq(1200); System.out.println("The first 15 elements are: " + sequence.subList(0, 15)); for(int i = 1; i <= 10; i++){ System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1)); } System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1)); boolean failure = false; for(int i = 0; i < 999; i++){ failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE); } System.out.println("All GCDs are" + (failure ? " not" : "") + " 1"); } }
Rewrite this program in Java while keeping its functionality equivalent to the Python version.
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 ± delta' return super().__new__(_cls, float(value), abs(float(delta))) def reciprocal(self): return I(1. / self.value, self.delta / (self.value**2)) def __str__(self): 'Shorter form of Imprecise as string' return 'I(%g, %g)' % self def __neg__(self): return I(-self.value, self.delta) def __add__(self, other): if type(other) == I: return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value + c, self.delta) def __sub__(self, other): return self + (-other) def __radd__(self, other): return I.__add__(self, other) def __mul__(self, other): if type(other) == I: a1,b1 = self a2,b2 = other f = a1 * a2 return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value * c, self.delta * c) def __pow__(self, other): if type(other) == I: return NotImplemented try: c = float(other) except: return NotImplemented f = self.value ** c return I(f, f * c * (self.delta / self.value)) def __rmul__(self, other): return I.__mul__(self, other) def __truediv__(self, other): if type(other) == I: return self.__mul__(other.reciprocal()) try: c = float(other) except: return NotImplemented return I(self.value / c, self.delta / c) def __rtruediv__(self, other): return other * self.reciprocal() __div__, __rdiv__ = __truediv__, __rtruediv__ Imprecise = I def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 x1 = I(100, 1.1) x2 = I(200, 2.2) y1 = I( 50, 1.2) y2 = I(100, 2.3) p1, p2 = (x1, y1), (x2, y2) print("Distance between points\n p1: %s\n and p2: %s\n = %r" % ( p1, p2, distance(p1, p2)))
public class Approx { private double value; private double error; public Approx(){this.value = this.error = 0;} public Approx(Approx b){ this.value = b.value; this.error = b.error; } public Approx(double value, double error){ this.value = value; this.error = error; } public Approx add(Approx b){ value+= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx add(double b){ value+= b; return this; } public Approx sub(Approx b){ value-= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx sub(double b){ value-= b; return this; } public Approx mult(Approx b){ double oldVal = value; value*= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx mult(double b){ value*= b; error = Math.abs(b * error); return this; } public Approx div(Approx b){ double oldVal = value; value/= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx div(double b){ value/= b; error = Math.abs(b * error); return this; } public Approx pow(double b){ double oldVal = value; value = Math.pow(value, b); error = Math.abs(value * b * (error / oldVal)); return this; } @Override public String toString(){return value+"±"+error;} public static void main(String[] args){ Approx x1 = new Approx(100, 1.1); Approx y1 = new Approx(50, 1.2); Approx x2 = new Approx(200, 2.2); Approx y2 = new Approx(100, 2.3); x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5); System.out.println(x1); } }
Preserve the algorithm and functionality while converting the code from Python to Java.
from itertools import groupby def soundex(word): codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) cmap2 = lambda kar: soundDict.get(kar, '9') sdx = ''.join(cmap2(kar) for kar in word.lower()) sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') sdx3 = sdx2[0:4].ljust(4,'0') return sdx3
public static void main(String[] args){ System.out.println(soundex("Soundex")); System.out.println(soundex("Example")); System.out.println(soundex("Sownteks")); System.out.println(soundex("Ekzampul")); } private static String getCode(char c){ switch(c){ case 'B': case 'F': case 'P': case 'V': return "1"; case 'C': case 'G': case 'J': case 'K': case 'Q': case 'S': case 'X': case 'Z': return "2"; case 'D': case 'T': return "3"; case 'L': return "4"; case 'M': case 'N': return "5"; case 'R': return "6"; default: return ""; } } public static String soundex(String s){ String code, previous, soundex; code = s.toUpperCase().charAt(0) + ""; previous = getCode(s.toUpperCase().charAt(0)); for(int i = 1;i < s.length();i++){ String current = getCode(s.toUpperCase().charAt(i)); if(current.length() > 0 && !current.equals(previous)){ code = code + current; } previous = current; } soundex = (code + "0000").substring(0, 4); return soundex; }
Rewrite the snippet below in Java so it works the same as the original Python code.
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i) return out def replace_brackets(s): depth,out = 0,[] for c in s: if c == '(': out.append("([{"[depth%3]) depth += 1 else: depth -= 1 out.append(")]}"[depth%3]) return "".join(out) for x in bags(5): print(replace_brackets(x[1]))
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET.add(1); } else { OFFSET.add(0); } } } private static void append(long t) { TREE_LIST.add(1 | (t << 1)); } private static void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { System.out.print('('); } else { System.out.print(')'); } t = t >> 1; } } private static void listTrees(int n) { for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) { show(TREE_LIST.get(i), n * 2); System.out.println(); } } private static void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } var pp = pos; var ss = sl; if (sl > rem) { ss = rem; pp = OFFSET.get(ss); } else if (pp >= OFFSET.get(ss + 1)) { ss--; if (ss == 0) { return; } pp = OFFSET.get(ss); } assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } private static void makeTrees(int n) { if (OFFSET.get(n + 1) != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1); OFFSET.set(n + 1, TREE_LIST.size()); } private static void test(int n) { if (n < 1 || n > 12) { throw new IllegalArgumentException("Argument must be between 1 and 12"); } append(0); makeTrees(n); System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n)); listTrees(n); } public static void main(String[] args) { test(5); } }
Generate a Java translation of this Python snippet without changing its computational steps.
class Doc(object): def method(self, num): pass
public class Doc{ private String field; public int method(long num) throws BadException{ } }
Keep all operations the same but rewrite the snippet in Java.
from collections import namedtuple import math Circle = namedtuple('Circle', 'x, y, r') def solveApollonius(c1, c2, c3, s1, s2, s3): x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3 v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1 v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2 w12 = v12/v11 w13 = v13/v11 w14 = v14/v11 w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14 P = -w23/w22 Q = w24/w22 M = -w12*P-w13 N = w14 - w12*Q a = N*N + Q*Q - 1 b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1 D = b*b-4*a*c rs = (-b-math.sqrt(D))/(2*a) xs = M+N*rs ys = P+Q*rs return Circle(xs, ys, rs) if __name__ == '__main__': c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2) print(solveApollonius(c1, c2, c3, 1, 1, 1)) print(solveApollonius(c1, c2, c3, -1, -1, -1))
public class Circle { public double[] center; public double radius; public Circle(double[] center, double radius) { this.center = center; this.radius = radius; } public String toString() { return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1], radius); } } public class ApolloniusSolver { public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1, int s2, int s3) { float x1 = c1.center[0]; float y1 = c1.center[1]; float r1 = c1.radius; float x2 = c2.center[0]; float y2 = c2.center[1]; float r2 = c2.radius; float x3 = c3.center[0]; float y3 = c3.center[1]; float r3 = c3.radius; float v11 = 2*x2 - 2*x1; float v12 = 2*y2 - 2*y1; float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2; float v14 = 2*s2*r2 - 2*s1*r1; float v21 = 2*x3 - 2*x2; float v22 = 2*y3 - 2*y2; float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3; float v24 = 2*s3*r3 - 2*s2*r2; float w12 = v12/v11; float w13 = v13/v11; float w14 = v14/v11; float w22 = v22/v21-w12; float w23 = v23/v21-w13; float w24 = v24/v21-w14; float P = -w23/w22; float Q = w24/w22; float M = -w12*P-w13; float N = w14 - w12*Q; float a = N*N + Q*Q - 1; float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1; float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1; float D = b*b-4*a*c; float rs = (-b-Math.sqrt(D))/(2*a); float xs = M + N * rs; float ys = P + Q * rs; return new Circle(new double[]{xs,ys}, rs); } public static void main(final String[] args) { Circle c1 = new Circle(new double[]{0,0}, 1); Circle c2 = new Circle(new double[]{4,0}, 1); Circle c3 = new Circle(new double[]{2,4}, 2); System.out.println(solveApollonius(c1,c2,c3,1,1,1)); System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1)); } }
Can you help me rewrite this code in Java instead of Python, keeping it the same logically?
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( allSame, zip(*(reversed(x) for x in xs)) ), '' ) def main(): samples = [ [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], [ "Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag" ] ] for xs in samples: print( longestCommonSuffix(xs) ) if __name__ == '__main__': main()
import java.util.List; public class App { private static String lcs(List<String> a) { var le = a.size(); if (le == 0) { return ""; } if (le == 1) { return a.get(0); } var le0 = a.get(0).length(); var minLen = le0; for (int i = 1; i < le; i++) { if (a.get(i).length() < minLen) { minLen = a.get(i).length(); } } if (minLen == 0) { return ""; } var res = ""; var a1 = a.subList(1, a.size()); for (int i = 1; i < minLen; i++) { var suffix = a.get(0).substring(le0 - i); for (String e : a1) { if (!e.endsWith(suffix)) { return res; } } res = suffix; } return ""; } public static void main(String[] args) { var tests = List.of( List.of("baabababc", "baabc", "bbbabc"), List.of("baabababc", "baabc", "bbbazc"), List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), List.of("longest", "common", "suffix"), List.of("suffix"), List.of("") ); for (List<String> test : tests) { System.out.printf("%s -> `%s`\n", test, lcs(test)); } } }
Produce a functionally identical Java code for the snippet given in Python.
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Write the same algorithm in Java as shown in this Python implementation.
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString class %s has %i characters the first of which are:\n %r' % (stringclass.__name__, len(chars), chars[:100]))
import java.util.stream.IntStream; public class Letters { public static void main(String[] args) throws Exception { System.out.print("Upper case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isUpperCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); System.out.print("Lower case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isLowerCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); } }
Convert the following code from Python to Java, ensuring the logic remains intact.
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString class %s has %i characters the first of which are:\n %r' % (stringclass.__name__, len(chars), chars[:100]))
import java.util.stream.IntStream; public class Letters { public static void main(String[] args) throws Exception { System.out.print("Upper case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isUpperCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); System.out.print("Lower case: "); IntStream.rangeClosed(0, 0x10FFFF) .filter(Character::isLowerCase) .limit(72) .forEach(n -> System.out.printf("%c", n)); System.out.println("..."); } }
Translate the given Python code snippet into Java without altering its behavior.
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
public static void main(String[] args) { int[][] matrix = {{1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}}; int sum = 0; for (int row = 1; row < matrix.length; row++) { for (int col = 0; col < row; col++) { sum += matrix[row][col]; } } System.out.println(sum); }
Change the programming language of this snippet from Python to Java without modifying what it does.
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); long newSize = Long.parseLong(args[1]); outChan.truncate(newSize); outChan.close(); } }
Translate this program into Java but keep the logic exactly as in Python.
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; } FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); long newSize = Long.parseLong(args[1]); outChan.truncate(newSize); outChan.close(); } }
Write the same code in Java as shown below in Python.
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float: lt = _quad_simpsons_mem(f, a, fa, m, fm) rt = _quad_simpsons_mem(f, m, fm, b, fb) delta = lt.simp + rt.simp - whole return (lt.simp + rt.simp + delta/15 if (abs(delta) <= eps * 15) else _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm) ) def quad_asr(f: callable, a: float, b: float, eps: float)->float: fa = f(a) fb = f(b) t = _quad_simpsons_mem(f, a, fa, b, fb) return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm) def main(): (a, b,) = (0.0, 1.0,) sinx = quad_asr(math.sin, a, b, 1e-09); print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx)) main()
import java.util.function.Function; public class NumericalIntegrationAdaptiveSimpsons { public static void main(String[] args) { Function<Double,Double> f = x -> sin(x); System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount); functionCount = 0; System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount); } private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) { double fa = function.apply(a); double fb = function.apply(b); Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb); return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx); } private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) { Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm); Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb); double delta = left.s + right.s - whole; if ( Math.abs(delta) <= 15*error ) { return left.s + right.s + delta / 15; } return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) + quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx); } private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = function.apply(m); return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb)); } private static class Triple { double x, fx, s; private Triple(double m, double fm, double s) { this.x = m; this.fx = fm; this.s = s; } } private static int functionCount = 0; private static double sin(double x) { functionCount++; return Math.sin(x); } }
Produce a language-to-language conversion: from Python to Java, same semantics.
import math import collections triple = collections.namedtuple('triple', 'm fm simp') def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple: m = a + (b - a) / 2 fm = f(m) simp = abs(b - a) / 6 * (fa + 4*fm + fb) return triple(m, fm, simp,) def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float: lt = _quad_simpsons_mem(f, a, fa, m, fm) rt = _quad_simpsons_mem(f, m, fm, b, fb) delta = lt.simp + rt.simp - whole return (lt.simp + rt.simp + delta/15 if (abs(delta) <= eps * 15) else _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) + _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm) ) def quad_asr(f: callable, a: float, b: float, eps: float)->float: fa = f(a) fb = f(b) t = _quad_simpsons_mem(f, a, fa, b, fb) return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm) def main(): (a, b,) = (0.0, 1.0,) sinx = quad_asr(math.sin, a, b, 1e-09); print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx)) main()
import java.util.function.Function; public class NumericalIntegrationAdaptiveSimpsons { public static void main(String[] args) { Function<Double,Double> f = x -> sin(x); System.out.printf("integrate sin(x), x = 0 .. Pi = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, Math.PI, 1e-8), functionCount); functionCount = 0; System.out.printf("integrate sin(x), x = 0 .. 1 = %2.12f. Function calls = %d%n", quadratureAdaptiveSimpsons(f, 0, 1, 1e-8), functionCount); } private static double quadratureAdaptiveSimpsons(Function<Double,Double> function, double a, double b, double error) { double fa = function.apply(a); double fb = function.apply(b); Triple t = quadratureAdaptiveSimpsonsOne(function, a, fa, b ,fb); return quadratureAdaptiveSimpsonsRecursive(function, a, fa, b, fb, error, t.s, t.x, t.fx); } private static double quadratureAdaptiveSimpsonsRecursive(Function<Double,Double> function, double a, double fa, double b, double fb, double error, double whole, double m, double fm) { Triple left = quadratureAdaptiveSimpsonsOne(function, a, fa, m, fm); Triple right = quadratureAdaptiveSimpsonsOne(function, m, fm, b, fb); double delta = left.s + right.s - whole; if ( Math.abs(delta) <= 15*error ) { return left.s + right.s + delta / 15; } return quadratureAdaptiveSimpsonsRecursive(function, a, fa, m, fm, error/2, left.s, left.x, left.fx) + quadratureAdaptiveSimpsonsRecursive(function, m, fm, b, fb, error/2, right.s, right.x, right.fx); } private static Triple quadratureAdaptiveSimpsonsOne(Function<Double,Double> function, double a, double fa, double b, double fb) { double m = (a + b) / 2; double fm = function.apply(m); return new Triple(m, fm, Math.abs(b-a) / 6 * (fa + 4*fm + fb)); } private static class Triple { double x, fx, s; private Triple(double m, double fm, double s) { this.x = m; this.fx = fm; this.s = s; } } private static int functionCount = 0; private static double sin(double x) { functionCount++; return Math.sin(x); } }
Convert this Python block to Java, preserving its control flow and logic.
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: yield key, val print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
import java.io.*; import java.util.Scanner; public class ReadFastaFile { public static void main(String[] args) throws FileNotFoundException { boolean first = true; try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.charAt(0) == '>') { if (first) first = false; else System.out.println(); System.out.printf("%s: ", line.substring(1)); } else { System.out.print(line); } } } System.out.println(); } }
Translate this program into Java but keep the logic exactly as in Python.
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: yield key, val print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
import java.io.*; import java.util.Scanner; public class ReadFastaFile { public static void main(String[] args) throws FileNotFoundException { boolean first = true; try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.charAt(0) == '>') { if (first) first = false; else System.out.println(); System.out.printf("%s: ", line.substring(1)); } else { System.out.print(line); } } } System.out.println(); } }
Change the programming language of this snippet from Python to Java without modifying what it does.
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Port the provided Python code into Java while preserving the original functionality.
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Convert the following code from Python to Java, ensuring the logic remains intact.
from Xlib import X, display class Window: def __init__(self, display, msg): self.display = display self.msg = msg self.screen = self.display.screen() self.window = self.screen.root.create_window( 10, 10, 100, 100, 1, self.screen.root_depth, background_pixel=self.screen.white_pixel, event_mask=X.ExposureMask | X.KeyPressMask, ) self.gc = self.window.create_gc( foreground = self.screen.black_pixel, background = self.screen.white_pixel, ) self.window.map() def loop(self): while True: e = self.display.next_event() if e.type == X.Expose: self.window.fill_rectangle(self.gc, 20, 20, 10, 10) self.window.draw_text(self.gc, 10, 50, self.msg) elif e.type == X.KeyPress: raise SystemExit if __name__ == "__main__": Window(display.Display(), "Hello, World!").loop()
import javax.swing.JFrame; import javax.swing.SwingUtilities; public class WindowExample { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { createAndShow(); } }; SwingUtilities.invokeLater(runnable); } static void createAndShow() { JFrame frame = new JFrame("Hello World"); frame.setSize(640,480); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Please provide an equivalent version of this Python code in Java.
states = { 'ready':{ 'prompt' : 'Machine ready: (d)eposit, or (q)uit?', 'responses' : ['d','q']}, 'waiting':{ 'prompt' : 'Machine waiting: (s)elect, or (r)efund?', 'responses' : ['s','r']}, 'dispense' : { 'prompt' : 'Machine dispensing: please (r)emove product', 'responses' : ['r']}, 'refunding' : { 'prompt' : 'Refunding money', 'responses' : []}, 'exit' :{} } transitions = { 'ready': { 'd': 'waiting', 'q': 'exit'}, 'waiting' : { 's' : 'dispense', 'r' : 'refunding'}, 'dispense' : { 'r' : 'ready'}, 'refunding' : { '' : 'ready'}} def Acceptor(prompt, valids): if not valids: print(prompt) return '' else: while True: resp = input(prompt)[0].lower() if resp in valids: return resp def finite_state_machine(initial_state, exit_state): response = True next_state = initial_state current_state = states[next_state] while response != exit_state: response = Acceptor(current_state['prompt'], current_state['responses']) next_state = transitions[next_state][response] current_state = states[next_state] if __name__ == "__main__": finite_state_machine('ready','q')
import java.util.*; public class FiniteStateMachine { private enum State { Ready(true, "Deposit", "Quit"), Waiting(true, "Select", "Refund"), Dispensing(true, "Remove"), Refunding(false, "Refunding"), Exiting(false, "Quiting"); State(boolean exp, String... in) { inputs = Arrays.asList(in); explicit = exp; } State nextState(String input, State current) { if (inputs.contains(input)) { return map.getOrDefault(input, current); } return current; } final List<String> inputs; final static Map<String, State> map = new HashMap<>(); final boolean explicit; static { map.put("Deposit", State.Waiting); map.put("Quit", State.Exiting); map.put("Select", State.Dispensing); map.put("Refund", State.Refunding); map.put("Remove", State.Ready); map.put("Refunding", State.Ready); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); State state = State.Ready; while (state != State.Exiting) { System.out.println(state.inputs); if (state.explicit){ System.out.print("> "); state = state.nextState(sc.nextLine().trim(), state); } else { state = state.nextState(state.inputs.get(0), state); } } } }
Port the following code from Python to Java with equivalent syntax and logic.
import turtle from itertools import cycle from time import sleep def rect(t, x, y): x2, y2 = x/2, y/2 t.setpos(-x2, -y2) t.pendown() for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: t.goto(pos) t.penup() def rects(t, colour, wait_between_rect=0.1): for x in range(550, 0, -25): t.color(colour) rect(t, x, x*.75) sleep(wait_between_rect) tl=turtle.Turtle() screen=turtle.Screen() screen.setup(620,620) screen.bgcolor('black') screen.title('Rosetta Code Vibrating Rectangles') tl.pensize(3) tl.speed(0) tl.penup() tl.ht() colours = 'red green blue orange white yellow'.split() for colour in cycle(colours): rects(tl, colour) sleep(0.5)
int counter = 100; void setup(){ size(1000,1000); } void draw(){ for(int i=0;i<20;i++){ fill(counter - 5*i); rect(10 + 20*i,10 + 20*i,980 - 40*i,980 - 40*i); } counter++; if(counter > 255) counter = 100; delay(100); }
Port the provided Python code into Java while preserving the original functionality.
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (ans,-ans%p) aa = 0 for i in xrange(1,p): temp = pow((i*i-n)%p,phi/2,p) if(temp == phi): aa = i break; exponent = convertToBase((p+1)/2,2) def cipollaMult((a,b),(c,d),w,p): return ((a*c+b*d*w)%p,(a*d+b*c)%p) x1 = (aa,1) x2 = cipollaMult(x1,x1,aa*aa-n,p) for i in xrange(1,len(exponent)): if(exponent[i] == 0): x2 = cipollaMult(x2,x1,aa*aa-n,p) x1 = cipollaMult(x1,x1,aa*aa-n,p) else: x1 = cipollaMult(x1,x2,aa*aa-n,p) x2 = cipollaMult(x2,x2,aa*aa-n,p) return (x1[0],-x1[0]%p) print "Roots of 2 mod 7: " +str(cipolla(2,7)) print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007)) print "Roots of 56 mod 101: " +str(cipolla(56,101)) print "Roots of 1 mod 11: " +str(cipolla(1,11)) print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Keep all operations the same but rewrite the snippet in Java.
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (ans,-ans%p) aa = 0 for i in xrange(1,p): temp = pow((i*i-n)%p,phi/2,p) if(temp == phi): aa = i break; exponent = convertToBase((p+1)/2,2) def cipollaMult((a,b),(c,d),w,p): return ((a*c+b*d*w)%p,(a*d+b*c)%p) x1 = (aa,1) x2 = cipollaMult(x1,x1,aa*aa-n,p) for i in xrange(1,len(exponent)): if(exponent[i] == 0): x2 = cipollaMult(x2,x1,aa*aa-n,p) x1 = cipollaMult(x1,x1,aa*aa-n,p) else: x1 = cipollaMult(x1,x2,aa*aa-n,p) x2 = cipollaMult(x2,x2,aa*aa-n,p) return (x1[0],-x1[0]%p) print "Roots of 2 mod 7: " +str(cipolla(2,7)) print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007)) print "Roots of 56 mod 101: " +str(cipolla(56,101)) print "Roots of 1 mod 11: " +str(cipolla(1,11)) print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Port the provided Python code into Java while preserving the original functionality.
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 CONST = 6364136223846793005 class PCG32(): def __init__(self, seed_state=None, seed_sequence=None): if all(type(x) == int for x in (seed_state, seed_sequence)): self.seed(seed_state, seed_sequence) else: self.state = self.inc = 0 def seed(self, seed_state, seed_sequence): self.state = 0 self.inc = ((seed_sequence << 1) | 1) & mask64 self.next_int() self.state = (self.state + seed_state) self.next_int() def next_int(self): "return random 32 bit unsigned int" old = self.state self.state = ((old * CONST) + self.inc) & mask64 xorshifted = (((old >> 18) ^ old) >> 27) & mask32 rot = (old >> 59) & mask32 answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)) answer = answer &mask32 return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32) if __name__ == '__main__': random_gen = PCG32() random_gen.seed(42, 54) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321, 1) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
public class PCG32 { private static final long N = 6364136223846793005L; private long state = 0x853c49e6748fea9bL; private long inc = 0xda3e39cb94b95bdbL; public void seed(long seedState, long seedSequence) { state = 0; inc = (seedSequence << 1) | 1; nextInt(); state = state + seedState; nextInt(); } public int nextInt() { long old = state; state = old * N + inc; int shifted = (int) (((old >>> 18) ^ old) >>> 27); int rot = (int) (old >>> 59); return (shifted >>> rot) | (shifted << ((~rot + 1) & 31)); } public double nextFloat() { var u = Integer.toUnsignedLong(nextInt()); return (double) u / (1L << 32); } public static void main(String[] args) { var r = new PCG32(); r.seed(42, 54); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; r.seed(987654321, 1); for (int i = 0; i < 100_000; i++) { int j = (int) Math.floor(r.nextFloat() * 5.0); counts[j]++; } System.out.println("The counts for 100,000 repetitions are:"); for (int i = 0; i < counts.length; i++) { System.out.printf(" %d : %d\n", i, counts[i]); } } }
Produce a functionally identical Java code for the snippet given in Python.
def ToReducedRowEchelonForm( M ): if not M: return lead = 0 rowCount = len(M) columnCount = len(M[0]) for r in range(rowCount): if lead >= columnCount: return i = r while M[i][lead] == 0: i += 1 if i == rowCount: i = r lead += 1 if columnCount == lead: return M[i],M[r] = M[r],M[i] lv = M[r][lead] M[r] = [ mrx / lv for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])] lead += 1 return M def pmtx(mtx): print ('\n'.join(''.join(' %4s' % col for col in row) for row in mtx)) def convolve(f, h): g = [0] * (len(f) + len(h) - 1) for hindex, hval in enumerate(h): for findex, fval in enumerate(f): g[hindex + findex] += fval * hval return g def deconvolve(g, f): lenh = len(g) - len(f) + 1 mtx = [[0 for x in range(lenh+1)] for y in g] for hindex in range(lenh): for findex, fval in enumerate(f): gindex = hindex + findex mtx[gindex][hindex] = fval for gindex, gval in enumerate(g): mtx[gindex][lenh] = gval ToReducedRowEchelonForm( mtx ) return [mtx[i][lenh] for i in range(lenh)] if __name__ == '__main__': h = [-8,-9,-3,-1,-6,7] f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7] assert convolve(f,h) == g assert deconvolve(g, f) == h
import java.util.Arrays; public class Deconvolution1D { public static int[] deconv(int[] g, int[] f) { int[] h = new int[g.length - f.length + 1]; for (int n = 0; n < h.length; n++) { h[n] = g[n]; int lower = Math.max(n - f.length + 1, 0); for (int i = lower; i < n; i++) h[n] -= h[i] * f[n - i]; h[n] /= f[0]; } return h; } public static void main(String[] args) { int[] h = { -8, -9, -3, -1, -6, 7 }; int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 }; int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7 }; StringBuilder sb = new StringBuilder(); sb.append("h = " + Arrays.toString(h) + "\n"); sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n"); sb.append("f = " + Arrays.toString(f) + "\n"); sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n"); System.out.println(sb.toString()); } }
Port the following code from Python to Java with equivalent syntax and logic.
import re _vowels = 'AEIOU' def replace_at(text, position, fromlist, tolist): for f, t in zip(fromlist, tolist): if text[position:].startswith(f): return ''.join([text[:position], t, text[position+len(f):]]) return text def replace_end(text, fromlist, tolist): for f, t in zip(fromlist, tolist): if text.endswith(f): return text[:-len(f)] + t return text def nysiis(name): name = re.sub(r'\W', '', name).upper() name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'], ['MCC', 'N', 'C', 'FF', 'FF', 'SSS']) name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'], ['Y', 'Y', 'D', 'D', 'D', 'D', 'D']) key, key1 = name[0], '' i = 1 while i < len(name): n_1, n = name[i-1], name[i] n1_ = name[i+1] if i+1 < len(name) else '' name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5) name = replace_at(name, i, 'QZM', 'GSN') name = replace_at(name, i, ['KN', 'K'], ['N', 'C']) name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF']) if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels): name = ''.join([name[:i], n_1, name[i+1:]]) if n == 'W' and n_1 in _vowels: name = ''.join([name[:i], 'A', name[i+1:]]) if key and key[-1] != name[i]: key += name[i] i += 1 key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', '']) return key1 + key if __name__ == '__main__': names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin', 'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence', 'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews', 'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison', "O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins', 'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV', 'knight', 'mitchell', "o'daniel"] for name in names: print('%15s: %s' % (name, nysiis(name)))
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}}; final static String Vowels = "AEIOU"; public static void main(String[] args) { stream(args).parallel().map(n -> transcode(n)).forEach(out::println); } static String transcode(String s) { int len = s.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z') sb.append((char) (c - 32)); else if (c >= 'A' && c <= 'Z') sb.append(c); } replace(sb, 0, first); replace(sb, sb.length() - 2, last); len = sb.length(); sb.append(" "); for (int i = 1; i < len; i++) { char prev = sb.charAt(i - 1); char curr = sb.charAt(i); char next = sb.charAt(i + 1); if (curr == 'E' && next == 'V') sb.replace(i, i + 2, "AF"); else if (isVowel(curr)) sb.setCharAt(i, 'A'); else if (curr == 'Q') sb.setCharAt(i, 'G'); else if (curr == 'Z') sb.setCharAt(i, 'S'); else if (curr == 'M') sb.setCharAt(i, 'N'); else if (curr == 'K' && next == 'N') sb.setCharAt(i, 'N'); else if (curr == 'K') sb.setCharAt(i, 'C'); else if (sb.indexOf("SCH", i) == i) sb.replace(i, i + 3, "SSS"); else if (curr == 'P' && next == 'H') sb.replace(i, i + 2, "FF"); else if (curr == 'H' && (!isVowel(prev) || !isVowel(next))) sb.setCharAt(i, prev); else if (curr == 'W' && isVowel(prev)) sb.setCharAt(i, prev); if (sb.charAt(i) == prev) { sb.deleteCharAt(i--); len--; } } sb.setLength(sb.length() - 1); int lastPos = sb.length() - 1; if (lastPos > 1) { if (sb.lastIndexOf("AY") == lastPos - 1) sb.delete(lastPos - 1, lastPos + 1).append("Y"); else if (sb.charAt(lastPos) == 'S') sb.setLength(lastPos); else if (sb.charAt(lastPos) == 'A') sb.setLength(lastPos); } if (sb.length() > 6) sb.insert(6, '[').append(']'); return String.format("%s -> %s", s, sb); } private static void replace(StringBuilder sb, int start, String[][] maps) { if (start >= 0) for (String[] map : maps) { if (sb.indexOf(map[0]) == start) { sb.replace(start, start + map[0].length(), map[1]); break; } } } private static boolean isVowel(char c) { return Vowels.indexOf(c) != -1; } }
Translate this program into Java but keep the logic exactly as in Python.
import re _vowels = 'AEIOU' def replace_at(text, position, fromlist, tolist): for f, t in zip(fromlist, tolist): if text[position:].startswith(f): return ''.join([text[:position], t, text[position+len(f):]]) return text def replace_end(text, fromlist, tolist): for f, t in zip(fromlist, tolist): if text.endswith(f): return text[:-len(f)] + t return text def nysiis(name): name = re.sub(r'\W', '', name).upper() name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'], ['MCC', 'N', 'C', 'FF', 'FF', 'SSS']) name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'], ['Y', 'Y', 'D', 'D', 'D', 'D', 'D']) key, key1 = name[0], '' i = 1 while i < len(name): n_1, n = name[i-1], name[i] n1_ = name[i+1] if i+1 < len(name) else '' name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5) name = replace_at(name, i, 'QZM', 'GSN') name = replace_at(name, i, ['KN', 'K'], ['N', 'C']) name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF']) if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels): name = ''.join([name[:i], n_1, name[i+1:]]) if n == 'W' and n_1 in _vowels: name = ''.join([name[:i], 'A', name[i+1:]]) if key and key[-1] != name[i]: key += name[i] i += 1 key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', '']) return key1 + key if __name__ == '__main__': names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin', 'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence', 'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews', 'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison', "O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins', 'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV', 'knight', 'mitchell', "o'daniel"] for name in names: print('%15s: %s' % (name, nysiis(name)))
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}}; final static String Vowels = "AEIOU"; public static void main(String[] args) { stream(args).parallel().map(n -> transcode(n)).forEach(out::println); } static String transcode(String s) { int len = s.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z') sb.append((char) (c - 32)); else if (c >= 'A' && c <= 'Z') sb.append(c); } replace(sb, 0, first); replace(sb, sb.length() - 2, last); len = sb.length(); sb.append(" "); for (int i = 1; i < len; i++) { char prev = sb.charAt(i - 1); char curr = sb.charAt(i); char next = sb.charAt(i + 1); if (curr == 'E' && next == 'V') sb.replace(i, i + 2, "AF"); else if (isVowel(curr)) sb.setCharAt(i, 'A'); else if (curr == 'Q') sb.setCharAt(i, 'G'); else if (curr == 'Z') sb.setCharAt(i, 'S'); else if (curr == 'M') sb.setCharAt(i, 'N'); else if (curr == 'K' && next == 'N') sb.setCharAt(i, 'N'); else if (curr == 'K') sb.setCharAt(i, 'C'); else if (sb.indexOf("SCH", i) == i) sb.replace(i, i + 3, "SSS"); else if (curr == 'P' && next == 'H') sb.replace(i, i + 2, "FF"); else if (curr == 'H' && (!isVowel(prev) || !isVowel(next))) sb.setCharAt(i, prev); else if (curr == 'W' && isVowel(prev)) sb.setCharAt(i, prev); if (sb.charAt(i) == prev) { sb.deleteCharAt(i--); len--; } } sb.setLength(sb.length() - 1); int lastPos = sb.length() - 1; if (lastPos > 1) { if (sb.lastIndexOf("AY") == lastPos - 1) sb.delete(lastPos - 1, lastPos + 1).append("Y"); else if (sb.charAt(lastPos) == 'S') sb.setLength(lastPos); else if (sb.charAt(lastPos) == 'A') sb.setLength(lastPos); } if (sb.length() > 6) sb.insert(6, '[').append(']'); return String.format("%s -> %s", s, sb); } private static void replace(StringBuilder sb, int start, String[][] maps) { if (start >= 0) for (String[] map : maps) { if (sb.indexOf(map[0]) == start) { sb.replace(start, start + map[0].length(), map[1]); break; } } } private static boolean isVowel(char c) { return Vowels.indexOf(c) != -1; } }
Port the provided Python code into Java while preserving the original functionality.
import re _vowels = 'AEIOU' def replace_at(text, position, fromlist, tolist): for f, t in zip(fromlist, tolist): if text[position:].startswith(f): return ''.join([text[:position], t, text[position+len(f):]]) return text def replace_end(text, fromlist, tolist): for f, t in zip(fromlist, tolist): if text.endswith(f): return text[:-len(f)] + t return text def nysiis(name): name = re.sub(r'\W', '', name).upper() name = replace_at(name, 0, ['MAC', 'KN', 'K', 'PH', 'PF', 'SCH'], ['MCC', 'N', 'C', 'FF', 'FF', 'SSS']) name = replace_end(name, ['EE', 'IE', 'DT', 'RT', 'RD', 'NT', 'ND'], ['Y', 'Y', 'D', 'D', 'D', 'D', 'D']) key, key1 = name[0], '' i = 1 while i < len(name): n_1, n = name[i-1], name[i] n1_ = name[i+1] if i+1 < len(name) else '' name = replace_at(name, i, ['EV'] + list(_vowels), ['AF'] + ['A']*5) name = replace_at(name, i, 'QZM', 'GSN') name = replace_at(name, i, ['KN', 'K'], ['N', 'C']) name = replace_at(name, i, ['SCH', 'PH'], ['SSS', 'FF']) if n == 'H' and (n_1 not in _vowels or n1_ not in _vowels): name = ''.join([name[:i], n_1, name[i+1:]]) if n == 'W' and n_1 in _vowels: name = ''.join([name[:i], 'A', name[i+1:]]) if key and key[-1] != name[i]: key += name[i] i += 1 key = replace_end(key, ['S', 'AY', 'A'], ['', 'Y', '']) return key1 + key if __name__ == '__main__': names = ['Bishop', 'Carlson', 'Carr', 'Chapman', 'Franklin', 'Greene', 'Harper', 'Jacobs', 'Larson', 'Lawrence', 'Lawson', 'Louis, XVI', 'Lynch', 'Mackenzie', 'Matthews', 'McCormack', 'McDaniel', 'McDonald', 'Mclaughlin', 'Morrison', "O'Banion", "O'Brien", 'Richards', 'Silva', 'Watkins', 'Wheeler', 'Willis', 'brown, sr', 'browne, III', 'browne, IV', 'knight', 'mitchell', "o'daniel"] for name in names: print('%15s: %s' % (name, nysiis(name)))
import static java.util.Arrays.*; import static java.lang.System.out; public class NYSIIS { final static String[][] first = {{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}}; final static String[][] last = {{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND", "D"}}; final static String Vowels = "AEIOU"; public static void main(String[] args) { stream(args).parallel().map(n -> transcode(n)).forEach(out::println); } static String transcode(String s) { int len = s.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= 'a' && c <= 'z') sb.append((char) (c - 32)); else if (c >= 'A' && c <= 'Z') sb.append(c); } replace(sb, 0, first); replace(sb, sb.length() - 2, last); len = sb.length(); sb.append(" "); for (int i = 1; i < len; i++) { char prev = sb.charAt(i - 1); char curr = sb.charAt(i); char next = sb.charAt(i + 1); if (curr == 'E' && next == 'V') sb.replace(i, i + 2, "AF"); else if (isVowel(curr)) sb.setCharAt(i, 'A'); else if (curr == 'Q') sb.setCharAt(i, 'G'); else if (curr == 'Z') sb.setCharAt(i, 'S'); else if (curr == 'M') sb.setCharAt(i, 'N'); else if (curr == 'K' && next == 'N') sb.setCharAt(i, 'N'); else if (curr == 'K') sb.setCharAt(i, 'C'); else if (sb.indexOf("SCH", i) == i) sb.replace(i, i + 3, "SSS"); else if (curr == 'P' && next == 'H') sb.replace(i, i + 2, "FF"); else if (curr == 'H' && (!isVowel(prev) || !isVowel(next))) sb.setCharAt(i, prev); else if (curr == 'W' && isVowel(prev)) sb.setCharAt(i, prev); if (sb.charAt(i) == prev) { sb.deleteCharAt(i--); len--; } } sb.setLength(sb.length() - 1); int lastPos = sb.length() - 1; if (lastPos > 1) { if (sb.lastIndexOf("AY") == lastPos - 1) sb.delete(lastPos - 1, lastPos + 1).append("Y"); else if (sb.charAt(lastPos) == 'S') sb.setLength(lastPos); else if (sb.charAt(lastPos) == 'A') sb.setLength(lastPos); } if (sb.length() > 6) sb.insert(6, '[').append(']'); return String.format("%s -> %s", s, sb); } private static void replace(StringBuilder sb, int start, String[][] maps) { if (start >= 0) for (String[] map : maps) { if (sb.indexOf(map[0]) == start) { sb.replace(start, start + map[0].length(), map[1]); break; } } } private static boolean isVowel(char c) { return Vowels.indexOf(c) != -1; } }
Translate the given Python code snippet into Java without altering its behavior.
def isDisarium(n): digitos = len(str(n)) suma = 0 x = n while x != 0: suma += (x % 10) ** digitos digitos -= 1 x //= 10 if suma == n: return True else: return False if __name__ == '__main__': limite = 19 cont = 0 n = 0 print("The first",limite,"Disarium numbers are:") while cont < limite: if isDisarium(n): print(n, end = " ") cont += 1 n += 1
import java.lang.Math; public class DisariumNumbers { public static boolean is_disarium(int num) { int n = num; int len = Integer.toString(n).length(); int sum = 0; int i = 1; while (n > 0) { sum += Math.pow(n % 10, len - i + 1); n /= 10; i ++; } return sum == num; } public static void main(String[] args) { int i = 0; int count = 0; while (count <= 18) { if (is_disarium(i)) { System.out.printf("%d ", i); count++; } i++; } System.out.printf("%s", "\n"); } }
Produce a language-to-language conversion: from Python to Java, same semantics.
def isDisarium(n): digitos = len(str(n)) suma = 0 x = n while x != 0: suma += (x % 10) ** digitos digitos -= 1 x //= 10 if suma == n: return True else: return False if __name__ == '__main__': limite = 19 cont = 0 n = 0 print("The first",limite,"Disarium numbers are:") while cont < limite: if isDisarium(n): print(n, end = " ") cont += 1 n += 1
import java.lang.Math; public class DisariumNumbers { public static boolean is_disarium(int num) { int n = num; int len = Integer.toString(n).length(); int sum = 0; int i = 1; while (n > 0) { sum += Math.pow(n % 10, len - i + 1); n /= 10; i ++; } return sum == num; } public static void main(String[] args) { int i = 0; int count = 0; while (count <= 18) { if (is_disarium(i)) { System.out.printf("%d ", i); count++; } i++; } System.out.printf("%s", "\n"); } }
Please provide an equivalent version of this Python code in Java.
from turtle import * import math speed(0) hideturtle() part_ratio = 2 * math.cos(math.radians(72)) side_ratio = 1 / (part_ratio + 2) hide_turtles = True path_color = "black" fill_color = "black" def pentagon(t, s): t.color(path_color, fill_color) t.pendown() t.right(36) t.begin_fill() for i in range(5): t.forward(s) t.right(72) t.end_fill() def sierpinski(i, t, s): t.setheading(0) new_size = s * side_ratio if i > 1: i -= 1 for j in range(4): t.right(36) short = s * side_ratio / part_ratio dist = [short, s, s, short][j] spawn = Turtle() if hide_turtles:spawn.hideturtle() spawn.penup() spawn.setposition(t.position()) spawn.setheading(t.heading()) spawn.forward(dist) sierpinski(i, spawn, new_size) sierpinski(i, t, new_size) else: pentagon(t, s) del t def main(): t = Turtle() t.hideturtle() t.penup() screen = t.getscreen() y = screen.window_height() t.goto(0, y/2-20) i = 5 size = 300 size *= part_ratio sierpinski(i, t, size) main()
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees072) * 2); final int margin = 20; int limit = 0; Random r = new Random(); public SierpinskiPentagon() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(3000, (ActionEvent e) -> { limit++; if (limit >= 5) limit = 0; repaint(); }).start(); } void drawPentagon(Graphics2D g, double x, double y, double side, int depth) { double angle = 3 * degrees072; if (depth == 0) { Path2D p = new Path2D.Double(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { x = x + cos(angle) * side; y = y - sin(angle) * side; p.lineTo(x, y); angle += degrees072; } g.setColor(RandomHue.next()); g.fill(p); } else { side *= scaleFactor; double distance = side + side * cos(degrees072) * 2; for (int i = 0; i < 5; i++) { x = x + cos(angle) * distance; y = y - sin(angle) * distance; drawPentagon(g, x, y, side, depth - 1); angle += degrees072; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int w = getWidth(); double radius = w / 2 - 2 * margin; double side = radius * sin(PI / 5) * 2; drawPentagon(g, w / 2, 3 * margin, side, limit); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Sierpinski Pentagon"); f.setResizable(true); f.add(new SierpinskiPentagon(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } } class RandomHue { final static double goldenRatioConjugate = (sqrt(5) - 1) / 2; private static double hue = Math.random(); static Color next() { hue = (hue + goldenRatioConjugate) % 1; return Color.getHSBColor((float) hue, 1, 1); } }
Translate this program into Java but keep the logic exactly as in Python.
from PIL import Image image = Image.open("lena.jpg") width, height = image.size amount = width * height total = 0 bw_image = Image.new('L', (width, height), 0) bm_image = Image.new('1', (width, height), 0) for h in range(0, height): for w in range(0, width): r, g, b = image.getpixel((w, h)) greyscale = int((r + g + b) / 3) total += greyscale bw_image.putpixel((w, h), gray_scale) avg = total / amount black = 0 white = 1 for h in range(0, height): for w in range(0, width): v = bw_image.getpixel((w, h)) if v >= avg: bm_image.putpixel((w, h), white) else: bm_image.putpixel((w, h), black) bw_image.show() bm_image.show()
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public enum ImageProcessing { ; public static void main(String[] args) throws IOException { BufferedImage img = ImageIO.read(new File("example.png")); BufferedImage bwimg = toBlackAndWhite(img); ImageIO.write(bwimg, "png", new File("example-bw.png")); } private static int luminance(int rgb) { int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = rgb & 0xFF; return (r + b + g) / 3; } private static BufferedImage toBlackAndWhite(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); int[] histo = computeHistogram(img); int median = getMedian(width * height, histo); BufferedImage bwimg = new BufferedImage(width, height, img.getType()); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000); } } return bwimg; } private static int[] computeHistogram(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); int[] histo = new int[256]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { histo[luminance(img.getRGB(x, y))]++; } } return histo; } private static int getMedian(int total, int[] histo) { int median = 0; int sum = 0; for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) { sum += histo[i]; median++; } return median; } }
Transform the following Python implementation into Java, maintaining the same output and logic.
import threading from time import sleep res = 2 sema = threading.Semaphore(res) class res_thread(threading.Thread): def run(self): global res n = self.getName() for i in range(1, 4): sema.acquire() res = res - 1 print n, "+ res count", res sleep(2) res = res + 1 print n, "- res count", res sema.release() for i in range(1, 5): t = res_thread() t.start()
import java.util.concurrent.Semaphore; public class VolatileClass{ public Semaphore mutex = new Semaphore(1); public void needsToBeSynched(){ } }
Write the same algorithm in Java as shown in this Python implementation.
import time def main(bpm = 72, bpb = 4): sleep = 60.0 / bpm counter = 0 while True: counter += 1 if counter % bpb: print 'tick' else: print 'TICK' time.sleep(sleep) main()
class Metronome{ double bpm; int measure, counter; public Metronome(double bpm, int measure){ this.bpm = bpm; this.measure = measure; } public void start(){ while(true){ try { Thread.sleep((long)(1000*(60.0/bpm))); }catch(InterruptedException e) { e.printStackTrace(); } counter++; if (counter%measure==0){ System.out.println("TICK"); }else{ System.out.println("TOCK"); } } } } public class test { public static void main(String[] args) { Metronome metronome1 = new Metronome(120,4); metronome1.start(); } }
Translate this program into Java but keep the logic exactly as in Python.
from itertools import count, islice, takewhile from math import gcd def EKG_gen(start=2): c = count(start + 1) last, so_far = start, list(range(2, start)) yield 1, [] yield last, [] while True: for index, sf in enumerate(so_far): if gcd(last, sf) > 1: last = so_far.pop(index) yield last, so_far[::] break else: so_far.append(next(c)) def find_convergence(ekgs=(5,7)): "Returns the convergence point or zero if not found within the limit" ekg = [EKG_gen(n) for n in ekgs] for e in ekg: next(e) return 2 + len(list(takewhile(lambda state: not all(state[0] == s for s in state[1:]), zip(*ekg)))) if __name__ == '__main__': for start in 2, 5, 7, 9, 10: print(f"EKG({start}):", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1]) print(f"\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!")
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class EKGSequenceConvergence { public static void main(String[] args) { System.out.println("Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10]."); for ( int i : new int[] {2, 5, 7, 9, 10} ) { System.out.printf("EKG[%d] = %s%n", i, ekg(i, 10)); } System.out.println("Calculate and show here at which term EKG[5] and EKG[7] converge."); List<Integer> ekg5 = ekg(5, 100); List<Integer> ekg7 = ekg(7, 100); for ( int i = 1 ; i < ekg5.size() ; i++ ) { if ( ekg5.get(i) == ekg7.get(i) && sameSeq(ekg5, ekg7, i)) { System.out.printf("EKG[%d](%d) = EKG[%d](%d) = %d, and are identical from this term on%n", 5, i+1, 7, i+1, ekg5.get(i)); break; } } } private static boolean sameSeq(List<Integer> seq1, List<Integer> seq2, int n) { List<Integer> list1 = new ArrayList<>(seq1.subList(0, n)); Collections.sort(list1); List<Integer> list2 = new ArrayList<>(seq2.subList(0, n)); Collections.sort(list2); for ( int i = 0 ; i < n ; i++ ) { if ( list1.get(i) != list2.get(i) ) { return false; } } return true; } private static List<Integer> ekg(int two, int maxN) { List<Integer> result = new ArrayList<>(); result.add(1); result.add(two); Map<Integer,Integer> seen = new HashMap<>(); seen.put(1, 1); seen.put(two, 1); int minUnseen = two == 2 ? 3 : 2; int prev = two; for ( int n = 3 ; n <= maxN ; n++ ) { int test = minUnseen - 1; while ( true ) { test++; if ( ! seen.containsKey(test) && gcd(test, prev) > 1 ) { result.add(test); seen.put(test, n); prev = test; if ( minUnseen == test ) { do { minUnseen++; } while ( seen.containsKey(minUnseen) ); } break; } } } return result; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }
Change the following Python code into Java without altering its purpose.
def is_repeated(text): 'check if the first part of the string is repeated throughout the string' for x in range(len(text)//2, 0, -1): if text.startswith(text[x:]): return x return 0 matchstr = for line in matchstr.split(): ln = is_repeated(line) print('%r has a repetition length of %i i.e. %s' % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s : %s%n", s, repString(s)); } static String repString(String s) { int len = s.length(); outer: for (int part = len / 2; part > 0; part--) { int tail = len % part; if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail))) continue; for (int j = 0; j < len / part - 1; j++) { int a = j * part; int b = (j + 1) * part; int c = (j + 2) * part; if (!s.substring(a, b).equals(s.substring(b, c))) continue outer; } return s.substring(0, part); } return "none"; } }
Rewrite this program in Java while keeping its functionality equivalent to the Python version.
import time print "\033[?1049h\033[H" print "Alternate buffer!" for i in xrange(5, 0, -1): print "Going back in:", i time.sleep(1) print "\033[?1049l"
public class PreserveScreen { public static void main(String[] args) throws InterruptedException { System.out.print("\033[?1049h\033[H"); System.out.println("Alternate screen buffer\n"); for (int i = 5; i > 0; i--) { String s = (i > 1) ? "s" : ""; System.out.printf("\rgoing back in %d second%s...", i, s); Thread.sleep(1000); } System.out.print("\033[?1049l"); } }