Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate an equivalent Java version of this Python code. | >>> from math import floor, sqrt
>>> def non_square(n):
return n + floor(1/2 + sqrt(n))
>>>
>>> print(*map(non_square, range(1, 23)))
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
>>>
>>> def is_square(n):
return sqrt(n).is_integer()
>>> non_squares = map(non_square, range(1, 10 ** 6))
>>> next(filter(is_square, non_squares))
StopIteration Traceback (most recent call last)
<ipython-input-45-f32645fc1c0a> in <module>()
1 non_squares = map(non_square, range(1, 10 ** 6))
----> 2 next(filter(is_square, non_squares))
StopIteration:
| public class SeqNonSquares {
public static int nonsqr(int n) {
return n + (int)Math.round(Math.sqrt(n));
}
public static void main(String[] args) {
for (int i = 1; i < 23; i++)
System.out.print(nonsqr(i) + " ");
System.out.println();
for (int i = 1; i < 1000000; i++) {
double j = Math.sqrt(nonsqr(i));
assert j != Math.floor(j);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | >>> s = 'abcdefgh'
>>> n, m, char, chars = 2, 3, 'd', 'cd'
>>>
>>> s[n-1:n+m-1]
'bcd'
>>>
>>> s[n-1:]
'bcdefgh'
>>>
>>> s[:-1]
'abcdefg'
>>>
>>> indx = s.index(char)
>>> s[indx:indx+m]
'def'
>>>
>>> indx = s.index(chars)
>>> s[indx:indx+m]
'cde'
>>>
| public static String Substring(String str, int n, int m){
return str.substring(n, n+m);
}
public static String Substring(String str, int n){
return str.substring(n);
}
public static String Substring(String str){
return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, int m){
return str.substring(str.indexOf(c), str.indexOf(c)+m+1);
}
public static String Substring(String str, String sub, int m){
return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | >>> def jortsort(sequence):
return list(sequence) == sorted(sequence)
>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:
print(f'jortsort({repr(data)}) is {jortsort(data)}')
jortsort((1, 2, 4, 3)) is False
jortsort((14, 6, 8)) is False
jortsort(['a', 'c']) is True
jortsort(['s', 'u', 'x']) is True
jortsort('CVGH') is False
jortsort('PQRST') is True
>>>
| public class JortSort {
public static void main(String[] args) {
System.out.println(jortSort(new int[]{1, 2, 3}));
}
static boolean jortSort(int[] arr) {
return true;
}
}
|
Write the same code in Java as shown below in Python. | import calendar
calendar.isleap(year)
| import java.util.GregorianCalendar;
import java.text.MessageFormat;
public class Leapyear{
public static void main(String[] argv){
int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
GregorianCalendar cal = new GregorianCalendar();
for(int year : yrs){
System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.",
year, cal.isLeapYear(year), isLeapYear(year)));
}
}
public static boolean isLeapYear(int year){
return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from __future__ import print_function
from scipy.misc import factorial as fact
from scipy.misc import comb
def perm(N, k, exact=0):
return comb(N, k, exact) * fact(k, exact)
exact=True
print('Sample Perms 1..12')
for N in range(1, 13):
k = max(N-2, 1)
print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n')
print('\n\nSample Combs 10..60')
for N in range(10, 61, 10):
k = N-2
print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n')
exact=False
print('\n\nSample Perms 5..1500 Using FP approximations')
for N in [5, 15, 150, 1500, 15000]:
k = N-2
print('%iP%i =' % (N, k), perm(N, k, exact))
print('\nSample Combs 100..1000 Using FP approximations')
for N in range(100, 1001, 100):
k = N-2
print('%iC%i =' % (N, k), comb(N, k, exact))
| import java.math.BigInteger;
public class CombinationsAndPermutations {
public static void main(String[] args) {
System.out.println(Double.MAX_VALUE);
System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:");
for ( int n = 1 ; n <= 12 ; n++ ) {
int k = n / 2;
System.out.printf("%d P %d = %s%n", n, k, permutation(n, k));
}
System.out.println();
System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:");
for ( int n = 10 ; n <= 60 ; n += 5 ) {
int k = n / 2;
System.out.printf("%d C %d = %s%n", n, k, combination(n, k));
}
System.out.println();
System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:");
System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50));
for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {
int k = n / 2;
System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50));
}
System.out.println();
System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:");
for ( int n = 100 ; n <= 1000 ; n += 100 ) {
int k = n / 2;
System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50));
}
}
private static String display(BigInteger val, int precision) {
String s = val.toString();
precision = Math.min(precision, s.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, 1));
sb.append(".");
sb.append(s.substring(1, precision));
sb.append(" * 10^");
sb.append(s.length()-1);
return sb.toString();
}
public static BigInteger combination(int n, int k) {
if ( n-k < k ) {
k = n-k;
}
BigInteger result = permutation(n, k);
while ( k > 0 ) {
result = result.divide(BigInteger.valueOf(k));
k--;
}
return result;
}
public static BigInteger permutation(int n, int k) {
BigInteger result = BigInteger.ONE;
for ( int i = n ; i >= n-k+1 ; i-- ) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | n=13
print(sorted(range(1,n+1), key=str))
| import java.util.List;
import java.util.stream.*;
public class LexicographicalNumbers {
static List<Integer> lexOrder(int n) {
int first = 1, last = n;
if (n < 1) {
first = n;
last = 1;
}
return IntStream.rangeClosed(first, last)
.mapToObj(Integer::toString)
.sorted()
.map(Integer::valueOf)
.collect(Collectors.toList());
}
public static void main(String[] args) {
System.out.println("In lexicographical order:\n");
int[] ints = {0, 5, 13, 21, -22};
for (int n : ints) {
System.out.printf("%3d: %s\n", n, lexOrder(n));
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
for h in ("m", "b", "tr", "quadr", "quint", "sext",
"sept", "oct", "non", "dec")]
def nonzero(c, n, connect=''):
return "" if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) + " thousand"
else:
return spell_integer(n) + " " + HUGE[e]
def base1000_rev(n):
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return "minus " + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero("-", b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
else:
num = ", ".join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num)
if __name__ == '__main__':
for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):
print('%+4i -> %s' % (n, spell_integer(n)))
print('')
n = 201021002001
while n:
print('%-12i -> %s' % (n, spell_integer(n)))
n //= -10
print('%-12i -> %s' % (n, spell_integer(n)))
print('')
| module NumberNames
{
void run()
{
@Inject Console console;
Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,
123456789000, 0x123456789ABCDEF];
for (Int test : tests)
{
console.print($"{test} = {toEnglish(test)}");
}
}
static String[] digits = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"];
static String[] teens = ["ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
static String[] tens = ["zero", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"];
static String[] ten3rd = ["?", "thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"];
static String toEnglish(Int n)
{
StringBuffer buf = new StringBuffer();
if (n < 0)
{
"negative ".appendTo(buf);
n = -n;
}
format3digits(n, buf);
return buf.toString();
}
static void format3digits(Int n, StringBuffer buf, Int nested=0)
{
(Int left, Int right) = n /% 1000;
if (left != 0)
{
format3digits(left, buf, nested+1);
}
if (right != 0 || (left == 0 && nested==0))
{
if (right >= 100)
{
(left, right) = (right /% 100);
digits[left].appendTo(buf);
" hundred ".appendTo(buf);
if (right != 0)
{
format2digits(right, buf);
}
}
else
{
format2digits(right, buf);
}
if (nested > 0)
{
ten3rd[nested].appendTo(buf).add(' ');
}
}
}
static void format2digits(Int n, StringBuffer buf)
{
switch (n)
{
case 0..9:
digits[n].appendTo(buf).add(' ');
break;
case 10..19:
teens[n-10].appendTo(buf).add(' ');
break;
default:
(Int left, Int right) = n /% 10;
tens[left].appendTo(buf);
if (right == 0)
{
buf.add(' ');
}
else
{
buf.add('-');
digits[right].appendTo(buf).add(' ');
}
break;
}
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | TENS = [None, None, "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
SMALL = ["zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
HUGE = [None, None] + [h + "illion"
for h in ("m", "b", "tr", "quadr", "quint", "sext",
"sept", "oct", "non", "dec")]
def nonzero(c, n, connect=''):
return "" if n == 0 else connect + c + spell_integer(n)
def last_and(num):
if ',' in num:
pre, last = num.rsplit(',', 1)
if ' and ' not in last:
last = ' and' + last
num = ''.join([pre, ',', last])
return num
def big(e, n):
if e == 0:
return spell_integer(n)
elif e == 1:
return spell_integer(n) + " thousand"
else:
return spell_integer(n) + " " + HUGE[e]
def base1000_rev(n):
while n != 0:
n, r = divmod(n, 1000)
yield r
def spell_integer(n):
if n < 0:
return "minus " + spell_integer(-n)
elif n < 20:
return SMALL[n]
elif n < 100:
a, b = divmod(n, 10)
return TENS[a] + nonzero("-", b)
elif n < 1000:
a, b = divmod(n, 100)
return SMALL[a] + " hundred" + nonzero(" ", b, ' and')
else:
num = ", ".join([big(e, x) for e, x in
enumerate(base1000_rev(n)) if x][::-1])
return last_and(num)
if __name__ == '__main__':
for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29):
print('%+4i -> %s' % (n, spell_integer(n)))
print('')
n = 201021002001
while n:
print('%-12i -> %s' % (n, spell_integer(n)))
n //= -10
print('%-12i -> %s' % (n, spell_integer(n)))
print('')
| module NumberNames
{
void run()
{
@Inject Console console;
Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000,
123456789000, 0x123456789ABCDEF];
for (Int test : tests)
{
console.print($"{test} = {toEnglish(test)}");
}
}
static String[] digits = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"];
static String[] teens = ["ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
static String[] tens = ["zero", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"];
static String[] ten3rd = ["?", "thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"];
static String toEnglish(Int n)
{
StringBuffer buf = new StringBuffer();
if (n < 0)
{
"negative ".appendTo(buf);
n = -n;
}
format3digits(n, buf);
return buf.toString();
}
static void format3digits(Int n, StringBuffer buf, Int nested=0)
{
(Int left, Int right) = n /% 1000;
if (left != 0)
{
format3digits(left, buf, nested+1);
}
if (right != 0 || (left == 0 && nested==0))
{
if (right >= 100)
{
(left, right) = (right /% 100);
digits[left].appendTo(buf);
" hundred ".appendTo(buf);
if (right != 0)
{
format2digits(right, buf);
}
}
else
{
format2digits(right, buf);
}
if (nested > 0)
{
ten3rd[nested].appendTo(buf).add(' ');
}
}
}
static void format2digits(Int n, StringBuffer buf)
{
switch (n)
{
case 0..9:
digits[n].appendTo(buf).add(' ');
break;
case 10..19:
teens[n-10].appendTo(buf).add(' ');
break;
default:
(Int left, Int right) = n /% 10;
tens[left].appendTo(buf);
if (right == 0)
{
buf.add(' ');
}
else
{
buf.add('-');
digits[right].appendTo(buf).add(' ');
}
break;
}
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | A = 'I am string'
B = 'I am string too'
if len(A) > len(B):
print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings')
print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings')
print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings')
else:
print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
| package stringlensort;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
public class ReportStringLengths {
public static void main(String[] args) {
String[] list = {"abcd", "123456789", "abcdef", "1234567"};
String[] strings = args.length > 0 ? args : list;
compareAndReportStringsLength(strings);
}
public static void compareAndReportStringsLength(String[] strings) {
compareAndReportStringsLength(strings, System.out);
}
public static void compareAndReportStringsLength(String[] strings, PrintStream stream) {
if (strings.length > 0) {
strings = strings.clone();
final String QUOTE = "\"";
Arrays.sort(strings, Comparator.comparing(String::length));
int min = strings[0].length();
int max = strings[strings.length - 1].length();
for (int i = strings.length - 1; i >= 0; i--) {
int length = strings[i].length();
String predicate;
if (length == max) {
predicate = "is the longest string";
} else if (length == min) {
predicate = "is the shortest string";
} else {
predicate = "is neither the longest nor the shortest string";
}
stream.println(QUOTE + strings[i] + QUOTE + " has length " + length
+ " and " + predicate);
}
}
}
}
|
Port the provided Python code into Java while preserving the original functionality. | def shell(seq):
inc = len(seq) // 2
while inc:
for i, el in enumerate(seq[inc:], inc):
while i >= inc and seq[i - inc] > el:
seq[i] = seq[i - inc]
i -= inc
seq[i] = el
inc = 1 if inc == 2 else inc * 5 // 11
| public static void shell(int[] a) {
int increment = a.length / 2;
while (increment > 0) {
for (int i = increment; i < a.length; i++) {
int j = i;
int temp = a[i];
while (j >= increment && a[j - increment] > temp) {
a[j] = a[j - increment];
j = j - increment;
}
a[j] = temp;
}
if (increment == 2) {
increment = 1;
} else {
increment *= (5.0 / 11);
}
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from collections import deque
some_list = deque(["a", "b", "c"])
print(some_list)
some_list.appendleft("Z")
print(some_list)
for value in reversed(some_list):
print(value)
| import java.util.LinkedList;
public class DoublyLinkedList {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.addFirst("Add First");
list.addLast("Add Last 1");
list.addLast("Add Last 2");
list.addLast("Add Last 1");
traverseList(list);
list.removeFirstOccurrence("Add Last 1");
traverseList(list);
}
private static void traverseList(LinkedList<String> list) {
System.out.println("Traverse List:");
for ( int i = 0 ; i < list.size() ; i++ ) {
System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
}
System.out.println();
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | import collections, sys
def filecharcount(openfile):
return sorted(collections.Counter(c for l in openfile for c in l).items())
f = open(sys.argv[1])
print(filecharcount(f))
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class LetterFreq {
public static int[] countLetters(String filename) throws IOException{
int[] freqs = new int[26];
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line = in.readLine()) != null){
line = line.toUpperCase();
for(char ch:line.toCharArray()){
if(Character.isLetter(ch)){
freqs[ch - 'A']++;
}
}
}
in.close();
return freqs;
}
public static void main(String[] args) throws IOException{
System.out.println(Arrays.toString(countLetters("filename.txt")));
}
}
|
Write a version of this Python function in Java with identical behavior. | from itertools import combinations as comb
def statistic(ab, a):
sumab, suma = sum(ab), sum(a)
return ( suma / len(a) -
(sumab -suma) / (len(ab) - len(a)) )
def permutationTest(a, b):
ab = a + b
Tobs = statistic(ab, a)
under = 0
for count, perm in enumerate(comb(ab, len(a)), 1):
if statistic(ab, perm) <= Tobs:
under += 1
return under * 100. / count
treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]
controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
under = permutationTest(treatmentGroup, controlGroup)
print("under=%.2f%%, over=%.2f%%" % (under, 100. - under))
| public class PermutationTest {
private static final int[] data = new int[]{
85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98
};
private static int pick(int at, int remain, int accu, int treat) {
if (remain == 0) return (accu > treat) ? 1 : 0;
return pick(at - 1, remain - 1, accu + data[at - 1], treat)
+ ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);
}
public static void main(String[] args) {
int treat = 0;
double total = 1.0;
for (int i = 0; i <= 8; ++i) {
treat += data[i];
}
for (int i = 19; i >= 11; --i) {
total *= i;
}
for (int i = 9; i >= 1; --i) {
total /= i;
}
int gt = pick(19, 9, 0, treat);
int le = (int) (total - gt);
System.out.printf("<= : %f%% %d\n", 100.0 * le / total, le);
System.out.printf(" > : %f%% %d\n", 100.0 * gt / total, gt);
}
}
|
Write a version of this Python function in Java with identical behavior. |
def isPrime(n) :
if (n < 2) :
return False
for i in range(2, n + 1) :
if (i * i <= n and n % i == 0) :
return False
return True
def mobius(N) :
if (N == 1) :
return 1
p = 0
for i in range(1, N + 1) :
if (N % i == 0 and
isPrime(i)) :
if (N % (i * i) == 0) :
return 0
else :
p = p + 1
if(p % 2 != 0) :
return -1
else :
return 1
print("Mobius numbers from 1..99:")
for i in range(1, 100):
print(f"{mobius(i):>4}", end = '')
if i % 20 == 0: print()
| public class MöbiusFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the möbius function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", möbiusFunction(n));
if ( (n+1) % 20 == 0 ) {
System.out.printf("%n");
}
}
}
private static int MU_MAX = 1_000_000;
private static int[] MU = null;
private static int möbiusFunction(int n) {
if ( MU != null ) {
return MU[n];
}
MU = new int[MU_MAX+1];
int sqrt = (int) Math.sqrt(MU_MAX);
for ( int i = 0 ; i < MU_MAX ; i++ ) {
MU[i] = 1;
}
for ( int i = 2 ; i <= sqrt ; i++ ) {
if ( MU[i] == 1 ) {
for ( int j = i ; j <= MU_MAX ; j += i ) {
MU[j] *= -i;
}
for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {
MU[j] = 0;
}
}
}
for ( int i = 2 ; i <= MU_MAX ; i++ ) {
if ( MU[i] == i ) {
MU[i] = 1;
}
else if ( MU[i] == -i ) {
MU[i] = -1;
}
else if ( MU[i] < 0 ) {
MU[i] = 1;
}
else if ( MU[i] > 0 ) {
MU[i] = -1;
}
}
return MU[n];
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | next = str(int('123') + 1)
| String s = "12345";
IntLiteral lit1 = new IntLiteral(s);
IntLiteral lit2 = 6789;
++lit1;
++lit2;
|
Keep all operations the same but rewrite the snippet in Java. | >>> def stripchars(s, chars):
... return s.translate(None, chars)
...
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws soul strppr. Sh took my hrt!'
| class StripChars {
public static String stripChars(String inString, String toStrip) {
return inString.replaceAll("[" + toStrip + "]", "");
}
public static void main(String[] args) {
String sentence = "She was a soul stripper. She took my heart!";
String chars = "aei";
System.out.println("sentence: " + sentence);
System.out.println("to strip: " + chars);
System.out.println("stripped: " + stripChars(sentence, chars));
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from itertools import permutations
in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
| import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class PermutationSort
{
public static void main(String[] args)
{
int[] a={3,2,1,8,9,4,6};
System.out.println("Unsorted: " + Arrays.toString(a));
a=pSort(a);
System.out.println("Sorted: " + Arrays.toString(a));
}
public static int[] pSort(int[] a)
{
List<int[]> list=new ArrayList<int[]>();
permute(a,a.length,list);
for(int[] x : list)
if(isSorted(x))
return x;
return a;
}
private static void permute(int[] a, int n, List<int[]> list)
{
if (n == 1)
{
int[] b=new int[a.length];
System.arraycopy(a, 0, b, 0, a.length);
list.add(b);
return;
}
for (int i = 0; i < n; i++)
{
swap(a, i, n-1);
permute(a, n-1, list);
swap(a, i, n-1);
}
}
private static boolean isSorted(int[] a)
{
for(int i=1;i<a.length;i++)
if(a[i-1]>a[i])
return false;
return true;
}
private static void swap(int[] arr,int i, int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | from math import fsum
def average(x):
return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
| public static double avg(double... arr) {
double sum = 0.0;
for (double x : arr) {
sum += x;
}
return sum / arr.length;
}
|
Convert this Python snippet to Java and keep its semantics consistent. | command_table_text =
user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin"
def find_abbreviations_length(command_table_text):
command_table = dict()
input_iter = iter(command_table_text.split())
word = None
try:
while True:
if word is None:
word = next(input_iter)
abbr_len = next(input_iter, len(word))
try:
command_table[word] = int(abbr_len)
word = None
except ValueError:
command_table[word] = len(word)
word = abbr_len
except StopIteration:
pass
return command_table
def find_abbreviations(command_table):
abbreviations = dict()
for command, min_abbr_len in command_table.items():
for l in range(min_abbr_len, len(command)+1):
abbr = command[:l].lower()
abbreviations[abbr] = command.upper()
return abbreviations
def parse_user_string(user_string, abbreviations):
user_words = [word.lower() for word in user_string.split()]
commands = [abbreviations.get(user_word, "*error*") for user_word in user_words]
return " ".join(commands)
command_table = find_abbreviations_length(command_table_text)
abbreviations_table = find_abbreviations(command_table)
full_words = parse_user_string(user_words, abbreviations_table)
print("user words:", user_words)
print("full words:", full_words)
| import java.util.*;
public class Abbreviations {
public static void main(String[] args) {
CommandList commands = new CommandList(commandTable);
String input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
System.out.println(" input: " + input);
System.out.println("output: " + test(commands, input));
}
private static String test(CommandList commands, String input) {
StringBuilder output = new StringBuilder();
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
String word = scanner.next();
if (output.length() > 0)
output.append(' ');
Command cmd = commands.findCommand(word);
if (cmd != null)
output.append(cmd.cmd);
else
output.append("*error*");
}
return output.toString();
}
private static String commandTable =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
private static class Command {
private Command(String cmd, int minLength) {
this.cmd = cmd;
this.minLength = minLength;
}
private boolean match(String str) {
int olen = str.length();
return olen >= minLength && olen <= cmd.length()
&& cmd.regionMatches(true, 0, str, 0, olen);
}
private String cmd;
private int minLength;
}
private static Integer parseInteger(String word) {
try {
return Integer.valueOf(word);
} catch (NumberFormatException ex) {
return null;
}
}
private static class CommandList {
private CommandList(String table) {
Scanner scanner = new Scanner(table);
List<String> words = new ArrayList<>();
while (scanner.hasNext()) {
String word = scanner.next();
words.add(word.toUpperCase());
}
for (int i = 0, n = words.size(); i < n; ++i) {
String word = words.get(i);
int len = word.length();
if (i + 1 < n) {
Integer number = parseInteger(words.get(i + 1));
if (number != null) {
len = number.intValue();
++i;
}
}
commands.add(new Command(word, len));
}
}
private Command findCommand(String word) {
for (Command command : commands) {
if (command.match(word))
return command;
}
return null;
}
private List<Command> commands = new ArrayList<>();
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | command_table_text =
user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin"
def find_abbreviations_length(command_table_text):
command_table = dict()
input_iter = iter(command_table_text.split())
word = None
try:
while True:
if word is None:
word = next(input_iter)
abbr_len = next(input_iter, len(word))
try:
command_table[word] = int(abbr_len)
word = None
except ValueError:
command_table[word] = len(word)
word = abbr_len
except StopIteration:
pass
return command_table
def find_abbreviations(command_table):
abbreviations = dict()
for command, min_abbr_len in command_table.items():
for l in range(min_abbr_len, len(command)+1):
abbr = command[:l].lower()
abbreviations[abbr] = command.upper()
return abbreviations
def parse_user_string(user_string, abbreviations):
user_words = [word.lower() for word in user_string.split()]
commands = [abbreviations.get(user_word, "*error*") for user_word in user_words]
return " ".join(commands)
command_table = find_abbreviations_length(command_table_text)
abbreviations_table = find_abbreviations(command_table)
full_words = parse_user_string(user_words, abbreviations_table)
print("user words:", user_words)
print("full words:", full_words)
| import java.util.*;
public class Abbreviations {
public static void main(String[] args) {
CommandList commands = new CommandList(commandTable);
String input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
System.out.println(" input: " + input);
System.out.println("output: " + test(commands, input));
}
private static String test(CommandList commands, String input) {
StringBuilder output = new StringBuilder();
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
String word = scanner.next();
if (output.length() > 0)
output.append(' ');
Command cmd = commands.findCommand(word);
if (cmd != null)
output.append(cmd.cmd);
else
output.append("*error*");
}
return output.toString();
}
private static String commandTable =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
private static class Command {
private Command(String cmd, int minLength) {
this.cmd = cmd;
this.minLength = minLength;
}
private boolean match(String str) {
int olen = str.length();
return olen >= minLength && olen <= cmd.length()
&& cmd.regionMatches(true, 0, str, 0, olen);
}
private String cmd;
private int minLength;
}
private static Integer parseInteger(String word) {
try {
return Integer.valueOf(word);
} catch (NumberFormatException ex) {
return null;
}
}
private static class CommandList {
private CommandList(String table) {
Scanner scanner = new Scanner(table);
List<String> words = new ArrayList<>();
while (scanner.hasNext()) {
String word = scanner.next();
words.add(word.toUpperCase());
}
for (int i = 0, n = words.size(); i < n; ++i) {
String word = words.get(i);
int len = word.length();
if (i + 1 < n) {
Integer number = parseInteger(words.get(i + 1));
if (number != null) {
len = number.intValue();
++i;
}
}
commands.add(new Command(word, len));
}
}
private Command findCommand(String word) {
for (Command command : commands) {
if (command.match(word))
return command;
}
return null;
}
private List<Command> commands = new ArrayList<>();
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | from __future__ import division
import math
def hist(source):
hist = {}; l = 0;
for e in source:
l += 1
if e not in hist:
hist[e] = 0
hist[e] += 1
return (l,hist)
def entropy(hist,l):
elist = []
for v in hist.values():
c = v / l
elist.append(-c * math.log(c ,2))
return sum(elist)
def printHist(h):
flip = lambda (k,v) : (v,k)
h = sorted(h.iteritems(), key = flip)
print 'Sym\thi\tfi\tInf'
for (k,v) in h:
print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2))
source = "1223334444"
(l,h) = hist(source);
print '.[Results].'
print 'Length',l
print 'Entropy:', entropy(h, l)
printHist(h)
| import java.lang.Math;
import java.util.Map;
import java.util.HashMap;
public class REntropy {
@SuppressWarnings("boxing")
public static double getShannonEntropy(String s) {
int n = 0;
Map<Character, Integer> occ = new HashMap<>();
for (int c_ = 0; c_ < s.length(); ++c_) {
char cx = s.charAt(c_);
if (occ.containsKey(cx)) {
occ.put(cx, occ.get(cx) + 1);
} else {
occ.put(cx, 1);
}
++n;
}
double e = 0.0;
for (Map.Entry<Character, Integer> entry : occ.entrySet()) {
char cx = entry.getKey();
double p = (double) entry.getValue() / n;
e += p * log2(p);
}
return -e;
}
private static double log2(double a) {
return Math.log(a) / Math.log(2);
}
public static void main(String[] args) {
String[] sstr = {
"1223334444",
"1223334444555555555",
"122333",
"1227774444",
"aaBBcccDDDD",
"1234567890abcdefghijklmnopqrstuvwxyz",
"Rosetta Code",
};
for (String ss : sstr) {
double entropy = REntropy.getShannonEntropy(ss);
System.out.printf("Shannon entropy of %40s: %.12f%n", "\"" + ss + "\"", entropy);
}
return;
}
}
|
Write the same code in Java as shown below in Python. | def token_with_escape(a, escape = '^', separator = '|'):
result = []
token = ''
state = 0
for c in a:
if state == 0:
if c == escape:
state = 1
elif c == separator:
result.append(token)
token = ''
else:
token += c
elif state == 1:
token += c
state = 0
result.append(token)
return result
| import java.util.*;
public class TokenizeStringWithEscaping {
public static void main(String[] args) {
String sample = "one^|uno||three^^^^|four^^^|^cuatro|";
char separator = '|';
char escape = '^';
System.out.println(sample);
try {
System.out.println(tokenizeString(sample, separator, escape));
} catch (Exception e) {
System.out.println(e);
}
}
public static List<String> tokenizeString(String s, char sep, char escape)
throws Exception {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean inEscape = false;
for (char c : s.toCharArray()) {
if (inEscape) {
inEscape = false;
} else if (c == escape) {
inEscape = true;
continue;
} else if (c == sep) {
tokens.add(sb.toString());
sb.setLength(0);
continue;
}
sb.append(c);
}
if (inEscape)
throw new Exception("Invalid terminal escape");
tokens.add(sb.toString());
return tokens;
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | print "Hello world!"
| module HelloWorld
{
void run()
{
@Inject Console console;
console.print("Hello World!");
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | LIMIT = 1_000_035
def primes2(limit=LIMIT):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p + 1)
return [2] + [i + i + 3 for i, v in enumerate(buf) if v]
primes = primes2(LIMIT +6)
primeset = set(primes)
primearray = [n in primeset for n in range(LIMIT)]
s = [[] for x in range(4)]
unsexy = []
for p in primes:
if p > LIMIT:
break
if p + 6 in primeset and p + 6 < LIMIT:
s[0].append((p, p+6))
elif p + 6 in primeset:
break
else:
if p - 6 not in primeset:
unsexy.append(p)
continue
if p + 12 in primeset and p + 12 < LIMIT:
s[1].append((p, p+6, p+12))
else:
continue
if p + 18 in primeset and p + 18 < LIMIT:
s[2].append((p, p+6, p+12, p+18))
else:
continue
if p + 24 in primeset and p + 24 < LIMIT:
s[3].append((p, p+6, p+12, p+18, p+24))
print('"SEXY" PRIME GROUPINGS:')
for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):
print(f' {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq
printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length
Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn ""
let ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')
for sx in sexy[-5:]:
print(' ',sx)
print(f'\nThere are {len(unsexy)} unsexy primes ending with ...')
for usx in unsexy[-10:]:
print(' ',usx)
| import java.util.ArrayList;
import java.util.List;
public class SexyPrimes {
public static void main(String[] args) {
sieve();
int pairs = 0;
List<String> pairList = new ArrayList<>();
int triples = 0;
List<String> tripleList = new ArrayList<>();
int quadruplets = 0;
List<String> quadrupletList = new ArrayList<>();
int unsexyCount = 1;
List<String> unsexyList = new ArrayList<>();
for ( int i = 3 ; i < MAX ; i++ ) {
if ( i-6 >= 3 && primes[i-6] && primes[i] ) {
pairs++;
pairList.add((i-6) + " " + i);
if ( pairList.size() > 5 ) {
pairList.remove(0);
}
}
else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) {
unsexyCount++;
unsexyList.add("" + i);
if ( unsexyList.size() > 10 ) {
unsexyList.remove(0);
}
}
if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) {
triples++;
tripleList.add((i-12) + " " + (i-6) + " " + i);
if ( tripleList.size() > 5 ) {
tripleList.remove(0);
}
}
if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) {
quadruplets++;
quadrupletList.add((i-18) + " " + (i-12) + " " + (i-6) + " " + i);
if ( quadrupletList.size() > 5 ) {
quadrupletList.remove(0);
}
}
}
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, pairs);
System.out.printf("The last 5 sexy pairs:%n %s%n%n", pairList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, triples);
System.out.printf("The last 5 sexy triples:%n %s%n%n", tripleList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of sexy quadruplets less than %,d = %,d%n", MAX, quadruplets);
System.out.printf("The last 5 sexy quadruplets:%n %s%n%n", quadrupletList.toString().replaceAll(", ", "], ["));
System.out.printf("Count of unsexy primes less than %,d = %,d%n", MAX, unsexyCount);
System.out.printf("The last 10 unsexy primes:%n %s%n%n", unsexyList.toString().replaceAll(", ", "], ["));
}
private static int MAX = 1_000_035;
private static boolean[] primes = new boolean[MAX];
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | >>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]
>>>
>>> difn = lambda s, n: difn(dif(s), n-1) if n else s
>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 0)
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 1)
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
>>> difn(s, 2)
[54, -40, 22, 17, 13, -73, 100, -32]
>>> from pprint import pprint
>>> pprint( [difn(s, i) for i in xrange(10)] )
[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],
[-43, 11, -29, -7, 10, 23, -50, 50, 18],
[54, -40, 22, 17, 13, -73, 100, -32],
[-94, 62, -5, -4, -86, 173, -132],
[156, -67, 1, -82, 259, -305],
[-223, 68, -83, 341, -564],
[291, -151, 424, -905],
[-442, 575, -1329],
[1017, -1904],
[-2921]]
| import java.util.Arrays;
public class FD {
public static void main(String args[]) {
double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
System.out.println(Arrays.toString(dif(a, 1)));
System.out.println(Arrays.toString(dif(a, 2)));
System.out.println(Arrays.toString(dif(a, 9)));
System.out.println(Arrays.toString(dif(a, 10)));
System.out.println(Arrays.toString(dif(a, 11)));
System.out.println(Arrays.toString(dif(a, -1)));
System.out.println(Arrays.toString(dif(a, 0)));
}
public static double[] dif(double[] a, int n) {
if (n < 0)
return null;
for (int i = 0; i < n && a.length > 0; i++) {
double[] b = new double[a.length - 1];
for (int j = 0; j < b.length; j++){
b[j] = a[j+1] - a[j];
}
a = b;
}
return a;
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | def prime(a):
return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
| public static boolean prime(long a){
if(a == 2){
return true;
}else if(a <= 1 || a % 2 == 0){
return false;
}
long max = (long)Math.sqrt(a);
for(long n= 3; n <= max; n+= 2){
if(a % n == 0){ return false; }
}
return true;
}
|
Translate the given Python code snippet into Java without altering its behavior. | def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-i+1) / i
return result
if __name__ == "__main__":
print(binomialCoeff(5, 3))
| public class Binomial {
private static long binomialInt(int n, int k) {
if (k > n - k)
k = n - k;
long binom = 1;
for (int i = 1; i <= k; i++)
binom = binom * (n + 1 - i) / i;
return binom;
}
private static Object binomialIntReliable(int n, int k) {
if (k > n - k)
k = n - k;
long binom = 1;
for (int i = 1; i <= k; i++) {
try {
binom = Math.multiplyExact(binom, n + 1 - i) / i;
} catch (ArithmeticException e) {
return "overflow";
}
}
return binom;
}
private static double binomialFloat(int n, int k) {
if (k > n - k)
k = n - k;
double binom = 1.0;
for (int i = 1; i <= k; i++)
binom = binom * (n + 1 - i) / i;
return binom;
}
private static BigInteger binomialBigInt(int n, int k) {
if (k > n - k)
k = n - k;
BigInteger binom = BigInteger.ONE;
for (int i = 1; i <= k; i++) {
binom = binom.multiply(BigInteger.valueOf(n + 1 - i));
binom = binom.divide(BigInteger.valueOf(i));
}
return binom;
}
private static void demo(int n, int k) {
List<Object> data = Arrays.asList(
n,
k,
binomialInt(n, k),
binomialIntReliable(n, k),
binomialFloat(n, k),
binomialBigInt(n, k));
System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t")));
}
public static void main(String[] args) {
demo(5, 3);
demo(1000, 300);
}
}
|
Please provide an equivalent version of this Python code in Java. | collection = [0, '1']
x = collection[0]
collection.append(2)
collection.insert(0, '-1')
y = collection[0]
collection.extend([2,'3'])
collection += [2,'3']
collection[2:6]
len(collection)
collection = (0, 1)
collection[:]
collection[-4:-1]
collection[::2]
collection="some string"
x = collection[::-1]
collection[::2] == "some string"[::2]
collection.__getitem__(slice(0,len(collection),2))
collection = {0: "zero", 1: "one"}
collection['zero'] = 2
collection = set([0, '1'])
| List arrayList = new ArrayList();
arrayList.add(new Integer(0));
arrayList.add(0);
List<Integer> myarrlist = new ArrayList<Integer>();
int sum;
for(int i = 0; i < 10; i++) {
myarrlist.add(i);
}
|
Change the following Python code into Java without altering its purpose. | for node in lst:
print node.value
| LinkedList<Type> list = new LinkedList<Type>();
for(Type i: list){
System.out.println(i);
}
|
Produce a functionally identical Java code for the snippet given in Python. |
import io
ppmfileout = io.StringIO('')
def writeppmp3(self, f):
self.writeppm(f, ppmformat='P3')
def writeppm(self, f, ppmformat='P6'):
assert ppmformat in ['P3', 'P6'], 'Format wrong'
magic = ppmformat + '\n'
comment = '
maxval = max(max(max(bit) for bit in row) for row in self.map)
assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'
if ppmformat == 'P6':
fwrite = lambda s: f.write(bytes(s, 'UTF-8'))
maxval = 255
else:
fwrite = f.write
numsize=len(str(maxval))
fwrite(magic)
fwrite(comment)
fwrite('%i %i\n%i\n' % (self.width, self.height, maxval))
for h in range(self.height-1, -1, -1):
for w in range(self.width):
r, g, b = self.get(w, h)
if ppmformat == 'P3':
fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))
else:
fwrite('%c%c%c' % (r, g, b))
if ppmformat == 'P3':
fwrite('\n')
Bitmap.writeppmp3 = writeppmp3
Bitmap.writeppm = writeppm
bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
bitmap.writeppmp3(ppmfileout)
print(ppmfileout.getvalue())
ppmfileout = open('tmp.ppm', 'wb')
bitmap.writeppm(ppmfileout)
ppmfileout.close()
| import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class PPMWriter {
public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {
file.delete();
try (var os = new FileOutputStream(file, true);
var bw = new BufferedOutputStream(os)) {
var header = String.format("P6\n%d %d\n255\n",
bitmap.getWidth(), bitmap.getHeight());
bw.write(header.getBytes(StandardCharsets.US_ASCII));
for (var y = 0; y < bitmap.getHeight(); y++) {
for (var x = 0; x < bitmap.getWidth(); x++) {
var pixel = bitmap.getPixel(x, y);
bw.write(pixel.getRed());
bw.write(pixel.getGreen());
bw.write(pixel.getBlue());
}
}
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | import os
os.remove("output.txt")
os.rmdir("docs")
os.remove("/output.txt")
os.rmdir("/docs")
| import java.io.File;
public class FileDeleteTest {
public static boolean deleteFile(String filename) {
boolean exists = new File(filename).delete();
return exists;
}
public static void test(String type, String filename) {
System.out.println("The following " + type + " called " + filename +
(deleteFile(filename) ? " was deleted." : " could not be deleted.")
);
}
public static void main(String args[]) {
test("file", "input.txt");
test("file", File.seperator + "input.txt");
test("directory", "docs");
test("directory", File.seperator + "docs" + File.seperator);
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | import os
os.remove("output.txt")
os.rmdir("docs")
os.remove("/output.txt")
os.rmdir("/docs")
| import java.io.File;
public class FileDeleteTest {
public static boolean deleteFile(String filename) {
boolean exists = new File(filename).delete();
return exists;
}
public static void test(String type, String filename) {
System.out.println("The following " + type + " called " + filename +
(deleteFile(filename) ? " was deleted." : " could not be deleted.")
);
}
public static void main(String args[]) {
test("file", "input.txt");
test("file", File.seperator + "input.txt");
test("directory", "docs");
test("directory", File.seperator + "docs" + File.seperator);
}
}
|
Change the following Python code into Java without altering its purpose. | import datetime, calendar
DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
def ddate(year, month, day):
today = datetime.date(year, month, day)
is_leap_year = calendar.isleap(year)
if is_leap_year and month == 2 and day == 29:
return "St. Tib's Day, YOLD " + (year + 1166)
day_of_year = today.timetuple().tm_yday - 1
if is_leap_year and day_of_year >= 60:
day_of_year -= 1
season, dday = divmod(day_of_year, 73)
return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
| import java.util.Calendar;
import java.util.GregorianCalendar;
public class DiscordianDate {
final static String[] seasons = {"Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"};
final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"};
final static String[] apostle = {"Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"};
final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"};
public static String discordianDate(final GregorianCalendar date) {
int y = date.get(Calendar.YEAR);
int yold = y + 1166;
int dayOfYear = date.get(Calendar.DAY_OF_YEAR);
if (date.isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold;
else if (dayOfYear > 60)
dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
if (seasonDay == 5)
return apostle[dayOfYear / 73] + ", in the YOLD " + yold;
if (seasonDay == 50)
return holiday[dayOfYear / 73] + ", in the YOLD " + yold;
String season = seasons[dayOfYear / 73];
String dayOfWeek = weekday[dayOfYear % 5];
return String.format("%s, day %s of %s in the YOLD %s",
dayOfWeek, seasonDay, season, yold);
}
public static void main(String[] args) {
System.out.println(discordianDate(new GregorianCalendar()));
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176");
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178");
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178");
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178");
test(2010, 0, 5, "Mungday, in the YOLD 3176");
test(2011, 4, 3, "Discoflux, in the YOLD 3177");
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181");
}
private static void test(int y, int m, int d, final String result) {
assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import datetime, calendar
DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
def ddate(year, month, day):
today = datetime.date(year, month, day)
is_leap_year = calendar.isleap(year)
if is_leap_year and month == 2 and day == 29:
return "St. Tib's Day, YOLD " + (year + 1166)
day_of_year = today.timetuple().tm_yday - 1
if is_leap_year and day_of_year >= 60:
day_of_year -= 1
season, dday = divmod(day_of_year, 73)
return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
| import java.util.Calendar;
import java.util.GregorianCalendar;
public class DiscordianDate {
final static String[] seasons = {"Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"};
final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"};
final static String[] apostle = {"Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"};
final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"};
public static String discordianDate(final GregorianCalendar date) {
int y = date.get(Calendar.YEAR);
int yold = y + 1166;
int dayOfYear = date.get(Calendar.DAY_OF_YEAR);
if (date.isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold;
else if (dayOfYear > 60)
dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
if (seasonDay == 5)
return apostle[dayOfYear / 73] + ", in the YOLD " + yold;
if (seasonDay == 50)
return holiday[dayOfYear / 73] + ", in the YOLD " + yold;
String season = seasons[dayOfYear / 73];
String dayOfWeek = weekday[dayOfYear % 5];
return String.format("%s, day %s of %s in the YOLD %s",
dayOfWeek, seasonDay, season, yold);
}
public static void main(String[] args) {
System.out.println(discordianDate(new GregorianCalendar()));
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176");
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178");
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178");
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178");
test(2010, 0, 5, "Mungday, in the YOLD 3176");
test(2011, 4, 3, "Discoflux, in the YOLD 3177");
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181");
}
private static void test(int y, int m, int d, final String result) {
assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. |
from random import randrange
from copy import deepcopy
from string import ascii_lowercase
try:
input = raw_input
except:
pass
N = 3
board = [[0]* N for i in range(N)]
def setbits(board, count=1):
for i in range(count):
board[randrange(N)][randrange(N)] ^= 1
def shuffle(board, count=1):
for i in range(count):
if randrange(0, 2):
fliprow(randrange(N))
else:
flipcol(randrange(N))
def pr(board, comment=''):
print(str(comment))
print(' ' + ' '.join(ascii_lowercase[i] for i in range(N)))
print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line])
for j, line in enumerate(board, 1)))
def init(board):
setbits(board, count=randrange(N)+1)
target = deepcopy(board)
while board == target:
shuffle(board, count=2 * N)
prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0],
ascii_lowercase[N-1])
return target, prompt
def fliprow(i):
board[i-1][:] = [x ^ 1 for x in board[i-1] ]
def flipcol(i):
for row in board:
row[i] ^= 1
if __name__ == '__main__':
print(__doc__ % (N, N))
target, prompt = init(board)
pr(target, 'Target configuration is:')
print('')
turns = 0
while board != target:
turns += 1
pr(board, '%i:' % turns)
ans = input(prompt).strip()
if (len(ans) == 1
and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
flipcol(ascii_lowercase.index(ans))
elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
fliprow(int(ans))
elif ans == 'T':
pr(target, 'Target configuration is:')
turns -= 1
elif ans == 'X':
break
else:
print(" I don't understand %r... Try again. "
"(X to exit or T to show target)\n" % ans[:9])
turns -= 1
else:
print('\nWell done!\nBye.')
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class FlippingBitsGame extends JPanel {
final int maxLevel = 7;
final int minLevel = 3;
private Random rand = new Random();
private int[][] grid, target;
private Rectangle box;
private int n = maxLevel;
private boolean solved = true;
FlippingBitsGame() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
setFont(new Font("SansSerif", Font.PLAIN, 18));
box = new Rectangle(120, 90, 400, 400);
startNewGame();
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (solved) {
startNewGame();
} else {
int x = e.getX();
int y = e.getY();
if (box.contains(x, y))
return;
if (x > box.x && x < box.x + box.width) {
flipCol((x - box.x) / (box.width / n));
} else if (y > box.y && y < box.y + box.height)
flipRow((y - box.y) / (box.height / n));
if (solved(grid, target))
solved = true;
printGrid(solved ? "Solved!" : "The board", grid);
}
repaint();
}
});
}
void startNewGame() {
if (solved) {
n = (n == maxLevel) ? minLevel : n + 1;
grid = new int[n][n];
target = new int[n][n];
do {
shuffle();
for (int i = 0; i < n; i++)
target[i] = Arrays.copyOf(grid[i], n);
shuffle();
} while (solved(grid, target));
solved = false;
printGrid("The target", target);
printGrid("The board", grid);
}
}
void printGrid(String msg, int[][] g) {
System.out.println(msg);
for (int[] row : g)
System.out.println(Arrays.toString(row));
System.out.println();
}
boolean solved(int[][] a, int[][] b) {
for (int i = 0; i < n; i++)
if (!Arrays.equals(a[i], b[i]))
return false;
return true;
}
void shuffle() {
for (int i = 0; i < n * n; i++) {
if (rand.nextBoolean())
flipRow(rand.nextInt(n));
else
flipCol(rand.nextInt(n));
}
}
void flipRow(int r) {
for (int c = 0; c < n; c++) {
grid[r][c] ^= 1;
}
}
void flipCol(int c) {
for (int[] row : grid) {
row[c] ^= 1;
}
}
void drawGrid(Graphics2D g) {
g.setColor(getForeground());
if (solved)
g.drawString("Solved! Click here to play again.", 180, 600);
else
g.drawString("Click next to a row or a column to flip.", 170, 600);
int size = box.width / n;
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) {
g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(getBackground());
g.drawRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Flipping Bits Game");
f.setResizable(false);
f.add(new FlippingBitsGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Translate the given Python code snippet into Java without altering its behavior. |
from random import randrange
from copy import deepcopy
from string import ascii_lowercase
try:
input = raw_input
except:
pass
N = 3
board = [[0]* N for i in range(N)]
def setbits(board, count=1):
for i in range(count):
board[randrange(N)][randrange(N)] ^= 1
def shuffle(board, count=1):
for i in range(count):
if randrange(0, 2):
fliprow(randrange(N))
else:
flipcol(randrange(N))
def pr(board, comment=''):
print(str(comment))
print(' ' + ' '.join(ascii_lowercase[i] for i in range(N)))
print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line])
for j, line in enumerate(board, 1)))
def init(board):
setbits(board, count=randrange(N)+1)
target = deepcopy(board)
while board == target:
shuffle(board, count=2 * N)
prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0],
ascii_lowercase[N-1])
return target, prompt
def fliprow(i):
board[i-1][:] = [x ^ 1 for x in board[i-1] ]
def flipcol(i):
for row in board:
row[i] ^= 1
if __name__ == '__main__':
print(__doc__ % (N, N))
target, prompt = init(board)
pr(target, 'Target configuration is:')
print('')
turns = 0
while board != target:
turns += 1
pr(board, '%i:' % turns)
ans = input(prompt).strip()
if (len(ans) == 1
and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
flipcol(ascii_lowercase.index(ans))
elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
fliprow(int(ans))
elif ans == 'T':
pr(target, 'Target configuration is:')
turns -= 1
elif ans == 'X':
break
else:
print(" I don't understand %r... Try again. "
"(X to exit or T to show target)\n" % ans[:9])
turns -= 1
else:
print('\nWell done!\nBye.')
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class FlippingBitsGame extends JPanel {
final int maxLevel = 7;
final int minLevel = 3;
private Random rand = new Random();
private int[][] grid, target;
private Rectangle box;
private int n = maxLevel;
private boolean solved = true;
FlippingBitsGame() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
setFont(new Font("SansSerif", Font.PLAIN, 18));
box = new Rectangle(120, 90, 400, 400);
startNewGame();
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (solved) {
startNewGame();
} else {
int x = e.getX();
int y = e.getY();
if (box.contains(x, y))
return;
if (x > box.x && x < box.x + box.width) {
flipCol((x - box.x) / (box.width / n));
} else if (y > box.y && y < box.y + box.height)
flipRow((y - box.y) / (box.height / n));
if (solved(grid, target))
solved = true;
printGrid(solved ? "Solved!" : "The board", grid);
}
repaint();
}
});
}
void startNewGame() {
if (solved) {
n = (n == maxLevel) ? minLevel : n + 1;
grid = new int[n][n];
target = new int[n][n];
do {
shuffle();
for (int i = 0; i < n; i++)
target[i] = Arrays.copyOf(grid[i], n);
shuffle();
} while (solved(grid, target));
solved = false;
printGrid("The target", target);
printGrid("The board", grid);
}
}
void printGrid(String msg, int[][] g) {
System.out.println(msg);
for (int[] row : g)
System.out.println(Arrays.toString(row));
System.out.println();
}
boolean solved(int[][] a, int[][] b) {
for (int i = 0; i < n; i++)
if (!Arrays.equals(a[i], b[i]))
return false;
return true;
}
void shuffle() {
for (int i = 0; i < n * n; i++) {
if (rand.nextBoolean())
flipRow(rand.nextInt(n));
else
flipCol(rand.nextInt(n));
}
}
void flipRow(int r) {
for (int c = 0; c < n; c++) {
grid[r][c] ^= 1;
}
}
void flipCol(int c) {
for (int[] row : grid) {
row[c] ^= 1;
}
}
void drawGrid(Graphics2D g) {
g.setColor(getForeground());
if (solved)
g.drawString("Solved! Click here to play again.", 180, 600);
else
g.drawString("Click next to a row or a column to flip.", 170, 600);
int size = box.width / n;
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) {
g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(getBackground());
g.drawRect(box.x + c * size, box.y + r * size, size, size);
g.setColor(target[r][c] == 1 ? Color.blue : Color.orange);
g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Flipping Bits Game");
f.setResizable(false);
f.add(new FlippingBitsGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(n)
norm = str(x.normalize())
almostinteger = (' Nearly integer'
if 'E' not in norm and ('.0' in norm or '.9' in norm)
else ' NOT nearly integer!')
print('n:%2i h:%s%s' % (n, norm, almostinteger))
| import java.math.*;
public class Hickerson {
final static String LN2 = "0.693147180559945309417232121458";
public static void main(String[] args) {
for (int n = 1; n <= 17; n++)
System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
}
static boolean almostInteger(int n) {
BigDecimal a = new BigDecimal(LN2);
a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));
long f = n;
while (--n > 1)
f *= n;
BigDecimal b = new BigDecimal(f);
b = b.divide(a, MathContext.DECIMAL128);
BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);
return c.toString().matches("0|9");
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(n)
norm = str(x.normalize())
almostinteger = (' Nearly integer'
if 'E' not in norm and ('.0' in norm or '.9' in norm)
else ' NOT nearly integer!')
print('n:%2i h:%s%s' % (n, norm, almostinteger))
| import java.math.*;
public class Hickerson {
final static String LN2 = "0.693147180559945309417232121458";
public static void main(String[] args) {
for (int n = 1; n <= 17; n++)
System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n));
}
static boolean almostInteger(int n) {
BigDecimal a = new BigDecimal(LN2);
a = a.pow(n + 1).multiply(BigDecimal.valueOf(2));
long f = n;
while (--n > 1)
f *= n;
BigDecimal b = new BigDecimal(f);
b = b.divide(a, MathContext.DECIMAL128);
BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN);
return c.toString().matches("0|9");
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | from __future__ import division
from math import factorial
from random import randrange
MAX_N = 20
TIMES = 1000000
def analytical(n):
return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))
def test(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
if __name__ == '__main__':
print(" n\tavg\texp.\tdiff\n-------------------------------")
for n in range(1, MAX_N+1):
avg = test(n, TIMES)
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
| import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from __future__ import division
from math import factorial
from random import randrange
MAX_N = 20
TIMES = 1000000
def analytical(n):
return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))
def test(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
if __name__ == '__main__':
print(" n\tavg\texp.\tdiff\n-------------------------------")
for n in range(1, MAX_N+1):
avg = test(n, TIMES)
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
| import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
}
|
Write a version of this Python function in Java with identical behavior. | >>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'
| String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little);
System.out.println(replaced);
System.out.printf("Mary had a %s lamb.", little);
String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);
|
Write a version of this Python function in Java with identical behavior. | from functools import total_ordering
from bisect import bisect_left
from heapq import merge
@total_ordering
class Pile(list):
def __lt__(self, other): return self[-1] < other[-1]
def __eq__(self, other): return self[-1] == other[-1]
def patience_sort(n):
piles = []
for x in n:
new_pile = Pile([x])
i = bisect_left(piles, new_pile)
if i != len(piles):
piles[i].append(x)
else:
piles.append(new_pile)
n[:] = merge(*[reversed(pile) for pile in piles])
if __name__ == "__main__":
a = [4, 65, 2, -31, 0, 99, 83, 782, 1]
patience_sort(a)
print a
| import java.util.*;
public class PatienceSort {
public static <E extends Comparable<? super E>> void sort (E[] n) {
List<Pile<E>> piles = new ArrayList<Pile<E>>();
for (E x : n) {
Pile<E> newPile = new Pile<E>();
newPile.push(x);
int i = Collections.binarySearch(piles, newPile);
if (i < 0) i = ~i;
if (i != piles.size())
piles.get(i).push(x);
else
piles.add(newPile);
}
PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);
for (int c = 0; c < n.length; c++) {
Pile<E> smallPile = heap.poll();
n[c] = smallPile.pop();
if (!smallPile.isEmpty())
heap.offer(smallPile);
}
assert(heap.isEmpty());
}
private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {
public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }
}
public static void main(String[] args) {
Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};
sort(a);
System.out.println(Arrays.toString(a));
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | import random
from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASECOUNT:")
tot = 0
for base, count in basecount(dna):
print(f" {base:>3}: {count}")
tot += count
base, count = 'TOT', tot
print(f" {base:>3}= {count}")
def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ):
mutation = []
k2txt = dict(I='Insert', D='Delete', S='Substitute')
for _ in range(count):
kind = random.choice(kinds)
index = random.randint(0, len(dna))
if kind == 'I':
dna = dna[:index] + random.choice(choice) + dna[index:]
elif kind == 'D' and dna:
dna = dna[:index] + dna[index+1:]
elif kind == 'S' and dna:
dna = dna[:index] + random.choice(choice) + dna[index+1:]
mutation.append((k2txt[kind], index))
return dna, mutation
if __name__ == '__main__':
length = 250
print("SEQUENCE:")
sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))
seq_pp(sequence)
print("\n\nMUTATIONS:")
mseq, m = seq_mutate(sequence, 10)
for kind, index in m:
print(f" {kind:>10} @{index}")
print()
seq_pp(mseq)
| import java.util.Arrays;
import java.util.Random;
public class SequenceMutation {
public static void main(String[] args) {
SequenceMutation sm = new SequenceMutation();
sm.setWeight(OP_CHANGE, 3);
String sequence = sm.generateSequence(250);
System.out.println("Initial sequence:");
printSequence(sequence);
int count = 10;
for (int i = 0; i < count; ++i)
sequence = sm.mutateSequence(sequence);
System.out.println("After " + count + " mutations:");
printSequence(sequence);
}
public SequenceMutation() {
totalWeight_ = OP_COUNT;
Arrays.fill(operationWeight_, 1);
}
public String generateSequence(int length) {
char[] ch = new char[length];
for (int i = 0; i < length; ++i)
ch[i] = getRandomBase();
return new String(ch);
}
public void setWeight(int operation, int weight) {
totalWeight_ -= operationWeight_[operation];
operationWeight_[operation] = weight;
totalWeight_ += weight;
}
public String mutateSequence(String sequence) {
char[] ch = sequence.toCharArray();
int pos = random_.nextInt(ch.length);
int operation = getRandomOperation();
if (operation == OP_CHANGE) {
char b = getRandomBase();
System.out.println("Change base at position " + pos + " from "
+ ch[pos] + " to " + b);
ch[pos] = b;
} else if (operation == OP_ERASE) {
System.out.println("Erase base " + ch[pos] + " at position " + pos);
char[] newCh = new char[ch.length - 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);
ch = newCh;
} else if (operation == OP_INSERT) {
char b = getRandomBase();
System.out.println("Insert base " + b + " at position " + pos);
char[] newCh = new char[ch.length + 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);
newCh[pos] = b;
ch = newCh;
}
return new String(ch);
}
public static void printSequence(String sequence) {
int[] count = new int[BASES.length];
for (int i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
System.out.println();
System.out.printf("%3d: ", i);
}
char ch = sequence.charAt(i);
System.out.print(ch);
for (int j = 0; j < BASES.length; ++j) {
if (BASES[j] == ch) {
++count[j];
break;
}
}
}
System.out.println();
System.out.println("Base counts:");
int total = 0;
for (int j = 0; j < BASES.length; ++j) {
total += count[j];
System.out.print(BASES[j] + ": " + count[j] + ", ");
}
System.out.println("Total: " + total);
}
private char getRandomBase() {
return BASES[random_.nextInt(BASES.length)];
}
private int getRandomOperation() {
int n = random_.nextInt(totalWeight_), op = 0;
for (int weight = 0; op < OP_COUNT; ++op) {
weight += operationWeight_[op];
if (n < weight)
break;
}
return op;
}
private final Random random_ = new Random();
private int[] operationWeight_ = new int[OP_COUNT];
private int totalWeight_ = 0;
private static final int OP_CHANGE = 0;
private static final int OP_ERASE = 1;
private static final int OP_INSERT = 2;
private static final int OP_COUNT = 3;
private static final char[] BASES = {'A', 'C', 'G', 'T'};
}
|
Change the following Python code into Java without altering its purpose. | import random
from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASECOUNT:")
tot = 0
for base, count in basecount(dna):
print(f" {base:>3}: {count}")
tot += count
base, count = 'TOT', tot
print(f" {base:>3}= {count}")
def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ):
mutation = []
k2txt = dict(I='Insert', D='Delete', S='Substitute')
for _ in range(count):
kind = random.choice(kinds)
index = random.randint(0, len(dna))
if kind == 'I':
dna = dna[:index] + random.choice(choice) + dna[index:]
elif kind == 'D' and dna:
dna = dna[:index] + dna[index+1:]
elif kind == 'S' and dna:
dna = dna[:index] + random.choice(choice) + dna[index+1:]
mutation.append((k2txt[kind], index))
return dna, mutation
if __name__ == '__main__':
length = 250
print("SEQUENCE:")
sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))
seq_pp(sequence)
print("\n\nMUTATIONS:")
mseq, m = seq_mutate(sequence, 10)
for kind, index in m:
print(f" {kind:>10} @{index}")
print()
seq_pp(mseq)
| import java.util.Arrays;
import java.util.Random;
public class SequenceMutation {
public static void main(String[] args) {
SequenceMutation sm = new SequenceMutation();
sm.setWeight(OP_CHANGE, 3);
String sequence = sm.generateSequence(250);
System.out.println("Initial sequence:");
printSequence(sequence);
int count = 10;
for (int i = 0; i < count; ++i)
sequence = sm.mutateSequence(sequence);
System.out.println("After " + count + " mutations:");
printSequence(sequence);
}
public SequenceMutation() {
totalWeight_ = OP_COUNT;
Arrays.fill(operationWeight_, 1);
}
public String generateSequence(int length) {
char[] ch = new char[length];
for (int i = 0; i < length; ++i)
ch[i] = getRandomBase();
return new String(ch);
}
public void setWeight(int operation, int weight) {
totalWeight_ -= operationWeight_[operation];
operationWeight_[operation] = weight;
totalWeight_ += weight;
}
public String mutateSequence(String sequence) {
char[] ch = sequence.toCharArray();
int pos = random_.nextInt(ch.length);
int operation = getRandomOperation();
if (operation == OP_CHANGE) {
char b = getRandomBase();
System.out.println("Change base at position " + pos + " from "
+ ch[pos] + " to " + b);
ch[pos] = b;
} else if (operation == OP_ERASE) {
System.out.println("Erase base " + ch[pos] + " at position " + pos);
char[] newCh = new char[ch.length - 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);
ch = newCh;
} else if (operation == OP_INSERT) {
char b = getRandomBase();
System.out.println("Insert base " + b + " at position " + pos);
char[] newCh = new char[ch.length + 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);
newCh[pos] = b;
ch = newCh;
}
return new String(ch);
}
public static void printSequence(String sequence) {
int[] count = new int[BASES.length];
for (int i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
System.out.println();
System.out.printf("%3d: ", i);
}
char ch = sequence.charAt(i);
System.out.print(ch);
for (int j = 0; j < BASES.length; ++j) {
if (BASES[j] == ch) {
++count[j];
break;
}
}
}
System.out.println();
System.out.println("Base counts:");
int total = 0;
for (int j = 0; j < BASES.length; ++j) {
total += count[j];
System.out.print(BASES[j] + ": " + count[j] + ", ");
}
System.out.println("Total: " + total);
}
private char getRandomBase() {
return BASES[random_.nextInt(BASES.length)];
}
private int getRandomOperation() {
int n = random_.nextInt(totalWeight_), op = 0;
for (int weight = 0; op < OP_COUNT; ++op) {
weight += operationWeight_[op];
if (n < weight)
break;
}
return op;
}
private final Random random_ = new Random();
private int[] operationWeight_ = new int[OP_COUNT];
private int totalWeight_ = 0;
private static final int OP_CHANGE = 0;
private static final int OP_ERASE = 1;
private static final int OP_INSERT = 2;
private static final int OP_COUNT = 3;
private static final char[] BASES = {'A', 'C', 'G', 'T'};
}
|
Port the following code from Python to Java with equivalent syntax and logic. | def tau(n):
assert(isinstance(n, int) and 0 < n)
ans, i, j = 0, 1, 1
while i*i <= n:
if 0 == n%i:
ans += 1
j = n//i
if j != i:
ans += 1
i += 1
return ans
def is_tau_number(n):
assert(isinstance(n, int))
if n <= 0:
return False
return 0 == n%tau(n)
if __name__ == "__main__":
n = 1
ans = []
while len(ans) < 100:
if is_tau_number(n):
ans.append(n)
n += 1
print(ans)
| public class Tau {
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;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("The first %d tau numbers are:%n", limit);
long count = 0;
for (long n = 1; count < limit; ++n) {
if (n % divisorCount(n) == 0) {
System.out.printf("%6d", n);
++count;
if (count % 10 == 0) {
System.out.println();
}
}
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations
def prod(lst):
return reduce(mul, lst, 1)
def perm(a):
n = len(a)
r = range(n)
s = permutations(r)
return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)
def det(a):
n = len(a)
r = range(n)
s = spermutations(n)
return fsum(sign * prod(a[i][sigma[i]] for i in r)
for sigma, sign in s)
if __name__ == '__main__':
from pprint import pprint as pp
for a in (
[
[1, 2],
[3, 4]],
[
[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10],
[10, 11, 12, 13]],
[
[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]],
):
print('')
pp(a)
print('Perm: %s Det: %s' % (perm(a), det(a)))
| import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j<y){
result[i][j] = a[i+1][j];
}else if(i<x && j>=y){
result[i][j] = a[i][j+1];
}else{
result[i][j] = a[i+1][j+1];
}
}
return result;
}
public static double det(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
int sign = 1;
double sum = 0;
for(int i=0;i<a.length;i++){
sum += sign * a[0][i] * det(minor(a,0,i));
sign *= -1;
}
return sum;
}
}
public static double perm(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
double sum = 0;
for(int i=0;i<a.length;i++){
sum += a[0][i] * perm(minor(a,0,i));
}
return sum;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
double[][] a = new double[size][size];
for(int i=0;i<size;i++) for(int j=0;j<size;j++){
a[i][j] = sc.nextDouble();
}
sc.close();
System.out.println("Determinant: "+det(a));
System.out.println("Permanent: "+perm(a));
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations
def prod(lst):
return reduce(mul, lst, 1)
def perm(a):
n = len(a)
r = range(n)
s = permutations(r)
return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)
def det(a):
n = len(a)
r = range(n)
s = spermutations(n)
return fsum(sign * prod(a[i][sigma[i]] for i in r)
for sigma, sign in s)
if __name__ == '__main__':
from pprint import pprint as pp
for a in (
[
[1, 2],
[3, 4]],
[
[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10],
[10, 11, 12, 13]],
[
[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]],
):
print('')
pp(a)
print('Perm: %s Det: %s' % (perm(a), det(a)))
| import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j<y){
result[i][j] = a[i+1][j];
}else if(i<x && j>=y){
result[i][j] = a[i][j+1];
}else{
result[i][j] = a[i+1][j+1];
}
}
return result;
}
public static double det(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
int sign = 1;
double sum = 0;
for(int i=0;i<a.length;i++){
sum += sign * a[0][i] * det(minor(a,0,i));
sign *= -1;
}
return sum;
}
}
public static double perm(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
double sum = 0;
for(int i=0;i<a.length;i++){
sum += a[0][i] * perm(minor(a,0,i));
}
return sum;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
double[][] a = new double[size][size];
for(int i=0;i<size;i++) for(int j=0;j<size;j++){
a[i][j] = sc.nextDouble();
}
sc.close();
System.out.println("Determinant: "+det(a));
System.out.println("Permanent: "+perm(a));
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | from itertools import islice
def posd():
"diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..."
count, odd = 1, 3
while True:
yield count
yield odd
count, odd = count + 1, odd + 2
def pos_gen():
"position numbers. 1 3 2 5 7 4 9 ..."
val = 1
diff = posd()
while True:
yield val
val += next(diff)
def plus_minus():
"yield (list_offset, sign) or zero for Partition calc"
n, sign = 0, [1, 1]
p_gen = pos_gen()
out_on = next(p_gen)
while True:
n += 1
if n == out_on:
next_sign = sign.pop(0)
if not sign:
sign = [-next_sign] * 2
yield -n, next_sign
out_on = next(p_gen)
else:
yield 0
def part(n):
"Partition numbers"
p = [1]
p_m = plus_minus()
mods = []
for _ in range(n):
next_plus_minus = next(p_m)
if next_plus_minus:
mods.append(next_plus_minus)
p.append(sum(p[offset] * sign for offset, sign in mods))
return p[-1]
print("(Intermediaries):")
print(" posd:", list(islice(posd(), 10)))
print(" pos_gen:", list(islice(pos_gen(), 10)))
print(" plus_minus:", list(islice(plus_minus(), 15)))
print("\nPartitions:", [part(x) for x in range(15)])
| import java.math.BigInteger;
public class PartitionFunction {
public static void main(String[] args) {
long start = System.currentTimeMillis();
BigInteger result = partitions(6666);
long end = System.currentTimeMillis();
System.out.println("P(6666) = " + result);
System.out.printf("elapsed time: %d milliseconds\n", end - start);
}
private static BigInteger partitions(int n) {
BigInteger[] p = new BigInteger[n + 1];
p[0] = BigInteger.ONE;
for (int i = 1; i <= n; ++i) {
p[i] = BigInteger.ZERO;
for (int k = 1; ; ++k) {
int j = (k * (3 * k - 1))/2;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
j += k;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
}
}
return p[n];
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | from collections import namedtuple
from pprint import pprint as pp
import sys
Pt = namedtuple('Pt', 'x, y')
Edge = namedtuple('Edge', 'a, b')
Poly = namedtuple('Poly', 'name, edges')
_eps = 0.00001
_huge = sys.float_info.max
_tiny = sys.float_info.min
def rayintersectseg(p, edge):
a,b = edge
if a.y > b.y:
a,b = b,a
if p.y == a.y or p.y == b.y:
p = Pt(p.x, p.y + _eps)
intersect = False
if (p.y > b.y or p.y < a.y) or (
p.x > max(a.x, b.x)):
return False
if p.x < min(a.x, b.x):
intersect = True
else:
if abs(a.x - b.x) > _tiny:
m_red = (b.y - a.y) / float(b.x - a.x)
else:
m_red = _huge
if abs(a.x - p.x) > _tiny:
m_blue = (p.y - a.y) / float(p.x - a.x)
else:
m_blue = _huge
intersect = m_blue >= m_red
return intersect
def _odd(x): return x%2 == 1
def ispointinside(p, poly):
ln = len(poly)
return _odd(sum(rayintersectseg(p, edge)
for edge in poly.edges ))
def polypp(poly):
print ("\n Polygon(name='%s', edges=(" % poly.name)
print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))')
if __name__ == '__main__':
polys = [
Poly(name='square', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))
)),
Poly(name='square_hole', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),
Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),
Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),
Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),
Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))
)),
Poly(name='strange', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),
Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),
Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),
Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))
)),
Poly(name='exagon', edges=(
Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),
Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),
Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),
Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),
Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),
Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))
)),
]
testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),
Pt(x=-10, y=5), Pt(x=0, y=5),
Pt(x=10, y=5), Pt(x=8, y=5),
Pt(x=10, y=10))
print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS")
for poly in polys:
polypp(poly)
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[:3]))
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[3:6]))
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[6:]))
| import static java.lang.Math.*;
public class RayCasting {
static boolean intersects(int[] A, int[] B, double[] P) {
if (A[1] > B[1])
return intersects(B, A, P);
if (P[1] == A[1] || P[1] == B[1])
P[1] += 0.0001;
if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))
return false;
if (P[0] < min(A[0], B[0]))
return true;
double red = (P[1] - A[1]) / (double) (P[0] - A[0]);
double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);
return red >= blue;
}
static boolean contains(int[][] shape, double[] pnt) {
boolean inside = false;
int len = shape.length;
for (int i = 0; i < len; i++) {
if (intersects(shape[i], shape[(i + 1) % len], pnt))
inside = !inside;
}
return inside;
}
public static void main(String[] a) {
double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},
{20, 10}, {16, 10}, {20, 20}};
for (int[][] shape : shapes) {
for (double[] pnt : testPoints)
System.out.printf("%7s ", contains(shape, pnt));
System.out.println();
}
}
final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};
final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},
{5, 5}, {15, 5}, {15, 15}, {5, 15}};
final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},
{20, 20}, {20, 0}};
final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},
{6, 20}, {0, 10}};
final static int[][][] shapes = {square, squareHole, strange, hexagon};
}
|
Produce a functionally identical Java code for the snippet given in Python. | from collections import namedtuple
from pprint import pprint as pp
import sys
Pt = namedtuple('Pt', 'x, y')
Edge = namedtuple('Edge', 'a, b')
Poly = namedtuple('Poly', 'name, edges')
_eps = 0.00001
_huge = sys.float_info.max
_tiny = sys.float_info.min
def rayintersectseg(p, edge):
a,b = edge
if a.y > b.y:
a,b = b,a
if p.y == a.y or p.y == b.y:
p = Pt(p.x, p.y + _eps)
intersect = False
if (p.y > b.y or p.y < a.y) or (
p.x > max(a.x, b.x)):
return False
if p.x < min(a.x, b.x):
intersect = True
else:
if abs(a.x - b.x) > _tiny:
m_red = (b.y - a.y) / float(b.x - a.x)
else:
m_red = _huge
if abs(a.x - p.x) > _tiny:
m_blue = (p.y - a.y) / float(p.x - a.x)
else:
m_blue = _huge
intersect = m_blue >= m_red
return intersect
def _odd(x): return x%2 == 1
def ispointinside(p, poly):
ln = len(poly)
return _odd(sum(rayintersectseg(p, edge)
for edge in poly.edges ))
def polypp(poly):
print ("\n Polygon(name='%s', edges=(" % poly.name)
print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))')
if __name__ == '__main__':
polys = [
Poly(name='square', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))
)),
Poly(name='square_hole', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),
Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),
Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),
Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),
Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))
)),
Poly(name='strange', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),
Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),
Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),
Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))
)),
Poly(name='exagon', edges=(
Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),
Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),
Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),
Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),
Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),
Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))
)),
]
testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),
Pt(x=-10, y=5), Pt(x=0, y=5),
Pt(x=10, y=5), Pt(x=8, y=5),
Pt(x=10, y=10))
print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS")
for poly in polys:
polypp(poly)
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[:3]))
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[3:6]))
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[6:]))
| import static java.lang.Math.*;
public class RayCasting {
static boolean intersects(int[] A, int[] B, double[] P) {
if (A[1] > B[1])
return intersects(B, A, P);
if (P[1] == A[1] || P[1] == B[1])
P[1] += 0.0001;
if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))
return false;
if (P[0] < min(A[0], B[0]))
return true;
double red = (P[1] - A[1]) / (double) (P[0] - A[0]);
double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);
return red >= blue;
}
static boolean contains(int[][] shape, double[] pnt) {
boolean inside = false;
int len = shape.length;
for (int i = 0; i < len; i++) {
if (intersects(shape[i], shape[(i + 1) % len], pnt))
inside = !inside;
}
return inside;
}
public static void main(String[] a) {
double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},
{20, 10}, {16, 10}, {20, 20}};
for (int[][] shape : shapes) {
for (double[] pnt : testPoints)
System.out.printf("%7s ", contains(shape, pnt));
System.out.println();
}
}
final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};
final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},
{5, 5}, {15, 5}, {15, 15}, {5, 15}};
final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},
{20, 20}, {20, 0}};
final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},
{6, 20}, {0, 10}};
final static int[][][] shapes = {square, squareHole, strange, hexagon};
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(self):
if self.is_zero():
return self.copy()
try:
L = (3 * self.x * self.x) / (2 * self.y)
except ZeroDivisionError:
return Point()
x = L * L - 2 * self.x
return Point(x, L * (self.x - x) - self.y)
def add(self, q):
if self.x == q.x and self.y == q.y:
return self.dbl()
if self.is_zero():
return q.copy()
if q.is_zero():
return self.copy()
try:
L = (q.y - self.y) / (q.x - self.x)
except ZeroDivisionError:
return Point()
x = L * L - self.x - q.x
return Point(x, L * (self.x - x) - self.y)
def mul(self, n):
p = self.copy()
r = Point()
i = 1
while i <= n:
if i&n:
r = r.add(p)
p = p.dbl()
i <<= 1
return r
def __str__(self):
return "({:.3f}, {:.3f})".format(self.x, self.y)
def show(s, p):
print(s, "Zero" if p.is_zero() else p)
def from_y(y):
n = y * y - Point.b
x = n**(1./3) if n>=0 else -((-n)**(1./3))
return Point(x, y)
a = from_y(1)
b = from_y(2)
show("a =", a)
show("b =", b)
c = a.add(b)
show("c = a + b =", c)
d = c.neg()
show("d = -c =", d)
show("c + d =", c.add(d))
show("a + b + d =", a.add(b.add(d)))
show("a * 12345 =", a.mul(12345))
| import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c = a + b = %s%n", c);
Pt d = c.neg();
System.out.printf("d = -c = %s%n", d);
System.out.printf("c + d = %s%n", c.plus(d));
System.out.printf("a + b + d = %s%n", a.plus(b).plus(d));
System.out.printf("a * 12345 = %s%n", a.mult(12345));
}
}
class Pt {
final static int bCoeff = 7;
double x, y;
Pt(double x, double y) {
this.x = x;
this.y = y;
}
static Pt zero() {
return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
}
boolean isZero() {
return this.x > 1e20 || this.x < -1e20;
}
static Pt fromY(double y) {
return new Pt(cbrt(pow(y, 2) - bCoeff), y);
}
Pt dbl() {
if (isZero())
return this;
double L = (3 * this.x * this.x) / (2 * this.y);
double x2 = pow(L, 2) - 2 * this.x;
return new Pt(x2, L * (this.x - x2) - this.y);
}
Pt neg() {
return new Pt(this.x, -this.y);
}
Pt plus(Pt q) {
if (this.x == q.x && this.y == q.y)
return dbl();
if (isZero())
return q;
if (q.isZero())
return this;
double L = (q.y - this.y) / (q.x - this.x);
double xx = pow(L, 2) - this.x - q.x;
return new Pt(xx, L * (this.x - xx) - this.y);
}
Pt mult(int n) {
Pt r = Pt.zero();
Pt p = this;
for (int i = 1; i <= n; i <<= 1) {
if ((i & n) != 0)
r = r.plus(p);
p = p.dbl();
}
return r;
}
@Override
public String toString() {
if (isZero())
return "Zero";
return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y);
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(self):
if self.is_zero():
return self.copy()
try:
L = (3 * self.x * self.x) / (2 * self.y)
except ZeroDivisionError:
return Point()
x = L * L - 2 * self.x
return Point(x, L * (self.x - x) - self.y)
def add(self, q):
if self.x == q.x and self.y == q.y:
return self.dbl()
if self.is_zero():
return q.copy()
if q.is_zero():
return self.copy()
try:
L = (q.y - self.y) / (q.x - self.x)
except ZeroDivisionError:
return Point()
x = L * L - self.x - q.x
return Point(x, L * (self.x - x) - self.y)
def mul(self, n):
p = self.copy()
r = Point()
i = 1
while i <= n:
if i&n:
r = r.add(p)
p = p.dbl()
i <<= 1
return r
def __str__(self):
return "({:.3f}, {:.3f})".format(self.x, self.y)
def show(s, p):
print(s, "Zero" if p.is_zero() else p)
def from_y(y):
n = y * y - Point.b
x = n**(1./3) if n>=0 else -((-n)**(1./3))
return Point(x, y)
a = from_y(1)
b = from_y(2)
show("a =", a)
show("b =", b)
c = a.add(b)
show("c = a + b =", c)
d = c.neg()
show("d = -c =", d)
show("c + d =", c.add(d))
show("a + b + d =", a.add(b.add(d)))
show("a * 12345 =", a.mul(12345))
| import static java.lang.Math.*;
import java.util.Locale;
public class Test {
public static void main(String[] args) {
Pt a = Pt.fromY(1);
Pt b = Pt.fromY(2);
System.out.printf("a = %s%n", a);
System.out.printf("b = %s%n", b);
Pt c = a.plus(b);
System.out.printf("c = a + b = %s%n", c);
Pt d = c.neg();
System.out.printf("d = -c = %s%n", d);
System.out.printf("c + d = %s%n", c.plus(d));
System.out.printf("a + b + d = %s%n", a.plus(b).plus(d));
System.out.printf("a * 12345 = %s%n", a.mult(12345));
}
}
class Pt {
final static int bCoeff = 7;
double x, y;
Pt(double x, double y) {
this.x = x;
this.y = y;
}
static Pt zero() {
return new Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
}
boolean isZero() {
return this.x > 1e20 || this.x < -1e20;
}
static Pt fromY(double y) {
return new Pt(cbrt(pow(y, 2) - bCoeff), y);
}
Pt dbl() {
if (isZero())
return this;
double L = (3 * this.x * this.x) / (2 * this.y);
double x2 = pow(L, 2) - 2 * this.x;
return new Pt(x2, L * (this.x - x2) - this.y);
}
Pt neg() {
return new Pt(this.x, -this.y);
}
Pt plus(Pt q) {
if (this.x == q.x && this.y == q.y)
return dbl();
if (isZero())
return q;
if (q.isZero())
return this;
double L = (q.y - this.y) / (q.x - this.x);
double xx = pow(L, 2) - this.x - q.x;
return new Pt(xx, L * (this.x - xx) - this.y);
}
Pt mult(int n) {
Pt r = Pt.zero();
Pt p = this;
for (int i = 1; i <= n; i <<= 1) {
if ((i & n) != 0)
r = r.plus(p);
p = p.dbl();
}
return r;
}
@Override
public String toString() {
if (isZero())
return "Zero";
return String.format(Locale.US, "(%.3f,%.3f)", this.x, this.y);
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | >>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2
| public class CountSubstring {
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
public static void main(String[] args){
System.out.println(countSubstring("th", "the three truths"));
System.out.println(countSubstring("abab", "ababababab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| public class PrimeDigits {
private static boolean primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
public static void main(String[] args) {
int c = 0;
for (int i = 1; i < 1_000_000; i++) {
if (primeDigitsSum13(i)) {
System.out.printf("%6d ", i);
if (c++ == 10) {
c = 0;
System.out.println();
}
}
}
System.out.println();
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| public class PrimeDigits {
private static boolean primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
public static void main(String[] args) {
int c = 0;
for (int i = 1; i < 1_000_000; i++) {
if (primeDigitsSum13(i)) {
System.out.printf("%6d ", i);
if (c++ == 10) {
c = 0;
System.out.println();
}
}
}
System.out.println();
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | fun compare(a, b):
print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}")
if a < b: print("$a is strictly less than $b")
if a <= b: print("$a is less than or equal to $b")
if a > b: print("$a is strictly greater than $b")
if a >= b: print("$a is greater than or equal to $b")
if a == b: print("$a is equal to $b")
if a != b: print("$a is not equal to $b")
if a is b: print("$a has object identity with $b")
if a is not b: print("$a has negated object identity with $b")
compare("YUP", "YUP")
compare('a', 'z')
compare("24", "123")
compare(24, 123)
compare(5.0, 5)
| public class Compare
{
public static void compare (String A, String B)
{
if (A.equals(B))
System.debug(A + ' and ' + B + ' are lexically equal.');
else
System.debug(A + ' and ' + B + ' are not lexically equal.');
if (A.equalsIgnoreCase(B))
System.debug(A + ' and ' + B + ' are case-insensitive lexically equal.');
else
System.debug(A + ' and ' + B + ' are not case-insensitive lexically equal.');
if (A.compareTo(B) < 0)
System.debug(A + ' is lexically before ' + B);
else if (A.compareTo(B) > 0)
System.debug(A + ' is lexically after ' + B);
if (A.compareTo(B) >= 0)
System.debug(A + ' is not lexically before ' + B);
if (A.compareTo(B) <= 0)
System.debug(A + ' is not lexically after ' + B);
System.debug('The lexical relationship is: ' + A.compareTo(B));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | import sys, datetime, shutil
if len(sys.argv) == 1:
try:
with open('notes.txt', 'r') as f:
shutil.copyfileobj(f, sys.stdout)
except IOError:
pass
else:
with open('notes.txt', 'a') as f:
f.write(datetime.datetime.now().isoformat() + '\n')
f.write("\t%s\n" % ' '.join(sys.argv[1:]))
| import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.close();
}
}
}
|
Change the following Python code into Java without altering its purpose. | import sys, datetime, shutil
if len(sys.argv) == 1:
try:
with open('notes.txt', 'r') as f:
shutil.copyfileobj(f, sys.stdout)
except IOError:
pass
else:
with open('notes.txt', 'a') as f:
f.write(datetime.datetime.now().isoformat() + '\n')
f.write("\t%s\n" % ' '.join(sys.argv[1:]))
| import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.close();
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. |
import math
def thieleInterpolator(x, y):
ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]
for i in range(len(ρ)-1):
ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
for i in range(2, len(ρ)):
for j in range(len(ρ)-i):
ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
ρ0 = ρ[0]
def t(xin):
a = 0
for i in range(len(ρ0)-1, 1, -1):
a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
return y[0] + (xin-x[0]) / (ρ0[1]+a)
return t
xVal = [i*.05 for i in range(32)]
tSin = [math.sin(x) for x in xVal]
tCos = [math.cos(x) for x in xVal]
tTan = [math.tan(x) for x in xVal]
iSin = thieleInterpolator(tSin, xVal)
iCos = thieleInterpolator(tCos, xVal)
iTan = thieleInterpolator(tTan, xVal)
print('{:16.14f}'.format(6*iSin(.5)))
print('{:16.14f}'.format(3*iCos(.5)))
print('{:16.14f}'.format(4*iTan(1)))
| import static java.lang.Math.*;
public class Test {
final static int N = 32;
final static int N2 = (N * (N - 1) / 2);
final static double STEP = 0.05;
static double[] xval = new double[N];
static double[] t_sin = new double[N];
static double[] t_cos = new double[N];
static double[] t_tan = new double[N];
static double[] r_sin = new double[N2];
static double[] r_cos = new double[N2];
static double[] r_tan = new double[N2];
static double rho(double[] x, double[] y, double[] r, int i, int n) {
if (n < 0)
return 0;
if (n == 0)
return y[i];
int idx = (N - 1 - n) * (N - n) / 2 + i;
if (r[idx] != r[idx])
r[idx] = (x[i] - x[i + n])
/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))
+ rho(x, y, r, i + 1, n - 2);
return r[idx];
}
static double thiele(double[] x, double[] y, double[] r, double xin, int n) {
if (n > N - 1)
return 1;
return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)
+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);
}
public static void main(String[] args) {
for (int i = 0; i < N; i++) {
xval[i] = i * STEP;
t_sin[i] = sin(xval[i]);
t_cos[i] = cos(xval[i]);
t_tan[i] = t_sin[i] / t_cos[i];
}
for (int i = 0; i < N2; i++)
r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN;
System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0));
System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0));
System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0));
}
}
|
Please provide an equivalent version of this Python code in Java. | >>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
... def pr(n, fwords):
... while len(fwords) < n:
... fwords += [''.join(fwords[-2:][::-1])]
... v = fwords[n-1]
... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
... for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N Length Entropy Fibword
1 1 -0 1
2 1 -0 0
3 2 1 01
4 3 0.9182958 010
5 5 0.9709506 01001
6 8 0.954434 01001010
7 13 0.9612366 0100101001001
8 21 0.9587119 <too long>
9 34 0.9596869 <too long>
10 55 0.959316 <too long>
11 89 0.9594579 <too long>
12 144 0.9594038 <too long>
13 233 0.9594244 <too long>
14 377 0.9594165 <too long>
15 610 0.9594196 <too long>
16 987 0.9594184 <too long>
17 1597 0.9594188 <too long>
18 2584 0.9594187 <too long>
19 4181 0.9594187 <too long>
20 6765 0.9594187 <too long>
21 10946 0.9594187 <too long>
22 17711 0.9594187 <too long>
23 28657 0.9594187 <too long>
24 46368 0.9594187 <too long>
25 75025 0.9594187 <too long>
26 121393 0.9594187 <too long>
27 196418 0.9594187 <too long>
28 317811 0.9594187 <too long>
29 514229 0.9594187 <too long>
30 832040 0.9594187 <too long>
31 1346269 0.9594187 <too long>
32 2178309 0.9594187 <too long>
33 3524578 0.9594187 <too long>
34 5702887 0.9594187 <too long>
35 9227465 0.9594187 <too long>
36 14930352 0.9594187 <too long>
37 24157817 0.9594187 <too long>
>>>
| import java.util.*;
public class FWord {
private String fWord0 = "";
private String fWord1 = "";
private String nextFWord () {
final String result;
if ( "".equals ( fWord1 ) ) result = "1";
else if ( "".equals ( fWord0 ) ) result = "0";
else result = fWord1 + fWord0;
fWord0 = fWord1;
fWord1 = result;
return result;
}
public static double entropy ( final String source ) {
final int length = source.length ();
final Map < Character, Integer > counts = new HashMap < Character, Integer > ();
double result = 0.0;
for ( int i = 0; i < length; i++ ) {
final char c = source.charAt ( i );
if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );
else counts.put ( c, 1 );
}
for ( final int count : counts.values () ) {
final double proportion = ( double ) count / length;
result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );
}
return result;
}
public static void main ( final String [] args ) {
final FWord fWord = new FWord ();
for ( int i = 0; i < 37; ) {
final String word = fWord.nextFWord ();
System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) );
}
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | >>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
... def pr(n, fwords):
... while len(fwords) < n:
... fwords += [''.join(fwords[-2:][::-1])]
... v = fwords[n-1]
... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
... for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N Length Entropy Fibword
1 1 -0 1
2 1 -0 0
3 2 1 01
4 3 0.9182958 010
5 5 0.9709506 01001
6 8 0.954434 01001010
7 13 0.9612366 0100101001001
8 21 0.9587119 <too long>
9 34 0.9596869 <too long>
10 55 0.959316 <too long>
11 89 0.9594579 <too long>
12 144 0.9594038 <too long>
13 233 0.9594244 <too long>
14 377 0.9594165 <too long>
15 610 0.9594196 <too long>
16 987 0.9594184 <too long>
17 1597 0.9594188 <too long>
18 2584 0.9594187 <too long>
19 4181 0.9594187 <too long>
20 6765 0.9594187 <too long>
21 10946 0.9594187 <too long>
22 17711 0.9594187 <too long>
23 28657 0.9594187 <too long>
24 46368 0.9594187 <too long>
25 75025 0.9594187 <too long>
26 121393 0.9594187 <too long>
27 196418 0.9594187 <too long>
28 317811 0.9594187 <too long>
29 514229 0.9594187 <too long>
30 832040 0.9594187 <too long>
31 1346269 0.9594187 <too long>
32 2178309 0.9594187 <too long>
33 3524578 0.9594187 <too long>
34 5702887 0.9594187 <too long>
35 9227465 0.9594187 <too long>
36 14930352 0.9594187 <too long>
37 24157817 0.9594187 <too long>
>>>
| import java.util.*;
public class FWord {
private String fWord0 = "";
private String fWord1 = "";
private String nextFWord () {
final String result;
if ( "".equals ( fWord1 ) ) result = "1";
else if ( "".equals ( fWord0 ) ) result = "0";
else result = fWord1 + fWord0;
fWord0 = fWord1;
fWord1 = result;
return result;
}
public static double entropy ( final String source ) {
final int length = source.length ();
final Map < Character, Integer > counts = new HashMap < Character, Integer > ();
double result = 0.0;
for ( int i = 0; i < length; i++ ) {
final char c = source.charAt ( i );
if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 );
else counts.put ( c, 1 );
}
for ( final int count : counts.values () ) {
final double proportion = ( double ) count / length;
result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) );
}
return result;
}
public static void main ( final String [] args ) {
final FWord fWord = new FWord ();
for ( int i = 0; i < 37; ) {
final String word = fWord.nextFWord ();
System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) );
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize2rad(a):
while a < 0: a += TWO_PI
while a >= TWO_PI: a -= TWO_PI
return a
def deg2grad(a): return a * 10.0 / 9.0
def deg2mil(a): return a * 160.0 / 9.0
def deg2rad(a): return a * PI / 180.0
def grad2deg(a): return a * 9.0 / 10.0
def grad2mil(a): return a * 16.0
def grad2rad(a): return a * PI / 200.0
def mil2deg(a): return a * 9.0 / 160.0
def mil2grad(a): return a / 16.0
def mil2rad(a): return a * PI / 3200.0
def rad2deg(a): return a * 180.0 / PI
def rad2grad(a): return a * 200.0 / PI
def rad2mil(a): return a * 3200.0 / PI
| import java.text.DecimalFormat;
public class AnglesNormalizationAndConversion {
public static void main(String[] args) {
DecimalFormat formatAngle = new DecimalFormat("######0.000000");
DecimalFormat formatConv = new DecimalFormat("###0.0000");
System.out.printf(" degrees gradiens mils radians%n");
for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {
for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) {
double d = 0, g = 0, m = 0, r = 0;
switch (units) {
case "degrees":
d = d2d(angle);
g = d2g(d);
m = d2m(d);
r = d2r(d);
break;
case "gradiens":
g = g2g(angle);
d = g2d(g);
m = g2m(g);
r = g2r(g);
break;
case "mils":
m = m2m(angle);
d = m2d(m);
g = m2g(m);
r = m2r(m);
break;
case "radians":
r = r2r(angle);
d = r2d(r);
g = r2g(r);
m = r2m(r);
break;
}
System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));
}
}
}
private static final double DEGREE = 360D;
private static final double GRADIAN = 400D;
private static final double MIL = 6400D;
private static final double RADIAN = (2 * Math.PI);
private static double d2d(double a) {
return a % DEGREE;
}
private static double d2g(double a) {
return a * (GRADIAN / DEGREE);
}
private static double d2m(double a) {
return a * (MIL / DEGREE);
}
private static double d2r(double a) {
return a * (RADIAN / 360);
}
private static double g2d(double a) {
return a * (DEGREE / GRADIAN);
}
private static double g2g(double a) {
return a % GRADIAN;
}
private static double g2m(double a) {
return a * (MIL / GRADIAN);
}
private static double g2r(double a) {
return a * (RADIAN / GRADIAN);
}
private static double m2d(double a) {
return a * (DEGREE / MIL);
}
private static double m2g(double a) {
return a * (GRADIAN / MIL);
}
private static double m2m(double a) {
return a % MIL;
}
private static double m2r(double a) {
return a * (RADIAN / MIL);
}
private static double r2d(double a) {
return a * (DEGREE / RADIAN);
}
private static double r2g(double a) {
return a * (GRADIAN / RADIAN);
}
private static double r2m(double a) {
return a * (MIL / RADIAN);
}
private static double r2r(double a) {
return a % RADIAN;
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
| public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/");
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j];
boolean allMatched = true;
for(int i = 1; i < folders.length && allMatched; i++){
if(folders[i].length < j){
allMatched = false;
break;
}
allMatched &= folders[i][j].equals(thisFolder);
}
if(allMatched){
commonPath += thisFolder + "/";
}else{
break;
}
}
return commonPath;
}
public static void main(String[] args){
String[] paths = { "/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths));
String[] paths2 = { "/hame/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths2));
}
}
|
Keep all operations the same but rewrite the snippet in Java. | from collections import Counter
from pprint import pprint as pp
def distcheck(fn, repeats, delta):
bin = Counter(fn() for i in range(repeats))
target = repeats // len(bin)
deltacount = int(delta / 100. * target)
assert all( abs(target - count) < deltacount
for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
target, deltacount, [ (key, target - count)
for key, count in sorted(bin.items()) ]
)
pp(dict(bin))
| import static java.lang.Math.abs;
import java.util.*;
import java.util.function.IntSupplier;
public class Test {
static void distCheck(IntSupplier f, int nRepeats, double delta) {
Map<Integer, Integer> counts = new HashMap<>();
for (int i = 0; i < nRepeats; i++)
counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1);
double target = nRepeats / (double) counts.size();
int deltaCount = (int) (delta / 100.0 * target);
counts.forEach((k, v) -> {
if (abs(target - v) >= deltaCount)
System.out.printf("distribution potentially skewed "
+ "for '%s': '%d'%n", k, v);
});
counts.keySet().stream().sorted().forEach(k
-> System.out.printf("%d %d%n", k, counts.get(k)));
}
public static void main(String[] a) {
distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1);
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
| import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling2(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S2(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling2(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling2(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {
return BigInteger.ZERO;
}
if ( n == k ) {
return BigInteger.valueOf(1);
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));
COMPUTED.put(key, result);
return result;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
| import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling2(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S2(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling2(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling2(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {
return BigInteger.ZERO;
}
if ( n == k ) {
return BigInteger.valueOf(1);
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));
COMPUTED.put(key, result);
return result;
}
}
|
Keep all operations the same but rewrite the snippet in Java. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
| import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class SterlingNumbersSecondKind {
public static void main(String[] args) {
System.out.println("Stirling numbers of the second kind:");
int max = 12;
System.out.printf("n/k");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%10d", n);
}
System.out.printf("%n");
for ( int n = 0 ; n <= max ; n++ ) {
System.out.printf("%-3d", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%10s", sterling2(n, k));
}
System.out.printf("%n");
}
System.out.println("The maximum value of S2(100, k) = ");
BigInteger previous = BigInteger.ZERO;
for ( int k = 1 ; k <= 100 ; k++ ) {
BigInteger current = sterling2(100, k);
if ( current.compareTo(previous) > 0 ) {
previous = current;
}
else {
System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1);
break;
}
}
}
private static Map<String,BigInteger> COMPUTED = new HashMap<>();
private static final BigInteger sterling2(int n, int k) {
String key = n + "," + k;
if ( COMPUTED.containsKey(key) ) {
return COMPUTED.get(key);
}
if ( n == 0 && k == 0 ) {
return BigInteger.valueOf(1);
}
if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) {
return BigInteger.ZERO;
}
if ( n == k ) {
return BigInteger.valueOf(1);
}
if ( k > n ) {
return BigInteger.ZERO;
}
BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1));
COMPUTED.put(key, result);
return result;
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
| import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
| import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | >>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
>>> for typecode, initializer in argslist:
a = array(typecode, initializer)
print a
del a
array('l')
array('c', 'hello world')
array('u', u'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.1400000000000001])
>>>
|
Object foo = new Object();
int[] fooArray = new int[size];
int x = 0;
|
Write a version of this Python function in Java with identical behavior. |
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))
def score():
for w in wins:
b = board[w[0]]
if b in 'XO' and all (board[i] == b for i in w):
return b, [i+1 for i in w]
return None, None
def finished():
return all (b in 'XO' for b in board)
def space():
return [ b for b in board if b not in 'XO']
def my_turn(xo):
options = space()
choice = random.choice(options)
board[int(choice)-1] = xo
return choice
def your_turn(xo):
options = space()
while True:
choice = input(" Put your %s in any of these positions: %s "
% (xo, ''.join(options))).strip()
if choice in options:
break
print( "Whoops I don't understand the input" )
board[int(choice)-1] = xo
return choice
def me(xo='X'):
printboard()
print('I go at', my_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
def you(xo='O'):
printboard()
print('You went at', your_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
print(__doc__)
while not finished():
s = me('X')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
if not finished():
s = you('O')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
else:
print('\nA draw')
| import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToe now=new TicTacToe();
now.startMatch();
}
private int[][] marks;
private int[][] wins;
private int[] weights;
private char[][] grid;
private final int knotcount=3;
private final int crosscount=4;
private final int totalcount=5;
private final int playerid=0;
private final int compid=1;
private final int truceid=2;
private final int playingid=3;
private String movesPlayer;
private byte override;
private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
private Hashtable<Integer,Integer> crossbank;
private Hashtable<Integer,Integer> knotbank;
public void startMatch()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Start?(y/n):");
char choice='y';
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(choice=='n'||choice=='N')
{
return;
}
System.out.println("Use a standard numpad as an entry grid, as so:\n ");
display(numpad);
System.out.println("Begin");
int playerscore=0;
int compscore=0;
do
{
int result=startGame();
if(result==playerid)
playerscore++;
else if(result==compid)
compscore++;
System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
System.out.print("Another?(y/n):");
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}while(choice!='n'||choice=='N');
System.out.println("Game over.");
}
private void put(int cell,int player)
{
int i=-1,j=-1;;
switch(cell)
{
case 1:i=2;j=0;break;
case 2:i=2;j=1;break;
case 3:i=2;j=2;break;
case 4:i=1;j=0;break;
case 5:i=1;j=1;break;
case 6:i=1;j=2;break;
case 7:i=0;j=0;break;
case 8:i=0;j=1;break;
case 9:i=0;j=2;break;
default:display(overridegrid);return;
}
char mark='x';
if(player==0)
mark='o';
grid[i][j]=mark;
display(grid);
}
private int startGame()
{
init();
display(grid);
int status=playingid;
while(status==playingid)
{
put(playerMove(),0);
if(override==1)
{
System.out.println("O wins.");
return playerid;
}
status=checkForWin();
if(status!=playingid)
break;
try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
put(compMove(),1);
status=checkForWin();
}
return status;
}
private void init()
{
movesPlayer="";
override=0;
marks=new int[8][6];
wins=new int[][]
{
{7,8,9},
{4,5,6},
{1,2,3},
{7,4,1},
{8,5,2},
{9,6,3},
{7,5,3},
{9,5,1}
};
weights=new int[]{3,2,3,2,4,2,3,2,3};
grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
crossbank=new Hashtable<Integer,Integer>();
knotbank=new Hashtable<Integer,Integer>();
}
private void mark(int m,int player)
{
for(int i=0;i<wins.length;i++)
for(int j=0;j<wins[i].length;j++)
if(wins[i][j]==m)
{
marks[i][j]=1;
if(player==playerid)
marks[i][knotcount]++;
else
marks[i][crosscount]++;
marks[i][totalcount]++;
}
}
private void fixWeights()
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(marks[i][j]==1)
if(weights[wins[i][j]-1]!=Integer.MIN_VALUE)
weights[wins[i][j]-1]=Integer.MIN_VALUE;
for(int i=0;i<8;i++)
{
if(marks[i][totalcount]!=2)
continue;
if(marks[i][crosscount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=6;
}
}
if(marks[i][knotcount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=5;
}
}
}
}
private int compMove()
{
int cell=move();
System.out.println("Computer plays: "+cell);
return cell;
}
private int move()
{
int max=Integer.MIN_VALUE;
int cell=0;
for(int i=0;i<weights.length;i++)
if(weights[i]>max)
{
max=weights[i];
cell=i+1;
}
if(movesPlayer.equals("76")||movesPlayer.equals("67"))
cell=9;
else if(movesPlayer.equals("92")||movesPlayer.equals("29"))
cell=3;
else if (movesPlayer.equals("18")||movesPlayer.equals("81"))
cell=7;
else if(movesPlayer.equals("73")||movesPlayer.equals("37"))
cell=4*((int)(Math.random()*2)+1);
else if(movesPlayer.equals("19")||movesPlayer.equals("91"))
cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));
mark(cell,1);
fixWeights();
crossbank.put(cell, 0);
return cell;
}
private int playerMove()
{
System.out.print("What's your move?: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int cell=0;
int okay=0;
while(okay==0)
{
try
{
cell=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(cell==7494)
{
override=1;
return -1;
}
if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)
System.out.print("Invalid move. Try again:");
else
okay=1;
}
playerMoved(cell);
System.out.println();
return cell;
}
private void playerMoved(int cell)
{
movesPlayer+=cell;
mark(cell,0);
fixWeights();
knotbank.put(cell, 0);
}
private int checkForWin()
{
int crossflag=0,knotflag=0;
for(int i=0;i<wins.length;i++)
{
if(crossbank.containsKey(wins[i][0]))
if(crossbank.containsKey(wins[i][1]))
if(crossbank.containsKey(wins[i][2]))
{
crossflag=1;
break;
}
if(knotbank.containsKey(wins[i][0]))
if(knotbank.containsKey(wins[i][1]))
if(knotbank.containsKey(wins[i][2]))
{
knotflag=1;
break;
}
}
if(knotflag==1)
{
display(grid);
System.out.println("O wins.");
return playerid;
}
else if(crossflag==1)
{
display(grid);
System.out.println("X wins.");
return compid;
}
for(int i=0;i<weights.length;i++)
if(weights[i]!=Integer.MIN_VALUE)
return playingid;
System.out.println("Truce");
return truceid;
}
private void display(char[][] grid)
{
for(int i=0;i<3;i++)
{
System.out.println("\n-------");
System.out.print("|");
for(int j=0;j<3;j++)
System.out.print(grid[i][j]+"|");
}
System.out.println("\n-------");
}
}
|
Convert this Python block to Java, preserving its control flow and logic. |
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))
def score():
for w in wins:
b = board[w[0]]
if b in 'XO' and all (board[i] == b for i in w):
return b, [i+1 for i in w]
return None, None
def finished():
return all (b in 'XO' for b in board)
def space():
return [ b for b in board if b not in 'XO']
def my_turn(xo):
options = space()
choice = random.choice(options)
board[int(choice)-1] = xo
return choice
def your_turn(xo):
options = space()
while True:
choice = input(" Put your %s in any of these positions: %s "
% (xo, ''.join(options))).strip()
if choice in options:
break
print( "Whoops I don't understand the input" )
board[int(choice)-1] = xo
return choice
def me(xo='X'):
printboard()
print('I go at', my_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
def you(xo='O'):
printboard()
print('You went at', your_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
print(__doc__)
while not finished():
s = me('X')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
if not finished():
s = you('O')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
else:
print('\nA draw')
| import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToe now=new TicTacToe();
now.startMatch();
}
private int[][] marks;
private int[][] wins;
private int[] weights;
private char[][] grid;
private final int knotcount=3;
private final int crosscount=4;
private final int totalcount=5;
private final int playerid=0;
private final int compid=1;
private final int truceid=2;
private final int playingid=3;
private String movesPlayer;
private byte override;
private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
private Hashtable<Integer,Integer> crossbank;
private Hashtable<Integer,Integer> knotbank;
public void startMatch()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Start?(y/n):");
char choice='y';
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(choice=='n'||choice=='N')
{
return;
}
System.out.println("Use a standard numpad as an entry grid, as so:\n ");
display(numpad);
System.out.println("Begin");
int playerscore=0;
int compscore=0;
do
{
int result=startGame();
if(result==playerid)
playerscore++;
else if(result==compid)
compscore++;
System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
System.out.print("Another?(y/n):");
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}while(choice!='n'||choice=='N');
System.out.println("Game over.");
}
private void put(int cell,int player)
{
int i=-1,j=-1;;
switch(cell)
{
case 1:i=2;j=0;break;
case 2:i=2;j=1;break;
case 3:i=2;j=2;break;
case 4:i=1;j=0;break;
case 5:i=1;j=1;break;
case 6:i=1;j=2;break;
case 7:i=0;j=0;break;
case 8:i=0;j=1;break;
case 9:i=0;j=2;break;
default:display(overridegrid);return;
}
char mark='x';
if(player==0)
mark='o';
grid[i][j]=mark;
display(grid);
}
private int startGame()
{
init();
display(grid);
int status=playingid;
while(status==playingid)
{
put(playerMove(),0);
if(override==1)
{
System.out.println("O wins.");
return playerid;
}
status=checkForWin();
if(status!=playingid)
break;
try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
put(compMove(),1);
status=checkForWin();
}
return status;
}
private void init()
{
movesPlayer="";
override=0;
marks=new int[8][6];
wins=new int[][]
{
{7,8,9},
{4,5,6},
{1,2,3},
{7,4,1},
{8,5,2},
{9,6,3},
{7,5,3},
{9,5,1}
};
weights=new int[]{3,2,3,2,4,2,3,2,3};
grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
crossbank=new Hashtable<Integer,Integer>();
knotbank=new Hashtable<Integer,Integer>();
}
private void mark(int m,int player)
{
for(int i=0;i<wins.length;i++)
for(int j=0;j<wins[i].length;j++)
if(wins[i][j]==m)
{
marks[i][j]=1;
if(player==playerid)
marks[i][knotcount]++;
else
marks[i][crosscount]++;
marks[i][totalcount]++;
}
}
private void fixWeights()
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(marks[i][j]==1)
if(weights[wins[i][j]-1]!=Integer.MIN_VALUE)
weights[wins[i][j]-1]=Integer.MIN_VALUE;
for(int i=0;i<8;i++)
{
if(marks[i][totalcount]!=2)
continue;
if(marks[i][crosscount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=6;
}
}
if(marks[i][knotcount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=5;
}
}
}
}
private int compMove()
{
int cell=move();
System.out.println("Computer plays: "+cell);
return cell;
}
private int move()
{
int max=Integer.MIN_VALUE;
int cell=0;
for(int i=0;i<weights.length;i++)
if(weights[i]>max)
{
max=weights[i];
cell=i+1;
}
if(movesPlayer.equals("76")||movesPlayer.equals("67"))
cell=9;
else if(movesPlayer.equals("92")||movesPlayer.equals("29"))
cell=3;
else if (movesPlayer.equals("18")||movesPlayer.equals("81"))
cell=7;
else if(movesPlayer.equals("73")||movesPlayer.equals("37"))
cell=4*((int)(Math.random()*2)+1);
else if(movesPlayer.equals("19")||movesPlayer.equals("91"))
cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));
mark(cell,1);
fixWeights();
crossbank.put(cell, 0);
return cell;
}
private int playerMove()
{
System.out.print("What's your move?: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int cell=0;
int okay=0;
while(okay==0)
{
try
{
cell=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(cell==7494)
{
override=1;
return -1;
}
if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)
System.out.print("Invalid move. Try again:");
else
okay=1;
}
playerMoved(cell);
System.out.println();
return cell;
}
private void playerMoved(int cell)
{
movesPlayer+=cell;
mark(cell,0);
fixWeights();
knotbank.put(cell, 0);
}
private int checkForWin()
{
int crossflag=0,knotflag=0;
for(int i=0;i<wins.length;i++)
{
if(crossbank.containsKey(wins[i][0]))
if(crossbank.containsKey(wins[i][1]))
if(crossbank.containsKey(wins[i][2]))
{
crossflag=1;
break;
}
if(knotbank.containsKey(wins[i][0]))
if(knotbank.containsKey(wins[i][1]))
if(knotbank.containsKey(wins[i][2]))
{
knotflag=1;
break;
}
}
if(knotflag==1)
{
display(grid);
System.out.println("O wins.");
return playerid;
}
else if(crossflag==1)
{
display(grid);
System.out.println("X wins.");
return compid;
}
for(int i=0;i<weights.length;i++)
if(weights[i]!=Integer.MIN_VALUE)
return playingid;
System.out.println("Truce");
return truceid;
}
private void display(char[][] grid)
{
for(int i=0;i<3;i++)
{
System.out.println("\n-------");
System.out.print("|");
for(int j=0;j<3;j++)
System.out.print(grid[i][j]+"|");
}
System.out.println("\n-------");
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | i=1
while i:
print(i)
i += 1
| public class Count{
public static void main(String[] args){
for(long i = 1; ;i++) System.out.println(i);
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | i=1
while i:
print(i)
i += 1
| public class Count{
public static void main(String[] args){
for(long i = 1; ;i++) System.out.println(i);
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | i=1
while i:
print(i)
i += 1
| public class Count{
public static void main(String[] args){
for(long i = 1; ;i++) System.out.println(i);
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | import math
from collections import Counter
def entropy(s):
p, lns = Counter(s), float(len(s))
return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
with open(__file__) as f:
b=f.read()
print(entropy(b))
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | import math
from collections import Counter
def entropy(s):
p, lns = Counter(s), float(len(s))
return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
with open(__file__) as f:
b=f.read()
print(entropy(b))
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194
| import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
class DnsQuery {
public static void main(String[] args) {
try {
InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net");
for(int i=0; i < ipAddr.length ; i++) {
if (ipAddr[i] instanceof Inet4Address) {
System.out.println("IPv4 : " + ipAddr[i].getHostAddress());
} else if (ipAddr[i] instanceof Inet6Address) {
System.out.println("IPv6 : " + ipAddr[i].getHostAddress());
}
}
} catch (UnknownHostException uhe) {
System.err.println("unknown host");
}
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | import turtle as tt
import inspect
stack = []
def peano(iterations=1):
global stack
ivan = tt.Turtle(shape = "classic", visible = True)
screen = tt.Screen()
screen.title("Desenhin do Peano")
screen.bgcolor("
screen.delay(0)
screen.setup(width=0.95, height=0.9)
walk = 1
def screenlength(k):
if k != 0:
length = screenlength(k-1)
return 2*length + 1
else: return 0
kkkj = screenlength(iterations)
screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)
ivan.color("
def step1(k):
global stack
stack.append(len(inspect.stack()))
if k != 0:
ivan.left(90)
step2(k - 1)
ivan.forward(walk)
ivan.right(90)
step1(k - 1)
ivan.forward(walk)
step1(k - 1)
ivan.right(90)
ivan.forward(walk)
step2(k - 1)
ivan.left(90)
def step2(k):
global stack
stack.append(len(inspect.stack()))
if k != 0:
ivan.right(90)
step1(k - 1)
ivan.forward(walk)
ivan.left(90)
step2(k - 1)
ivan.forward(walk)
step2(k - 1)
ivan.left(90)
ivan.forward(walk)
step1(k - 1)
ivan.right(90)
ivan.left(90)
step2(iterations)
tt.done()
if __name__ == "__main__":
peano(4)
import pylab as P
P.plot(stack)
P.show()
| import java.io.*;
public class PeanoCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) {
PeanoCurve s = new PeanoCurve(writer);
final int length = 8;
s.currentAngle = 90;
s.currentX = length;
s.currentY = length;
s.lineLength = length;
s.begin(656);
s.execute(rewrite(4));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private PeanoCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY += length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = "L";
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'L')
sb.append("LFRFL-F-RFLFR+F+LFRFL");
else if (ch == 'R')
sb.append("RFLFR+F+LFRFL-F-RFLFR");
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final int ANGLE = 90;
}
|
Write a version of this Python function in Java with identical behavior. | from random import randint
def dice5():
return randint(1, 5)
def dice7():
r = dice5() + dice5() * 5 - 6
return (r % 7) + 1 if r < 21 else dice7()
| import java.util.Random;
public class SevenSidedDice
{
private static final Random rnd = new Random();
public static void main(String[] args)
{
SevenSidedDice now=new SevenSidedDice();
System.out.println("Random number from 1 to 7: "+now.seven());
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1+rnd.nextInt(5);
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from __future__ import print_function
from itertools import permutations
from enum import Enum
A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')
connections = ((A, C), (A, D), (A, E),
(B, D), (B, E), (B, F),
(G, C), (G, D), (G, E),
(H, D), (H, E), (H, F),
(C, D), (D, E), (E, F))
def ok(conn, perm):
this, that = (c.value - 1 for c in conn)
return abs(perm[this] - perm[that]) != 1
def solve():
return [perm for perm in permutations(range(1, 9))
if all(ok(conn, perm) for conn in connections)]
if __name__ == '__main__':
solutions = solve()
print("A, B, C, D, E, F, G, H =", ', '.join(str(i) for i in solutions[0]))
| import static java.lang.Math.abs;
import java.util.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public class NoConnection {
static int[][] links = {
{2, 3, 4},
{3, 4, 5},
{2, 4},
{5},
{2, 3, 4},
{3, 4, 5},
};
static int[] pegs = new int[8];
public static void main(String[] args) {
List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());
do {
Collections.shuffle(vals);
for (int i = 0; i < pegs.length; i++)
pegs[i] = vals.get(i);
} while (!solved());
printResult();
}
static boolean solved() {
for (int i = 0; i < links.length; i++)
for (int peg : links[i])
if (abs(pegs[i] - peg) == 1)
return false;
return true;
}
static void printResult() {
System.out.printf(" %s %s%n", pegs[0], pegs[1]);
System.out.printf("%s %s %s %s%n", pegs[2], pegs[3], pegs[4], pegs[5]);
System.out.printf(" %s %s%n", pegs[6], pegs[7]);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | from __future__ import print_function
from itertools import permutations
from enum import Enum
A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')
connections = ((A, C), (A, D), (A, E),
(B, D), (B, E), (B, F),
(G, C), (G, D), (G, E),
(H, D), (H, E), (H, F),
(C, D), (D, E), (E, F))
def ok(conn, perm):
this, that = (c.value - 1 for c in conn)
return abs(perm[this] - perm[that]) != 1
def solve():
return [perm for perm in permutations(range(1, 9))
if all(ok(conn, perm) for conn in connections)]
if __name__ == '__main__':
solutions = solve()
print("A, B, C, D, E, F, G, H =", ', '.join(str(i) for i in solutions[0]))
| import static java.lang.Math.abs;
import java.util.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public class NoConnection {
static int[][] links = {
{2, 3, 4},
{3, 4, 5},
{2, 4},
{5},
{2, 3, 4},
{3, 4, 5},
};
static int[] pegs = new int[8];
public static void main(String[] args) {
List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());
do {
Collections.shuffle(vals);
for (int i = 0; i < pegs.length; i++)
pegs[i] = vals.get(i);
} while (!solved());
printResult();
}
static boolean solved() {
for (int i = 0; i < links.length; i++)
for (int peg : links[i])
if (abs(pegs[i] - peg) == 1)
return false;
return true;
}
static void printResult() {
System.out.printf(" %s %s%n", pegs[0], pegs[1]);
System.out.printf("%s %s %s %s%n", pegs[2], pegs[3], pegs[4], pegs[5]);
System.out.printf(" %s %s%n", pegs[6], pegs[7]);
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | islice(count(7), 0, None, 2)
| import java.util.*;
public class PrimeGenerator {
private int limit_;
private int index_ = 0;
private int increment_;
private int count_ = 0;
private List<Integer> primes_ = new ArrayList<>();
private BitSet sieve_ = new BitSet();
private int sieveLimit_ = 0;
public PrimeGenerator(int initialLimit, int increment) {
limit_ = nextOddNumber(initialLimit);
increment_ = increment;
primes_.add(2);
findPrimes(3);
}
public int nextPrime() {
if (index_ == primes_.size()) {
if (Integer.MAX_VALUE - increment_ < limit_)
return 0;
int start = limit_ + 2;
limit_ = nextOddNumber(limit_ + increment_);
primes_.clear();
findPrimes(start);
}
++count_;
return primes_.get(index_++);
}
public int count() {
return count_;
}
private void findPrimes(int start) {
index_ = 0;
int newLimit = sqrt(limit_);
for (int p = 3; p * p <= newLimit; p += 2) {
if (sieve_.get(p/2 - 1))
continue;
int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p));
for (; q <= newLimit; q += 2*p)
sieve_.set(q/2 - 1, true);
}
sieveLimit_ = newLimit;
int count = (limit_ - start)/2 + 1;
BitSet composite = new BitSet(count);
for (int p = 3; p <= newLimit; p += 2) {
if (sieve_.get(p/2 - 1))
continue;
int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start;
q /= 2;
for (; q >= 0 && q < count; q += p)
composite.set(q, true);
}
for (int p = 0; p < count; ++p) {
if (!composite.get(p))
primes_.add(p * 2 + start);
}
}
private static int sqrt(int n) {
return nextOddNumber((int)Math.sqrt(n));
}
private static int nextOddNumber(int n) {
return 1 + 2 * (n/2);
}
public static void main(String[] args) {
PrimeGenerator pgen = new PrimeGenerator(20, 200000);
System.out.println("First 20 primes:");
for (int i = 0; i < 20; ++i) {
if (i > 0)
System.out.print(", ");
System.out.print(pgen.nextPrime());
}
System.out.println();
System.out.println("Primes between 100 and 150:");
for (int i = 0; ; ) {
int prime = pgen.nextPrime();
if (prime > 150)
break;
if (prime >= 100) {
if (i++ != 0)
System.out.print(", ");
System.out.print(prime);
}
}
System.out.println();
int count = 0;
for (;;) {
int prime = pgen.nextPrime();
if (prime > 8000)
break;
if (prime >= 7700)
++count;
}
System.out.println("Number of primes between 7700 and 8000: " + count);
int n = 10000;
for (;;) {
int prime = pgen.nextPrime();
if (prime == 0) {
System.out.println("Can't generate any more primes.");
break;
}
if (pgen.count() == n) {
System.out.println(n + "th prime: " + prime);
n *= 10;
}
}
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | from random import choice
rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
previous = ['rock', 'paper', 'scissors']
while True:
human = input('\nchoose your weapon: ')
computer = rules[choice(previous)]
if human in ('quit', 'exit'): break
elif human in rules:
previous.append(human)
print('the computer played', computer, end='; ')
if rules[computer] == human:
print('yay you win!')
elif rules[human] == computer:
print('the computer beat you... :(')
else: print("it's a tie!")
else: print("that's not a valid choice")
| import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Random;
public class RPS {
public enum Item{
ROCK, PAPER, SCISSORS, ;
public List<Item> losesToList;
public boolean losesTo(Item other) {
return losesToList.contains(other);
}
static {
SCISSORS.losesToList = Arrays.asList(ROCK);
ROCK.losesToList = Arrays.asList(PAPER);
PAPER.losesToList = Arrays.asList(SCISSORS);
}
}
public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{
for(Item item:Item.values())
put(item, 1);
}};
private int totalThrows = Item.values().length;
public static void main(String[] args){
RPS rps = new RPS();
rps.run();
}
public void run() {
Scanner in = new Scanner(System.in);
System.out.print("Make your choice: ");
while(in.hasNextLine()){
Item aiChoice = getAIChoice();
String input = in.nextLine();
Item choice;
try{
choice = Item.valueOf(input.toUpperCase());
}catch (IllegalArgumentException ex){
System.out.println("Invalid choice");
continue;
}
counts.put(choice, counts.get(choice) + 1);
totalThrows++;
System.out.println("Computer chose: " + aiChoice);
if(aiChoice == choice){
System.out.println("Tie!");
}else if(aiChoice.losesTo(choice)){
System.out.println("You chose...wisely. You win!");
}else{
System.out.println("You chose...poorly. You lose!");
}
System.out.print("Make your choice: ");
}
}
private static final Random rng = new Random();
private Item getAIChoice() {
int rand = rng.nextInt(totalThrows);
for(Map.Entry<Item, Integer> entry:counts.entrySet()){
Item item = entry.getKey();
int count = entry.getValue();
if(rand < count){
List<Item> losesTo = item.losesToList;
return losesTo.get(rng.nextInt(losesTo.size()));
}
rand -= count;
}
return null;
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
| import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. |
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a)
| import static java.util.Arrays.stream;
public class ChineseRemainderTheorem {
public static int chineseRemainder(int[] n, int[] a) {
int prod = stream(n).reduce(1, (i, j) -> i * j);
int p, sm = 0;
for (int i = 0; i < n.length; i++) {
p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
private static int mulInv(int a, int b) {
int b0 = b;
int x0 = 0;
int x1 = 1;
if (b == 1)
return 1;
while (a > 1) {
int q = a / b;
int amb = a % b;
a = b;
b = amb;
int xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0)
x1 += b0;
return x1;
}
public static void main(String[] args) {
int[] n = {3, 5, 7};
int[] a = {2, 3, 2};
System.out.println(chineseRemainder(n, a));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. |
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a)
| import static java.util.Arrays.stream;
public class ChineseRemainderTheorem {
public static int chineseRemainder(int[] n, int[] a) {
int prod = stream(n).reduce(1, (i, j) -> i * j);
int p, sm = 0;
for (int i = 0; i < n.length; i++) {
p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
private static int mulInv(int a, int b) {
int b0 = b;
int x0 = 0;
int x1 = 1;
if (b == 1)
return 1;
while (a > 1) {
int q = a / b;
int amb = a % b;
a = b;
b = amb;
int xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0)
x1 += b0;
return x1;
}
public static void main(String[] args) {
int[] n = {3, 5, 7};
int[] a = {2, 3, 2};
System.out.println(chineseRemainder(n, a));
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | from string import uppercase
from operator import itemgetter
def vigenere_decrypt(target_freqs, input):
nchars = len(uppercase)
ordA = ord('A')
sorted_targets = sorted(target_freqs)
def frequency(input):
result = [[c, 0.0] for c in uppercase]
for c in input:
result[c - ordA][1] += 1
return result
def correlation(input):
result = 0.0
freq = frequency(input)
freq.sort(key=itemgetter(1))
for i, f in enumerate(freq):
result += f[1] * sorted_targets[i]
return result
cleaned = [ord(c) for c in input.upper() if c.isupper()]
best_len = 0
best_corr = -100.0
for i in xrange(2, len(cleaned) // 20):
pieces = [[] for _ in xrange(i)]
for j, c in enumerate(cleaned):
pieces[j % i].append(c)
corr = -0.5 * i + sum(correlation(p) for p in pieces)
if corr > best_corr:
best_len = i
best_corr = corr
if best_len == 0:
return ("Text is too short to analyze", "")
pieces = [[] for _ in xrange(best_len)]
for i, c in enumerate(cleaned):
pieces[i % best_len].append(c)
freqs = [frequency(p) for p in pieces]
key = ""
for fr in freqs:
fr.sort(key=itemgetter(1), reverse=True)
m = 0
max_corr = 0.0
for j in xrange(nchars):
corr = 0.0
c = ordA + j
for frc in fr:
d = (ord(frc[0]) - c + nchars) % nchars
corr += frc[1] * target_freqs[d]
if corr > max_corr:
m = j
max_corr = corr
key += chr(m + ordA)
r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)
for i, c in enumerate(cleaned))
return (key, "".join(r))
def main():
encoded =
english_frequences = [
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074]
(key, decoded) = vigenere_decrypt(english_frequences, encoded)
print "Key:", key
print "\nText:", decoded
main()
| public class Vig{
static String encodedMessage =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK";
final static double freq[] = {
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074
};
public static void main(String[] args) {
int lenghtOfEncodedMessage = encodedMessage.length();
char[] encoded = new char [lenghtOfEncodedMessage] ;
char[] key = new char [lenghtOfEncodedMessage] ;
encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0);
int txt[] = new int[lenghtOfEncodedMessage];
int len = 0, j;
double fit, best_fit = 1e100;
for (j = 0; j < lenghtOfEncodedMessage; j++)
if (Character.isUpperCase(encoded[j]))
txt[len++] = encoded[j] - 'A';
for (j = 1; j < 30; j++) {
fit = freq_every_nth(txt, len, j, key);
System.out.printf("%f, key length: %2d ", fit, j);
System.out.print(key);
if (fit < best_fit) {
best_fit = fit;
System.out.print(" <--- best so far");
}
System.out.print("\n");
}
}
static String decrypt(String text, final String key) {
String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < 'A' || c > 'Z') continue;
res += (char)((c - key.charAt(j) + 26) % 26 + 'A');
j = ++j % key.length();
}
return res;
}
static int best_match(final double []a, final double []b) {
double sum = 0, fit, d, best_fit = 1e100;
int i, rotate, best_rotate = 0;
for (i = 0; i < 26; i++)
sum += a[i];
for (rotate = 0; rotate < 26; rotate++) {
fit = 0;
for (i = 0; i < 26; i++) {
d = a[(i + rotate) % 26] / sum - b[i];
fit += d * d / b[i];
}
if (fit < best_fit) {
best_fit = fit;
best_rotate = rotate;
}
}
return best_rotate;
}
static double freq_every_nth(final int []msg, int len, int interval, char[] key) {
double sum, d, ret;
double [] accu = new double [26];
double [] out = new double [26];
int i, j, rot;
for (j = 0; j < interval; j++) {
for (i = 0; i < 26; i++)
out[i] = 0;
for (i = j; i < len; i += interval)
out[msg[i]]++;
rot = best_match(out, freq);
try{
key[j] = (char)(rot + 'A');
} catch (Exception e) {
System.out.print(e.getMessage());
}
for (i = 0; i < 26; i++)
accu[i] += out[(i + rot) % 26];
}
for (i = 0, sum = 0; i < 26; i++)
sum += accu[i];
for (i = 0, ret = 0; i < 26; i++) {
d = accu[i] / sum - freq[i];
ret += d * d / freq[i];
}
key[interval] = '\0';
return ret;
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0
| import java.math.BigInteger ;
public class Pi {
final BigInteger TWO = BigInteger.valueOf(2) ;
final BigInteger THREE = BigInteger.valueOf(3) ;
final BigInteger FOUR = BigInteger.valueOf(4) ;
final BigInteger SEVEN = BigInteger.valueOf(7) ;
BigInteger q = BigInteger.ONE ;
BigInteger r = BigInteger.ZERO ;
BigInteger t = BigInteger.ONE ;
BigInteger k = BigInteger.ONE ;
BigInteger n = BigInteger.valueOf(3) ;
BigInteger l = BigInteger.valueOf(3) ;
public void calcPiDigits(){
BigInteger nn, nr ;
boolean first = true ;
while(true){
if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){
System.out.print(n) ;
if(first){System.out.print(".") ; first = false ;}
nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ;
n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ;
q = q.multiply(BigInteger.TEN) ;
r = nr ;
System.out.flush() ;
}else{
nr = TWO.multiply(q).add(r).multiply(l) ;
nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ;
q = q.multiply(k) ;
t = t.multiply(l) ;
l = l.add(TWO) ;
k = k.add(BigInteger.ONE) ;
n = nn ;
r = nr ;
}
}
}
public static void main(String[] args) {
Pi p = new Pi() ;
p.calcPiDigits() ;
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | def q(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return q.seq[n]
except IndexError:
ans = q(n - q(n - 1)) + q(n - q(n - 2))
q.seq.append(ans)
return ans
q.seq = [None, 1, 1]
if __name__ == '__main__':
first10 = [q(i) for i in range(1,11)]
assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)"
print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10))
assert q(1000) == 502, "Q(1000) value error"
print("Q(1000) =", q(1000))
| import java.util.HashMap;
import java.util.Map;
public class HofQ {
private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{
put(1, 1);
put(2, 1);
}};
private static int[] nUses = new int[100001];
public static int Q(int n){
nUses[n]++;
if(q.containsKey(n)){
return q.get(n);
}
int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));
q.put(n, ans);
return ans;
}
public static void main(String[] args){
for(int i = 1; i <= 10; i++){
System.out.println("Q(" + i + ") = " + Q(i));
}
int last = 6;
int count = 0;
for(int i = 11; i <= 100000; i++){
int curr = Q(i);
if(curr < last) count++;
last = curr;
if(i == 1000) System.out.println("Q(1000) = " + curr);
}
System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times");
int maxUses = 0, maxN = 0;
for(int i = 1; i<nUses.length;i++){
if(nUses[i] > maxUses){
maxUses = nUses[i];
maxN = i;
}
}
System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls");
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def q(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return q.seq[n]
except IndexError:
ans = q(n - q(n - 1)) + q(n - q(n - 2))
q.seq.append(ans)
return ans
q.seq = [None, 1, 1]
if __name__ == '__main__':
first10 = [q(i) for i in range(1,11)]
assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)"
print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10))
assert q(1000) == 502, "Q(1000) value error"
print("Q(1000) =", q(1000))
| import java.util.HashMap;
import java.util.Map;
public class HofQ {
private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{
put(1, 1);
put(2, 1);
}};
private static int[] nUses = new int[100001];
public static int Q(int n){
nUses[n]++;
if(q.containsKey(n)){
return q.get(n);
}
int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2));
q.put(n, ans);
return ans;
}
public static void main(String[] args){
for(int i = 1; i <= 10; i++){
System.out.println("Q(" + i + ") = " + Q(i));
}
int last = 6;
int count = 0;
for(int i = 11; i <= 100000; i++){
int curr = Q(i);
if(curr < last) count++;
last = curr;
if(i == 1000) System.out.println("Q(1000) = " + curr);
}
System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times");
int maxUses = 0, maxN = 0;
for(int i = 1; i<nUses.length;i++){
if(nUses[i] > maxUses){
maxUses = nUses[i];
maxN = i;
}
}
System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls");
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| import java.util.function.Function;
public interface YCombinator {
interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }
public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {
RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));
return r.apply(r);
}
public static void main(String... arguments) {
Function<Integer,Integer> fib = Y(f -> n ->
(n <= 2)
? 1
: (f.apply(n - 1) + f.apply(n - 2))
);
Function<Integer,Integer> fac = Y(f -> n ->
(n <= 1)
? 1
: (n * f.apply(n - 1))
);
System.out.println("fib(10) = " + fib.apply(10));
System.out.println("fac(10) = " + fac.apply(10));
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | def addsub(x, y):
return x + y, x - y
| import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class RReturnMultipleVals {
public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
public static final Long K_1024 = 1024L;
public static final String L = "L";
public static final String R = "R";
public static void main(String[] args) throws NumberFormatException{
Long nv_;
String sv_;
switch (args.length) {
case 0:
nv_ = K_1024;
sv_ = K_lipsum;
break;
case 1:
nv_ = Long.parseLong(args[0]);
sv_ = K_lipsum;
break;
case 2:
nv_ = Long.parseLong(args[0]);
sv_ = args[1];
break;
default:
nv_ = Long.parseLong(args[0]);
sv_ = args[1];
for (int ix = 2; ix < args.length; ++ix) {
sv_ = sv_ + " " + args[ix];
}
break;
}
RReturnMultipleVals lcl = new RReturnMultipleVals();
Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_);
System.out.println("Results extracted from a composite object:");
System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal());
List<Object> rvl = lcl.getPairFromList(nv_, sv_);
System.out.println("Results extracted from a Java Colections \"List\" object:");
System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1));
Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_);
System.out.println("Results extracted from a Java Colections \"Map\" object:");
System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R));
}
public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {
return new Pair<T, U>(vl_, vr_);
}
public List<Object> getPairFromList(Object nv_, Object sv_) {
List<Object> rset = new ArrayList<Object>();
rset.add(nv_);
rset.add(sv_);
return rset;
}
public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {
Map<String, Object> rset = new HashMap<String, Object>();
rset.put(L, nv_);
rset.put(R, sv_);
return rset;
}
private static class Pair<L, R> {
private L leftVal;
private R rightVal;
public Pair(L nv_, R sv_) {
setLeftVal(nv_);
setRightVal(sv_);
}
public void setLeftVal(L nv_) {
leftVal = nv_;
}
public L getLeftVal() {
return leftVal;
}
public void setRightVal(R sv_) {
rightVal = sv_;
}
public R getRightVal() {
return rightVal;
}
}
}
|
Change the following Python code into Java without altering its purpose. | def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
| import java.util.HashMap;
import java.util.Map;
public class VanEckSequence {
public static void main(String[] args) {
System.out.println("First 10 terms of Van Eck's sequence:");
vanEck(1, 10);
System.out.println("");
System.out.println("Terms 991 to 1000 of Van Eck's sequence:");
vanEck(991, 1000);
}
private static void vanEck(int firstIndex, int lastIndex) {
Map<Integer,Integer> vanEckMap = new HashMap<>();
int last = 0;
if ( firstIndex == 1 ) {
System.out.printf("VanEck[%d] = %d%n", 1, 0);
}
for ( int n = 2 ; n <= lastIndex ; n++ ) {
int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;
vanEckMap.put(last, n);
last = vanEck;
if ( n >= firstIndex ) {
System.out.printf("VanEck[%d] = %d%n", n, vanEck);
}
}
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
| import java.util.HashMap;
import java.util.Map;
public class VanEckSequence {
public static void main(String[] args) {
System.out.println("First 10 terms of Van Eck's sequence:");
vanEck(1, 10);
System.out.println("");
System.out.println("Terms 991 to 1000 of Van Eck's sequence:");
vanEck(991, 1000);
}
private static void vanEck(int firstIndex, int lastIndex) {
Map<Integer,Integer> vanEckMap = new HashMap<>();
int last = 0;
if ( firstIndex == 1 ) {
System.out.printf("VanEck[%d] = %d%n", 1, 0);
}
for ( int n = 2 ; n <= lastIndex ; n++ ) {
int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0;
vanEckMap.put(last, n);
last = vanEck;
if ( n >= firstIndex ) {
System.out.printf("VanEck[%d] = %d%n", n, vanEck);
}
}
}
}
|
Translate the given Java code snippet into PHP without altering its behavior. | module BitwiseOps
{
@Inject Console console;
void run()
{
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])
{
static String hex(Int64 n)
{
return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
}
console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
| {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
| {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
| {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
| NOT {hex(n1)} = {hex(~n1)}
| left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
| right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
| right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
| left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
| right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
| leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
| rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
| leading zero count of {hex(n1)} = {n1.leadingZeroCount}
| trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
| bit count (aka "population") of {hex(n1)} = {n1.bitCount}
| reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
| reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
|
);
}
}
}
| function bitwise($a, $b)
{
function zerofill($a,$b) {
if($a>=0) return $a>>$b;
if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens
return ((~$a)>>$b)^(0x7fffffff>>($b-1));
echo '$a AND $b: ' . $a & $b . '\n';
echo '$a OR $b: ' . $a | $b . '\n';
echo '$a XOR $b: ' . $a ^ $b . '\n';
echo 'NOT $a: ' . ~$a . '\n';
echo '$a << $b: ' . $a << $b . '\n'; // left shift
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}
|
Ensure the translated PHP code behaves exactly like the original Java snippet. | module BitwiseOps
{
@Inject Console console;
void run()
{
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])
{
static String hex(Int64 n)
{
return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
}
console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
| {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
| {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
| {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
| NOT {hex(n1)} = {hex(~n1)}
| left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
| right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
| right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
| left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
| right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
| leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
| rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
| leading zero count of {hex(n1)} = {n1.leadingZeroCount}
| trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
| bit count (aka "population") of {hex(n1)} = {n1.bitCount}
| reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
| reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
|
);
}
}
}
| function bitwise($a, $b)
{
function zerofill($a,$b) {
if($a>=0) return $a>>$b;
if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens
return ((~$a)>>$b)^(0x7fffffff>>($b-1));
echo '$a AND $b: ' . $a & $b . '\n';
echo '$a OR $b: ' . $a | $b . '\n';
echo '$a XOR $b: ' . $a ^ $b . '\n';
echo 'NOT $a: ' . ~$a . '\n';
echo '$a << $b: ' . $a << $b . '\n'; // left shift
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}
|
Rewrite this program in PHP while keeping its functionality equivalent to the Java version. | import java.io.BufferedReader;
import java.io.FileReader;
public class ReadFileByLines {
private static void processLine(int lineNo, String line) {
}
public static void main(String[] args) {
for (String filename : args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
processLine(++lineNo, line);
}
}
catch (Exception x) {
x.printStackTrace();
}
finally {
if (fr != null) {
try {br.close();} catch (Exception ignoreMe) {}
try {fr.close();} catch (Exception ignoreMe) {}
}
}
}
}
}
| <?php
$file = fopen(__FILE__, 'r'); // read current file
while ($line = fgets($file)) {
$line = rtrim($line); // removes linebreaks and spaces at end
echo strrev($line) . "\n"; // reverse line and upload it
}
|
Convert this Java snippet to PHP and keep its semantics consistent. | import java.io.BufferedReader;
import java.io.FileReader;
public class ReadFileByLines {
private static void processLine(int lineNo, String line) {
}
public static void main(String[] args) {
for (String filename : args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
processLine(++lineNo, line);
}
}
catch (Exception x) {
x.printStackTrace();
}
finally {
if (fr != null) {
try {br.close();} catch (Exception ignoreMe) {}
try {fr.close();} catch (Exception ignoreMe) {}
}
}
}
}
}
| <?php
$file = fopen(__FILE__, 'r'); // read current file
while ($line = fgets($file)) {
$line = rtrim($line); // removes linebreaks and spaces at end
echo strrev($line) . "\n"; // reverse line and upload it
}
|
Change the programming language of this snippet from Java to PHP without modifying what it does. | public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase);
}
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);
}
| base_convert("26", 10, 16); // returns "1a"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.