Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite the snippet below in Java so it works the same as the original Python code. |
from itertools import chain, count, islice
from operator import itemgetter
from math import gcd
from matplotlib import pyplot
def yellowstone():
def relativelyPrime(a):
return lambda b: 1 == gcd(a, b)
def nextWindow(triple):
p2, p1, rest = triple
[rp2, rp1] = map(relativelyPrime, [p2, p1])
def match(xxs):
x, xs = uncons(xxs)['Just']
return (x, xs) if rp1(x) and not rp2(x) else (
second(cons(x))(
match(xs)
)
)
n, residue = match(rest)
return (p1, n, residue)
return chain(
range(1, 3),
map(
itemgetter(1),
iterate(nextWindow)(
(2, 3, count(4))
)
)
)
def main():
print(showList(
take(30)(yellowstone())
))
pyplot.plot(
take(100)(yellowstone())
)
pyplot.xlabel(main.__doc__)
pyplot.show()
def Just(x):
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
def Nothing():
return {'type': 'Maybe', 'Nothing': True}
def cons(x):
return lambda xs: [x] + xs if (
isinstance(xs, list)
) else x + xs if (
isinstance(xs, str)
) else chain([x], xs)
def iterate(f):
def go(x):
v = x
while True:
yield v
v = f(v)
return go
def second(f):
return lambda xy: (xy[0], f(xy[1]))
def showList(xs):
return '[' + ','.join(repr(x) for x in xs) + ']'
def take(n):
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
def uncons(xs):
if isinstance(xs, list):
return Just((xs[0], xs[1:])) if xs else Nothing()
else:
nxt = take(1)(xs)
return Just((nxt[0], xs)) if nxt else Nothing()
if __name__ == '__main__':
main()
| import java.util.ArrayList;
import java.util.List;
public class YellowstoneSequence {
public static void main(String[] args) {
System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30));
}
private static List<Integer> yellowstoneSequence(int sequenceCount) {
List<Integer> yellowstoneList = new ArrayList<Integer>();
yellowstoneList.add(1);
yellowstoneList.add(2);
yellowstoneList.add(3);
int num = 4;
List<Integer> notYellowstoneList = new ArrayList<Integer>();
int yellowSize = 3;
while ( yellowSize < sequenceCount ) {
int found = -1;
for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {
int test = notYellowstoneList.get(index);
if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {
found = index;
break;
}
}
if ( found >= 0 ) {
yellowstoneList.add(notYellowstoneList.remove(found));
yellowSize++;
}
else {
while ( true ) {
if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {
yellowstoneList.add(num);
yellowSize++;
num++;
break;
}
notYellowstoneList.add(num);
num++;
}
}
}
return yellowstoneList;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def cut_it(h, w):
dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
if h % 2: h, w = w, h
if h % 2: return 0
if w == 1: return 1
count = 0
next = [w + 1, -w - 1, -1, 1]
blen = (h + 1) * (w + 1) - 1
grid = [False] * (blen + 1)
def walk(y, x, count):
if not y or y == h or not x or x == w:
return count + 1
t = y * (w + 1) + x
grid[t] = grid[blen - t] = True
if not grid[t + next[0]]:
count = walk(y + dirs[0][0], x + dirs[0][1], count)
if not grid[t + next[1]]:
count = walk(y + dirs[1][0], x + dirs[1][1], count)
if not grid[t + next[2]]:
count = walk(y + dirs[2][0], x + dirs[2][1], count)
if not grid[t + next[3]]:
count = walk(y + dirs[3][0], x + dirs[3][1], count)
grid[t] = grid[blen - t] = False
return count
t = h // 2 * (w + 1) + w // 2
if w % 2:
grid[t] = grid[t + 1] = True
count = walk(h // 2, w // 2 - 1, count)
res = count
count = 0
count = walk(h // 2 - 1, w // 2, count)
return res + count * 2
else:
grid[t] = True
count = walk(h // 2, w // 2 - 1, count)
if h == w:
return count * 2
count = walk(h // 2 - 1, w // 2, count)
return count
def main():
for w in xrange(1, 10):
for h in xrange(1, w + 1):
if not((w * h) % 2):
print "%d x %d: %d" % (w, h, cut_it(w, h))
main()
| import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def cut_it(h, w):
dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
if h % 2: h, w = w, h
if h % 2: return 0
if w == 1: return 1
count = 0
next = [w + 1, -w - 1, -1, 1]
blen = (h + 1) * (w + 1) - 1
grid = [False] * (blen + 1)
def walk(y, x, count):
if not y or y == h or not x or x == w:
return count + 1
t = y * (w + 1) + x
grid[t] = grid[blen - t] = True
if not grid[t + next[0]]:
count = walk(y + dirs[0][0], x + dirs[0][1], count)
if not grid[t + next[1]]:
count = walk(y + dirs[1][0], x + dirs[1][1], count)
if not grid[t + next[2]]:
count = walk(y + dirs[2][0], x + dirs[2][1], count)
if not grid[t + next[3]]:
count = walk(y + dirs[3][0], x + dirs[3][1], count)
grid[t] = grid[blen - t] = False
return count
t = h // 2 * (w + 1) + w // 2
if w % 2:
grid[t] = grid[t + 1] = True
count = walk(h // 2, w // 2 - 1, count)
res = count
count = 0
count = walk(h // 2 - 1, w // 2, count)
return res + count * 2
else:
grid[t] = True
count = walk(h // 2, w // 2 - 1, count)
if h == w:
return count * 2
count = walk(h // 2 - 1, w // 2, count)
return count
def main():
for w in xrange(1, 10):
for h in xrange(1, w + 1):
if not((w * h) % 2):
print "%d x %d: %d" % (w, h, cut_it(w, h))
main()
| import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
}
|
Port the provided Python code into Java while preserving the original functionality. | def mertens(count):
m = [None, 1]
for n in range(2, count+1):
m.append(1)
for k in range(2, n+1):
m[n] -= m[n//k]
return m
ms = mertens(1000)
print("The first 99 Mertens numbers are:")
print(" ", end=' ')
col = 1
for n in ms[1:100]:
print("{:2d}".format(n), end=' ')
col += 1
if col == 10:
print()
col = 0
zeroes = sum(x==0 for x in ms)
crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))
print("M(N) equals zero {} times.".format(zeroes))
print("M(N) crosses zero {} times.".format(crosses))
| public class MertensFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the merten function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", mertenFunction(n));
if ( (n+1) % 20 == 0 ) {
System.out.printf("%n");
}
}
for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {
int zeroCount = 0;
int zeroCrossingCount = 0;
int positiveCount = 0;
int negativeCount = 0;
int mSum = 0;
int mMin = Integer.MAX_VALUE;
int mMinIndex = 0;
int mMax = Integer.MIN_VALUE;
int mMaxIndex = 0;
int nMax = (int) Math.pow(10, exponent);
for ( int n = 1 ; n <= nMax ; n++ ) {
int m = mertenFunction(n);
mSum += m;
if ( m < mMin ) {
mMin = m;
mMinIndex = n;
}
if ( m > mMax ) {
mMax = m;
mMaxIndex = n;
}
if ( m > 0 ) {
positiveCount++;
}
if ( m < 0 ) {
negativeCount++;
}
if ( m == 0 ) {
zeroCount++;
}
if ( m == 0 && mertenFunction(n - 1) != 0 ) {
zeroCrossingCount++;
}
}
System.out.printf("%nFor M(x) with x from 1 to %,d%n", nMax);
System.out.printf("The maximum of M(x) is M(%,d) = %,d.%n", mMaxIndex, mMax);
System.out.printf("The minimum of M(x) is M(%,d) = %,d.%n", mMinIndex, mMin);
System.out.printf("The sum of M(x) is %,d.%n", mSum);
System.out.printf("The count of positive M(x) is %,d, count of negative M(x) is %,d.%n", positiveCount, negativeCount);
System.out.printf("M(x) has %,d zeroes in the interval.%n", zeroCount);
System.out.printf("M(x) has %,d crossings in the interval.%n", zeroCrossingCount);
}
}
private static int MU_MAX = 100_000_000;
private static int[] MU = null;
private static int[] MERTEN = null;
private static int mertenFunction(int n) {
if ( MERTEN != null ) {
return MERTEN[n];
}
MU = new int[MU_MAX+1];
MERTEN = new int[MU_MAX+1];
MERTEN[1] = 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;
}
}
}
int sum = 1;
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;
}
sum += MU[i];
MERTEN[i] = sum;
}
return MERTEN[n];
}
}
|
Generate an equivalent Java version of this Python code. | def _insort_right(a, x, q):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo+hi)//2
q += 1
less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y'
if less: hi = mid
else: lo = mid+1
a.insert(lo, x)
return q
def order(items):
ordered, q = [], 0
for item in items:
q = _insort_right(ordered, item, q)
return ordered, q
if __name__ == '__main__':
items = 'violet red green indigo blue yellow orange'.split()
ans, questions = order(items)
print('\n' + ' '.join(ans))
| import java.util.*;
public class SortComp1 {
public static void main(String[] args) {
List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
List<String> sortedItems = new ArrayList<>();
Comparator<String> interactiveCompare = new Comparator<String>() {
int count = 0;
Scanner s = new Scanner(System.in);
public int compare(String s1, String s2) {
System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2);
return s.nextInt();
}
};
for (String item : items) {
System.out.printf("Inserting '%s' into %s\n", item, sortedItems);
int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);
if (spotToInsert < 0) spotToInsert = ~spotToInsert;
sortedItems.add(spotToInsert, item);
}
System.out.println(sortedItems);
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
def power_of_threes():
return (3**k for k in count(0))
def heads(s):
for a in s: yield int(str(a)[0])
def show_dist(title, s):
c = Counter(s)
size = sum(c.values())
res = [c[d]/size for d in range(1,10)]
print("\n%s Benfords deviation" % title)
for r, e in zip(res, expected):
print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.))
def rand1000():
while True: yield randint(1,9999)
if __name__ == '__main__':
show_dist("fibbed", islice(heads(fib()), 1000))
show_dist("threes", islice(heads(power_of_threes()), 1000))
show_dist("random", islice(heads(rand1000()), 10000))
| import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
}
|
Generate an equivalent Java version of this Python code. | from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
def power_of_threes():
return (3**k for k in count(0))
def heads(s):
for a in s: yield int(str(a)[0])
def show_dist(title, s):
c = Counter(s)
size = sum(c.values())
res = [c[d]/size for d in range(1,10)]
print("\n%s Benfords deviation" % title)
for r, e in zip(res, expected):
print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.))
def rand1000():
while True: yield randint(1,9999)
if __name__ == '__main__':
show_dist("fibbed", islice(heads(fib()), 1000))
show_dist("threes", islice(heads(power_of_threes()), 1000))
show_dist("random", islice(heads(rand1000()), 10000))
| import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); off(0.5)
def bongs(m):
for i in range(m):
print(bellchar, end=' ')
bong()
if i % 2:
print(' ', end='')
off(0.5)
print('')
scheds = sched.scheduler(time.time, time.sleep)
def ships_bell(now=None):
def adjust_to_half_hour(atime):
atime[4] = (atime[4] // 30) * 30
atime[5] = 0
return atime
debug = now is not None
rightnow = time.gmtime()
if not debug:
now = adjust_to_half_hour( list(rightnow) )
then = now[::]
then[4] += 30
hr, mn = now[3:5]
watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)
b += 1
bells = '%i bell%s' % (b, 's' if b > 1 else ' ')
if debug:
print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
else:
print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
bongs(b)
if not debug:
scheds.enterabs(calendar.timegm(then), 0, ships_bell)
scheds.run()
def dbg_tester():
for h in range(24):
for m in (0, 30):
if (h,m) == (24,30): break
ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
if __name__ == '__main__':
ships_bell()
| import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000));
while (next < time) {
next += 30 * 60 * 1000;
numBells = 1 + (numBells % 8);
}
while (true) {
long wait = 100L;
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
return;
}
}
}
}
|
Write the same code in Java as shown below in Python. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); off(0.5)
def bongs(m):
for i in range(m):
print(bellchar, end=' ')
bong()
if i % 2:
print(' ', end='')
off(0.5)
print('')
scheds = sched.scheduler(time.time, time.sleep)
def ships_bell(now=None):
def adjust_to_half_hour(atime):
atime[4] = (atime[4] // 30) * 30
atime[5] = 0
return atime
debug = now is not None
rightnow = time.gmtime()
if not debug:
now = adjust_to_half_hour( list(rightnow) )
then = now[::]
then[4] += 30
hr, mn = now[3:5]
watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)
b += 1
bells = '%i bell%s' % (b, 's' if b > 1 else ' ')
if debug:
print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
else:
print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
bongs(b)
if not debug:
scheds.enterabs(calendar.timegm(then), 0, ships_bell)
scheds.run()
def dbg_tester():
for h in range(24):
for m in (0, 30):
if (h,m) == (24,30): break
ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
if __name__ == '__main__':
ships_bell()
| import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000));
while (next < time) {
next += 30 * 60 * 1000;
numBells = 1 + (numBells % 8);
}
while (true) {
long wait = 100L;
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
return;
}
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| public static long fib(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not be a negative number");
return new Object() {
private long fibInner(int n) {
return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));
}
}.fibInner(n);
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
|
Convert this Python block to Java, preserving its control flow and logic. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from primesieve import primes
from math import isqrt
from functools import cache
p = primes(isqrt(1_000_000_000))
@cache
def phi(x, a):
res = 0
while True:
if not a or not x:
return x + res
a -= 1
res -= phi(x//p[a], a)
def legpi(n):
if n < 2: return 0
a = legpi(isqrt(n))
return phi(n, a) + a - 1
for e in range(10):
print(f'10^{e}', legpi(10**e))
| import java.util.*;
public class LegendrePrimeCounter {
public static void main(String[] args) {
LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
System.out.printf("10^%d\t%d\n", i, counter.primeCount((n)));
}
private List<Integer> primes;
public LegendrePrimeCounter(int limit) {
primes = generatePrimes((int)Math.sqrt((double)limit));
}
public int primeCount(int n) {
if (n < 2)
return 0;
int a = primeCount((int)Math.sqrt((double)n));
return phi(n, a) + a - 1;
}
private int phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes.get(a - 1);
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
private static List<Integer> generatePrimes(int limit) {
boolean[] sieve = new boolean[limit >> 1];
Arrays.fill(sieve, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
List<Integer> primes = new ArrayList<>();
if (limit > 2)
primes.add(2);
for (int i = 1; i < sieve.length; ++i) {
if (sieve[i])
primes.add((i << 1) + 1);
}
return primes;
}
}
|
Port the provided Python code into Java while preserving the original functionality. |
def query(buffer_length):
message = b'Here am I'
L = len(message)
return message[0:L*(L <= buffer_length)]
|
public class Query {
public static boolean call(byte[] data, int[] length)
throws java.io.UnsupportedEncodingException
{
String message = "Here am I";
byte[] mb = message.getBytes("utf-8");
if (length[0] < mb.length)
return false;
length[0] = mb.length;
System.arraycopy(mb, 0, data, 0, mb.length);
return true;
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import fileinput
def longer(a, b):
try:
b[len(a)-1]
return False
except:
return True
longest, lines = '', ''
for x in fileinput.input():
if longer(x, longest):
lines, longest = x, x
elif not longer(longest, x):
lines += x
print(lines, end='')
| import java.io.File;
import java.util.Scanner;
public class LongestStringChallenge {
public static void main(String[] args) throws Exception {
String lines = "", longest = "";
try (Scanner sc = new Scanner(new File("lines.txt"))) {
while(sc.hasNext()) {
String line = sc.nextLine();
if (longer(longest, line))
lines = longest = line;
else if (!longer(line, longest))
lines = lines.concat("\n").concat(line);
}
}
System.out.println(lines);
}
static boolean longer(String a, String b) {
try {
String dummy = a.substring(b.length());
} catch (StringIndexOutOfBoundsException e) {
return true;
}
return false;
}
}
|
Generate an equivalent Java version of this Python code. | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction;
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) {
tape = input;
}
public void initializeTape(String input) {
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() {
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) {
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol);
tsp.state = trans.to.state;
if (trans.direction == -1) {
if (!head.hasPrevious()) {
head.add(blankSymbol);
}
tsp.tapeSymbol = head.previous();
} else if (trans.direction == 1) {
head.next();
if (!head.hasNext()) {
head.add(blankSymbol);
head.previous();
}
tsp.tapeSymbol = head.next();
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction;
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) {
tape = input;
}
public void initializeTape(String input) {
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() {
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) {
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol);
tsp.state = trans.to.state;
if (trans.direction == -1) {
if (!head.hasPrevious()) {
head.add(blankSymbol);
}
tsp.tapeSymbol = head.previous();
} else if (trans.direction == 1) {
head.next();
if (!head.hasNext()) {
head.add(blankSymbol);
head.previous();
}
tsp.tapeSymbol = head.next();
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
}
|
Change the following Python code into Java without altering its purpose. | import os
for directory in ['/', './']:
open(directory + 'output.txt', 'w').close()
os.mkdir(directory + 'docs')
| import java.io.*;
public class CreateFileTest {
public static void main(String args[]) {
try {
new File("output.txt").createNewFile();
new File(File.separator + "output.txt").createNewFile();
new File("docs").mkdir();
new File(File.separator + "docs").mkdir();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from itertools import count, islice
def primes(_cache=[2, 3]):
yield from _cache
for n in count(_cache[-1]+2, 2):
if isprime(n):
_cache.append(n)
yield n
def isprime(n, _seen={0: False, 1: False}):
def _isprime(n):
for p in primes():
if p*p > n:
return True
if n%p == 0:
return False
if n not in _seen:
_seen[n] = _isprime(n)
return _seen[n]
def unprime():
for a in count(1):
d = 1
while d <= a:
base = (a//(d*10))*(d*10) + (a%d)
if any(isprime(y) for y in range(base, base + d*10, d)):
break
d *= 10
else:
yield a
print('First 35:')
print(' '.join(str(i) for i in islice(unprime(), 35)))
print('\nThe 600-th:')
print(list(islice(unprime(), 599, 600))[0])
print()
first, need = [False]*10, 10
for p in unprime():
i = p%10
if first[i]: continue
first[i] = p
need -= 1
if not need:
break
for i,v in enumerate(first):
print(f'{i} ending: {v}')
| public class UnprimeableNumbers {
private static int MAX = 10_000_000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 35 unprimeable numbers:");
displayUnprimeableNumbers(35);
int n = 600;
System.out.printf("%nThe %dth unprimeable number = %,d%n%n", n, nthUnprimeableNumber(n));
int[] lowest = genLowest();
System.out.println("Least unprimeable number that ends in:");
for ( int i = 0 ; i <= 9 ; i++ ) {
System.out.printf(" %d is %,d%n", i, lowest[i]);
}
}
private static int[] genLowest() {
int[] lowest = new int[10];
int count = 0;
int test = 1;
while ( count < 10 ) {
test++;
if ( unPrimable(test) && lowest[test % 10] == 0 ) {
lowest[test % 10] = test;
count++;
}
}
return lowest;
}
private static int nthUnprimeableNumber(int maxCount) {
int test = 1;
int count = 0;
int result = 0;
while ( count < maxCount ) {
test++;
if ( unPrimable(test) ) {
count++;
result = test;
}
}
return result;
}
private static void displayUnprimeableNumbers(int maxCount) {
int test = 1;
int count = 0;
while ( count < maxCount ) {
test++;
if ( unPrimable(test) ) {
count++;
System.out.printf("%d ", test);
}
}
System.out.println();
}
private static boolean unPrimable(int test) {
if ( primes[test] ) {
return false;
}
String s = test + "";
for ( int i = 0 ; i < s.length() ; i++ ) {
for ( int j = 0 ; j <= 9 ; j++ ) {
if ( primes[Integer.parseInt(replace(s, i, j))] ) {
return false;
}
}
}
return true;
}
private static String replace(String str, int position, int value) {
char[] sChar = str.toCharArray();
sChar[position] = (char) value;
return str.substring(0, position) + value + str.substring(position + 1);
}
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;
}
}
}
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. |
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
n = cl.get(k, 0)
cl[k] = n+v
return cl
def constrain(nsum, vn ):
nn = {}
nn.update(vn)
n = nn.get('1', 0)
nn['1'] = n - nsum
return nn
def makeMatrix( constraints ):
vmap = set()
for c in constraints:
vmap.update( c.keys())
vmap.remove('1')
nvars = len(vmap)
vmap = sorted(vmap)
mtx = []
for c in constraints:
row = []
for vv in vmap:
row.append(float(c.get(vv, 0)))
row.append(-float(c.get('1',0)))
mtx.append(row)
if len(constraints) == nvars:
print 'System appears solvable'
elif len(constraints) < nvars:
print 'System is not solvable - needs more constraints.'
return mtx, vmap
def SolvePyramid( vl, cnstr ):
vl.reverse()
constraints = [cnstr]
lvls = len(vl)
for lvln in range(1,lvls):
lvd = vl[lvln]
for k in range(lvls - lvln):
sn = lvd[k]
ll = vl[lvln-1]
vn = combine(ll[k], ll[k+1])
if sn is None:
lvd[k] = vn
else:
constraints.append(constrain( sn, vn ))
print 'Constraint Equations:'
for cstr in constraints:
fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
print ' + '.join(fset), ' = 0'
mtx,vmap = makeMatrix(constraints)
MtxSolve(mtx)
d = len(vmap)
for j in range(d):
print vmap[j],'=', mtx[j][d]
def MtxSolve(mtx):
mDim = len(mtx)
for j in range(mDim):
rw0= mtx[j]
f = 1.0/rw0[j]
for k in range(j, mDim+1):
rw0[k] *= f
for l in range(1+j,mDim):
rwl = mtx[l]
f = -rwl[j]
for k in range(j, mDim+1):
rwl[k] += f * rw0[k]
for j1 in range(1,mDim):
j = mDim - j1
rw0= mtx[j]
for l in range(0, j):
rwl = mtx[l]
f = -rwl[j]
rwl[j] += f * rw0[j]
rwl[mDim] += f * rw0[mDim]
return mtx
p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint)
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalsTrianglePuzzle {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d),
Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),
Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),
Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));
List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);
List<Double> solution = cramersRule(mat, b);
System.out.println("Solution = " + cramersRule(mat, b));
System.out.printf("X = %.2f%n", solution.get(8));
System.out.printf("Y = %.2f%n", solution.get(9));
System.out.printf("Z = %.2f%n", solution.get(10));
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant();
List<Double> result = new ArrayList<>();
for ( int i = 0 ; i < b.size() ; i++ ) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator);
}
return result;
}
private static class Matrix {
private List<List<Double>> matrix;
@Override
public String toString() {
return matrix.toString();
}
@SafeVarargs
public Matrix(List<Double> ... lists) {
matrix = new ArrayList<>();
for ( List<Double> list : lists) {
matrix.add(list);
}
}
public Matrix(List<List<Double>> mat) {
matrix = mat;
}
public double determinant() {
if ( matrix.size() == 1 ) {
return get(0, 0);
}
if ( matrix.size() == 2 ) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);
}
double sum = 0;
double sign = 1;
for ( int i = 0 ; i < matrix.size() ; i++ ) {
sum += sign * get(0, i) * coFactor(0, i).determinant();
sign *= -1;
}
return sum;
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>();
for ( int i = 0 ; i < matrix.size() ; i++ ) {
if ( i == row ) {
continue;
}
List<Double> list = new ArrayList<>();
for ( int j = 0 ; j < matrix.size() ; j++ ) {
if ( j == col ) {
continue;
}
list.add(get(i, j));
}
mat.add(list);
}
return new Matrix(mat);
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>();
for ( int row = 0 ; row < matrix.size() ; row++ ) {
List<Double> list = new ArrayList<>();
for ( int col = 0 ; col < matrix.size() ; col++ ) {
double value = get(row, col);
if ( col == column ) {
value = b.get(row);
}
list.add(value);
}
mat.add(list);
}
return new Matrix(mat);
}
private double get(int row, int col) {
return matrix.get(row).get(col);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. |
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
n = cl.get(k, 0)
cl[k] = n+v
return cl
def constrain(nsum, vn ):
nn = {}
nn.update(vn)
n = nn.get('1', 0)
nn['1'] = n - nsum
return nn
def makeMatrix( constraints ):
vmap = set()
for c in constraints:
vmap.update( c.keys())
vmap.remove('1')
nvars = len(vmap)
vmap = sorted(vmap)
mtx = []
for c in constraints:
row = []
for vv in vmap:
row.append(float(c.get(vv, 0)))
row.append(-float(c.get('1',0)))
mtx.append(row)
if len(constraints) == nvars:
print 'System appears solvable'
elif len(constraints) < nvars:
print 'System is not solvable - needs more constraints.'
return mtx, vmap
def SolvePyramid( vl, cnstr ):
vl.reverse()
constraints = [cnstr]
lvls = len(vl)
for lvln in range(1,lvls):
lvd = vl[lvln]
for k in range(lvls - lvln):
sn = lvd[k]
ll = vl[lvln-1]
vn = combine(ll[k], ll[k+1])
if sn is None:
lvd[k] = vn
else:
constraints.append(constrain( sn, vn ))
print 'Constraint Equations:'
for cstr in constraints:
fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
print ' + '.join(fset), ' = 0'
mtx,vmap = makeMatrix(constraints)
MtxSolve(mtx)
d = len(vmap)
for j in range(d):
print vmap[j],'=', mtx[j][d]
def MtxSolve(mtx):
mDim = len(mtx)
for j in range(mDim):
rw0= mtx[j]
f = 1.0/rw0[j]
for k in range(j, mDim+1):
rw0[k] *= f
for l in range(1+j,mDim):
rwl = mtx[l]
f = -rwl[j]
for k in range(j, mDim+1):
rwl[k] += f * rw0[k]
for j1 in range(1,mDim):
j = mDim - j1
rw0= mtx[j]
for l in range(0, j):
rwl = mtx[l]
f = -rwl[j]
rwl[j] += f * rw0[j]
rwl[mDim] += f * rw0[mDim]
return mtx
p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint)
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalsTrianglePuzzle {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d),
Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),
Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),
Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));
List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);
List<Double> solution = cramersRule(mat, b);
System.out.println("Solution = " + cramersRule(mat, b));
System.out.printf("X = %.2f%n", solution.get(8));
System.out.printf("Y = %.2f%n", solution.get(9));
System.out.printf("Z = %.2f%n", solution.get(10));
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant();
List<Double> result = new ArrayList<>();
for ( int i = 0 ; i < b.size() ; i++ ) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator);
}
return result;
}
private static class Matrix {
private List<List<Double>> matrix;
@Override
public String toString() {
return matrix.toString();
}
@SafeVarargs
public Matrix(List<Double> ... lists) {
matrix = new ArrayList<>();
for ( List<Double> list : lists) {
matrix.add(list);
}
}
public Matrix(List<List<Double>> mat) {
matrix = mat;
}
public double determinant() {
if ( matrix.size() == 1 ) {
return get(0, 0);
}
if ( matrix.size() == 2 ) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);
}
double sum = 0;
double sign = 1;
for ( int i = 0 ; i < matrix.size() ; i++ ) {
sum += sign * get(0, i) * coFactor(0, i).determinant();
sign *= -1;
}
return sum;
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>();
for ( int i = 0 ; i < matrix.size() ; i++ ) {
if ( i == row ) {
continue;
}
List<Double> list = new ArrayList<>();
for ( int j = 0 ; j < matrix.size() ; j++ ) {
if ( j == col ) {
continue;
}
list.add(get(i, j));
}
mat.add(list);
}
return new Matrix(mat);
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>();
for ( int row = 0 ; row < matrix.size() ; row++ ) {
List<Double> list = new ArrayList<>();
for ( int col = 0 ; col < matrix.size() ; col++ ) {
double value = get(row, col);
if ( col == column ) {
value = b.get(row);
}
list.add(value);
}
mat.add(list);
}
return new Matrix(mat);
}
private double get(int row, int col) {
return matrix.get(row).get(col);
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. |
from sympy import isprime
def primality_pretest(k):
if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):
return (k <= 23)
return True
def is_chernick(n, m):
t = 9 * m
if not primality_pretest(6 * m + 1):
return False
if not primality_pretest(12 * m + 1):
return False
for i in range(1,n-1):
if not primality_pretest((t << i) + 1):
return False
if not isprime(6 * m + 1):
return False
if not isprime(12 * m + 1):
return False
for i in range(1,n - 1):
if not isprime((t << i) + 1):
return False
return True
for n in range(3,10):
if n > 4:
multiplier = 1 << (n - 4)
else:
multiplier = 1
if n > 5:
multiplier *= 5
k = 1
while True:
m = k * multiplier
if is_chernick(n, m):
print("a("+str(n)+") has m = "+str(m))
break
k += 1
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class ChernicksCarmichaelNumbers {
public static void main(String[] args) {
for ( long n = 3 ; n < 10 ; n++ ) {
long m = 0;
boolean foundComposite = true;
List<Long> factors = null;
while ( foundComposite ) {
m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);
factors = U(n, m);
foundComposite = false;
for ( long factor : factors ) {
if ( ! isPrime(factor) ) {
foundComposite = true;
break;
}
}
}
System.out.printf("U(%d, %d) = %s = %s %n", n, m, display(factors), multiply(factors));
}
}
private static String display(List<Long> factors) {
return factors.toString().replace("[", "").replace("]", "").replaceAll(", ", " * ");
}
private static BigInteger multiply(List<Long> factors) {
BigInteger result = BigInteger.ONE;
for ( long factor : factors ) {
result = result.multiply(BigInteger.valueOf(factor));
}
return result;
}
private static List<Long> U(long n, long m) {
List<Long> factors = new ArrayList<>();
factors.add(6*m + 1);
factors.add(12*m + 1);
for ( int i = 1 ; i <= n-2 ; i++ ) {
factors.add(((long)Math.pow(2, i)) * 9 * m + 1);
}
return factors;
}
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
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;
}
}
}
}
public static final boolean isPrime(long testValue) {
if ( testValue == 2 ) return true;
if ( testValue % 2 == 0 ) return false;
if ( testValue <= MAX ) return isPrimeTrivial(testValue);
long d = testValue-1;
int s = 0;
while ( d % 2 == 0 ) {
s += 1;
d /= 2;
}
if ( testValue < 1373565L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 4759123141L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(7, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 10000000000000000L ) {
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
if ( ! aSrp(24251, s, d, testValue) ) {
return false;
}
return true;
}
if ( ! aSrp(37, s, d, testValue) ) {
return false;
}
if ( ! aSrp(47, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
if ( ! aSrp(73, s, d, testValue) ) {
return false;
}
if ( ! aSrp(83, s, d, testValue) ) {
return false;
}
return true;
}
private static final boolean aSrp(int a, int s, long d, long n) {
long modPow = modPow(a, d, n);
if ( modPow == 1 ) {
return true;
}
int twoExpR = 1;
for ( int r = 0 ; r < s ; r++ ) {
if ( modPow(modPow, twoExpR, n) == n-1 ) {
return true;
}
twoExpR *= 2;
}
return false;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long modPow(long base, long exponent, long modulus) {
long result = 1;
while ( exponent > 0 ) {
if ( exponent % 2 == 1 ) {
if ( result > SQRT || base > SQRT ) {
result = multiply(result, base, modulus);
}
else {
result = (result * base) % modulus;
}
}
exponent >>= 1;
if ( base > SQRT ) {
base = multiply(base, base, modulus);
}
else {
base = (base * base) % modulus;
}
}
return result;
}
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
}
|
Port the provided Python code into Java while preserving the original functionality. |
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
| import java.util.Objects;
public class FindTriangle {
private static final double EPS = 0.001;
private static final double EPS_SQUARE = EPS * EPS;
public static class Point {
private final double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return String.format("(%f, %f)", x, y);
}
}
public static class Triangle {
private final Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = Objects.requireNonNull(p1);
this.p2 = Objects.requireNonNull(p2);
this.p3 = Objects.requireNonNull(p3);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public Point getP3() {
return p3;
}
private boolean pointInTriangleBoundingBox(Point p) {
var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;
var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;
var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;
var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;
return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());
}
private static double side(Point p1, Point p2, Point p) {
return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());
}
private boolean nativePointInTriangle(Point p) {
boolean checkSide1 = side(p1, p2, p) >= 0;
boolean checkSide2 = side(p2, p3, p) >= 0;
boolean checkSide3 = side(p3, p1, p) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {
double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());
double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;
if (dotProduct < 0) {
return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());
}
if (dotProduct <= 1) {
double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
}
return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());
}
private boolean accuratePointInTriangle(Point p) {
if (!pointInTriangleBoundingBox(p)) {
return false;
}
if (nativePointInTriangle(p)) {
return true;
}
if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
return true;
}
return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;
}
public boolean within(Point p) {
Objects.requireNonNull(p);
return accuratePointInTriangle(p);
}
@Override
public String toString() {
return String.format("Triangle[%s, %s, %s]", p1, p2, p3);
}
}
private static void test(Triangle t, Point p) {
System.out.println(t);
System.out.printf("Point %s is within triangle? %s\n", p, t.within(p));
}
public static void main(String[] args) {
var p1 = new Point(1.5, 2.4);
var p2 = new Point(5.1, -3.1);
var p3 = new Point(-3.8, 1.2);
var tri = new Triangle(p1, p2, p3);
test(tri, new Point(0, 0));
test(tri, new Point(0, 1));
test(tri, new Point(3, 1));
System.out.println();
p1 = new Point(1.0 / 10, 1.0 / 9);
p2 = new Point(100.0 / 8, 100.0 / 3);
p3 = new Point(100.0 / 4, 100.0 / 9);
tri = new Triangle(p1, p2, p3);
var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));
test(tri, pt);
System.out.println();
p3 = new Point(-100.0 / 8, 100.0 / 6);
tri = new Triangle(p1, p2, p3);
test(tri, pt);
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. |
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
| import java.util.Objects;
public class FindTriangle {
private static final double EPS = 0.001;
private static final double EPS_SQUARE = EPS * EPS;
public static class Point {
private final double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return String.format("(%f, %f)", x, y);
}
}
public static class Triangle {
private final Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = Objects.requireNonNull(p1);
this.p2 = Objects.requireNonNull(p2);
this.p3 = Objects.requireNonNull(p3);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public Point getP3() {
return p3;
}
private boolean pointInTriangleBoundingBox(Point p) {
var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;
var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;
var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;
var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;
return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());
}
private static double side(Point p1, Point p2, Point p) {
return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());
}
private boolean nativePointInTriangle(Point p) {
boolean checkSide1 = side(p1, p2, p) >= 0;
boolean checkSide2 = side(p2, p3, p) >= 0;
boolean checkSide3 = side(p3, p1, p) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {
double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());
double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;
if (dotProduct < 0) {
return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());
}
if (dotProduct <= 1) {
double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
}
return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());
}
private boolean accuratePointInTriangle(Point p) {
if (!pointInTriangleBoundingBox(p)) {
return false;
}
if (nativePointInTriangle(p)) {
return true;
}
if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
return true;
}
return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;
}
public boolean within(Point p) {
Objects.requireNonNull(p);
return accuratePointInTriangle(p);
}
@Override
public String toString() {
return String.format("Triangle[%s, %s, %s]", p1, p2, p3);
}
}
private static void test(Triangle t, Point p) {
System.out.println(t);
System.out.printf("Point %s is within triangle? %s\n", p, t.within(p));
}
public static void main(String[] args) {
var p1 = new Point(1.5, 2.4);
var p2 = new Point(5.1, -3.1);
var p3 = new Point(-3.8, 1.2);
var tri = new Triangle(p1, p2, p3);
test(tri, new Point(0, 0));
test(tri, new Point(0, 1));
test(tri, new Point(3, 1));
System.out.println();
p1 = new Point(1.0 / 10, 1.0 / 9);
p2 = new Point(100.0 / 8, 100.0 / 3);
p3 = new Point(100.0 / 4, 100.0 / 9);
tri = new Triangle(p1, p2, p3);
var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));
test(tri, pt);
System.out.println();
p3 = new Point(-100.0 / 8, 100.0 / 6);
tri = new Triangle(p1, p2, p3);
test(tri, pt);
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print(*map(tau, range(1, 101)))
| public class TauFunction {
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 int limit = 100;
System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%3d", divisorCount(n));
if (n % 20 == 0) {
System.out.println();
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print(*map(tau, range(1, 101)))
| public class TauFunction {
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 int limit = 100;
System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%3d", divisorCount(n));
if (n % 20 == 0) {
System.out.println();
}
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print(*map(tau, range(1, 101)))
| public class TauFunction {
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 int limit = 100;
System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%3d", divisorCount(n));
if (n % 20 == 0) {
System.out.println();
}
}
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import pyprimes
def primorial_prime(_pmax=500):
isprime = pyprimes.isprime
n, primo = 0, 1
for prime in pyprimes.nprimes(_pmax):
n, primo = n+1, primo * prime
if isprime(primo-1) or isprime(primo+1):
yield n
if __name__ == '__main__':
pyprimes.warn_probably = False
for i, n in zip(range(20), primorial_prime()):
print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
| import java.math.BigInteger;
public class PrimorialPrimes {
final static int sieveLimit = 1550_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
int count = 0;
for (int i = 1; i < 1000_000 && count < 20; i++) {
BigInteger b = primorial(i);
if (b.add(BigInteger.ONE).isProbablePrime(1)
|| b.subtract(BigInteger.ONE).isProbablePrime(1)) {
System.out.printf("%d ", i);
count++;
}
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | import pyprimes
def primorial_prime(_pmax=500):
isprime = pyprimes.isprime
n, primo = 0, 1
for prime in pyprimes.nprimes(_pmax):
n, primo = n+1, primo * prime
if isprime(primo-1) or isprime(primo+1):
yield n
if __name__ == '__main__':
pyprimes.warn_probably = False
for i, n in zip(range(20), primorial_prime()):
print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
| import java.math.BigInteger;
public class PrimorialPrimes {
final static int sieveLimit = 1550_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
int count = 0;
for (int i = 1; i < 1000_000 && count < 20; i++) {
BigInteger b = primorial(i);
if (b.add(BigInteger.ONE).isProbablePrime(1)
|| b.subtract(BigInteger.ONE).isProbablePrime(1)) {
System.out.printf("%d ", i);
count++;
}
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | 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}")
if __name__ == '__main__':
print("SEQUENCE:")
sequence =
seq_pp(sequence)
| import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
gene.runSequence();
}
}
public class Sequence {
private final String seq;
public Sequence(String sq) {
this.seq = sq;
}
public void prettyPrint() {
System.out.println("Sequence:");
int i = 0;
for ( ; i < seq.length() - 50 ; i += 50) {
System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
}
System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
}
public void displayCount() {
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0 ; i < seq.length() ; ++i) {
counter.merge(seq.charAt(i), 1, Integer::sum);
}
System.out.println("Base vs. Count:");
counter.forEach(
key, value -> System.out.printf("%5s : %s\n", key, value));
System.out.printf("%5s: %s\n", "SUM", seq.length());
}
public void runSequence() {
this.prettyPrint();
this.displayCount();
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | 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}")
if __name__ == '__main__':
print("SEQUENCE:")
sequence =
seq_pp(sequence)
| import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
gene.runSequence();
}
}
public class Sequence {
private final String seq;
public Sequence(String sq) {
this.seq = sq;
}
public void prettyPrint() {
System.out.println("Sequence:");
int i = 0;
for ( ; i < seq.length() - 50 ; i += 50) {
System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
}
System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
}
public void displayCount() {
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0 ; i < seq.length() ; ++i) {
counter.merge(seq.charAt(i), 1, Integer::sum);
}
System.out.println("Base vs. Count:");
counter.forEach(
key, value -> System.out.printf("%5s : %s\n", key, value));
System.out.printf("%5s: %s\n", "SUM", seq.length());
}
public void runSequence() {
this.prettyPrint();
this.displayCount();
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | import threading
import random
import time
class Philosopher(threading.Thread):
running = True
def __init__(self, xname, forkOnLeft, forkOnRight):
threading.Thread.__init__(self)
self.name = xname
self.forkOnLeft = forkOnLeft
self.forkOnRight = forkOnRight
def run(self):
while(self.running):
time.sleep( random.uniform(3,13))
print '%s is hungry.' % self.name
self.dine()
def dine(self):
fork1, fork2 = self.forkOnLeft, self.forkOnRight
while self.running:
fork1.acquire(True)
locked = fork2.acquire(False)
if locked: break
fork1.release()
print '%s swaps forks' % self.name
fork1, fork2 = fork2, fork1
else:
return
self.dining()
fork2.release()
fork1.release()
def dining(self):
print '%s starts eating '% self.name
time.sleep(random.uniform(1,10))
print '%s finishes eating and leaves to think.' % self.name
def DiningPhilosophers():
forks = [threading.Lock() for n in range(5)]
philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')
philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
for i in range(5)]
random.seed(507129)
Philosopher.running = True
for p in philosophers: p.start()
time.sleep(100)
Philosopher.running = False
print ("Now we're finishing.")
DiningPhilosophers()
| package diningphilosophers;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
enum PhilosopherState { Get, Eat, Pon }
class Fork {
public static final int ON_TABLE = -1;
static int instances = 0;
public int id;
public AtomicInteger holder = new AtomicInteger(ON_TABLE);
Fork() { id = instances++; }
}
class Philosopher implements Runnable {
static final int maxWaitMs = 100;
static AtomicInteger token = new AtomicInteger(0);
static int instances = 0;
static Random rand = new Random();
AtomicBoolean end = new AtomicBoolean(false);
int id;
PhilosopherState state = PhilosopherState.Get;
Fork left;
Fork right;
int timesEaten = 0;
Philosopher() {
id = instances++;
left = Main.forks.get(id);
right = Main.forks.get((id+1)%Main.philosopherCount);
}
void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }
catch (InterruptedException ex) {} }
void waitForFork(Fork fork) {
do {
if (fork.holder.get() == Fork.ON_TABLE) {
fork.holder.set(id);
return;
} else {
sleep();
}
} while (true);
}
public void run() {
do {
if (state == PhilosopherState.Pon) {
state = PhilosopherState.Get;
} else {
if (token.get() == id) {
waitForFork(left);
waitForFork(right);
token.set((id+2)% Main.philosopherCount);
state = PhilosopherState.Eat;
timesEaten++;
sleep();
left.holder.set(Fork.ON_TABLE);
right.holder.set(Fork.ON_TABLE);
state = PhilosopherState.Pon;
sleep();
} else {
sleep();
}
}
} while (!end.get());
}
}
public class Main {
static final int philosopherCount = 5;
static final int runSeconds = 15;
static ArrayList<Fork> forks = new ArrayList<Fork>();
static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();
public static void main(String[] args) {
for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());
for (int i = 0 ; i < philosopherCount ; i++)
philosophers.add(new Philosopher());
for (Philosopher p : philosophers) new Thread(p).start();
long endTime = System.currentTimeMillis() + (runSeconds * 1000);
do {
StringBuilder sb = new StringBuilder("|");
for (Philosopher p : philosophers) {
sb.append(p.state.toString());
sb.append("|");
}
sb.append(" |");
for (Fork f : forks) {
int holder = f.holder.get();
sb.append(holder==-1?" ":String.format("P%02d",holder));
sb.append("|");
}
System.out.println(sb.toString());
try {Thread.sleep(1000);} catch (Exception ex) {}
} while (System.currentTimeMillis() < endTime);
for (Philosopher p : philosophers) p.end.set(true);
for (Philosopher p : philosophers)
System.out.printf("P%02d: ate %,d times, %,d/sec\n",
p.id, p.timesEaten, p.timesEaten/runSeconds);
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_sum == i:
print(i, end=" ")
print("\n")
| public class Factorion {
public static void main(String [] args){
System.out.println("Base 9:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,9);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 10:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,10);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 11:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,11);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 12:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,12);
if(multiplied == i){
System.out.print(i + "\t");
}
}
}
public static int factorialRec(int n){
int result = 1;
return n == 0 ? result : result * n * factorialRec(n-1);
}
public static int operate(String s, int base){
int sum = 0;
String strx = fromDeci(base, Integer.parseInt(s));
for(int i = 0; i < strx.length(); i++){
if(strx.charAt(i) == 'A'){
sum += factorialRec(10);
}else if(strx.charAt(i) == 'B') {
sum += factorialRec(11);
}else if(strx.charAt(i) == 'C') {
sum += factorialRec(12);
}else {
sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
}
}
return sum;
}
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
static String fromDeci(int base, int num){
StringBuilder s = new StringBuilder();
while (num > 0) {
s.append(reVal(num % base));
num /= base;
}
return new String(new StringBuilder(s).reverse());
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_sum == i:
print(i, end=" ")
print("\n")
| public class Factorion {
public static void main(String [] args){
System.out.println("Base 9:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,9);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 10:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,10);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 11:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,11);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 12:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,12);
if(multiplied == i){
System.out.print(i + "\t");
}
}
}
public static int factorialRec(int n){
int result = 1;
return n == 0 ? result : result * n * factorialRec(n-1);
}
public static int operate(String s, int base){
int sum = 0;
String strx = fromDeci(base, Integer.parseInt(s));
for(int i = 0; i < strx.length(); i++){
if(strx.charAt(i) == 'A'){
sum += factorialRec(10);
}else if(strx.charAt(i) == 'B') {
sum += factorialRec(11);
}else if(strx.charAt(i) == 'C') {
sum += factorialRec(12);
}else {
sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
}
}
return sum;
}
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
static String fromDeci(int base, int num){
StringBuilder s = new StringBuilder();
while (num > 0) {
s.append(reVal(num % base));
num /= base;
}
return new String(new StringBuilder(s).reverse());
}
}
|
Write the same code in Java as shown below in Python. | import numpy as np
import scipy.optimize as opt
n0, K = 27, 7_800_000_000
def f(t, r):
return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K))
y = [
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,
2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,
24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,
60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,
76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,
85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,
105824, 109695, 114232, 118610, 125497, 133852, 143227,
151367, 167418, 180096, 194836, 213150, 242364, 271106,
305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054,
1174652,
]
x = np.linspace(0.0, 96, 97)
r, cov = opt.curve_fit(f, x, y, [0.5])
print("The r for the world Covid-19 data is:", r,
", with covariance of", cov)
print("The calculated R0 is then", np.exp(12 * r))
| import java.util.List;
import java.util.function.Function;
public class LogisticCurveFitting {
private static final double K = 7.8e9;
private static final int N0 = 27;
private static final List<Double> ACTUAL = List.of(
27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,
61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,
4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,
31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,
69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,
80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,
95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,
133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,
271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,
656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0
);
private static double f(double r) {
var sq = 0.0;
var len = ACTUAL.size();
for (int i = 0; i < len; i++) {
var eri = Math.exp(r * i);
var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);
var diff = guess - ACTUAL.get(i);
sq += diff * diff;
}
return sq;
}
private static double solve(Function<Double, Double> fn) {
return solve(fn, 0.5, 0.0);
}
private static double solve(Function<Double, Double> fn, double guess, double epsilon) {
double delta;
if (guess != 0.0) {
delta = guess;
} else {
delta = 1.0;
}
var f0 = fn.apply(guess);
var factor = 2.0;
while (delta > epsilon && guess != guess - delta) {
var nf = fn.apply(guess - delta);
if (nf < f0) {
f0 = nf;
guess -= delta;
} else {
nf = fn.apply(guess + delta);
if (nf < f0) {
f0 = nf;
guess += delta;
} else {
factor = 0.5;
}
}
delta *= factor;
}
return guess;
}
public static void main(String[] args) {
var r = solve(LogisticCurveFitting::f);
var r0 = Math.exp(12.0 * r);
System.out.printf("r = %.16f, R0 = %.16f\n", r, r0);
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def merge_list(a, b):
out = []
while len(a) and len(b):
if a[0] < b[0]:
out.append(a.pop(0))
else:
out.append(b.pop(0))
out += a
out += b
return out
def strand(a):
i, s = 0, [a.pop(0)]
while i < len(a):
if a[i] > s[-1]:
s.append(a.pop(i))
else:
i += 1
return s
def strand_sort(a):
out = strand(a)
while len(a):
out = merge_list(out, strand(a))
return out
print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])
| import java.util.Arrays;
import java.util.LinkedList;
public class Strand{
public static <E extends Comparable<? super E>>
LinkedList<E> strandSort(LinkedList<E> list){
if(list.size() <= 1) return list;
LinkedList<E> result = new LinkedList<E>();
while(list.size() > 0){
LinkedList<E> sorted = new LinkedList<E>();
sorted.add(list.removeFirst());
for(Iterator<E> it = list.iterator(); it.hasNext(); ){
E elem = it.next();
if(sorted.peekLast().compareTo(elem) <= 0){
sorted.addLast(elem);
it.remove();
}
}
result = merge(sorted, result);
}
return result;
}
private static <E extends Comparable<? super E>>
LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){
LinkedList<E> result = new LinkedList<E>();
while(!left.isEmpty() && !right.isEmpty()){
if(left.peek().compareTo(right.peek()) <= 0)
result.add(left.remove());
else
result.add(right.remove());
}
result.addAll(left);
result.addAll(right);
return result;
}
public static void main(String[] args){
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def digit_sum(n: int) -> int:
sum = 0
while n > 0:
sum += n % 10
n //= 10
return sum
def main() -> None:
additive_primes = 0
for i in range(2, 500):
if is_prime(i) and is_prime(digit_sum(i)):
additive_primes += 1
print(i, end=" ")
print(f"\nFound {additive_primes} additive primes less than 500")
if __name__ == "__main__":
main()
| public class additivePrimes {
public static void main(String[] args) {
int additive_primes = 0;
for (int i = 2; i < 500; i++) {
if(isPrime(i) && isPrime(digitSum(i))){
additive_primes++;
System.out.print(i + " ");
}
}
System.out.print("\nFound " + additive_primes + " additive primes less than 500");
}
static boolean isPrime(int n) {
int counter = 1;
if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {
return false;
}
while (counter * 6 - 1 <= Math.sqrt(n)) {
if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {
return false;
} else {
counter++;
}
}
return true;
}
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
parts += n
if parts == n0:
yield n0
if __name__ == '__main__':
print(list(islice(perfect_totient(), 20)))
| import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Integer> perfectTotient(int n) {
int test = 2;
List<Integer> results = new ArrayList<Integer>();
for ( int i = 0 ; i < n ; test++ ) {
int phiLoop = test;
int sum = 0;
do {
phiLoop = phi[phiLoop];
sum += phiLoop;
} while ( phiLoop > 1);
if ( sum == test ) {
i++;
results.add(test);
}
}
return results;
}
private static final int max = 100000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
parts += n
if parts == n0:
yield n0
if __name__ == '__main__':
print(list(islice(perfect_totient(), 20)))
| import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Integer> perfectTotient(int n) {
int test = 2;
List<Integer> results = new ArrayList<Integer>();
for ( int i = 0 ; i < n ; test++ ) {
int phiLoop = test;
int sum = 0;
do {
phiLoop = phi[phiLoop];
sum += phiLoop;
} while ( phiLoop > 1);
if ( sum == test ) {
i++;
results.add(test);
}
}
return results;
}
private static final int max = 100000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | class Delegator:
def __init__(self):
self.delegate = None
def operation(self):
if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):
return self.delegate.thing()
return 'default implementation'
class Delegate:
def thing(self):
return 'delegate implementation'
if __name__ == '__main__':
a = Delegator()
assert a.operation() == 'default implementation'
a.delegate = 'A delegate may be any object'
assert a.operation() == 'default implementation'
a.delegate = Delegate()
assert a.operation() == 'delegate implementation'
| interface Thingable {
String thing();
}
class Delegator {
public Thingable delegate;
public String operation() {
if (delegate == null)
return "default implementation";
else
return delegate.thing();
}
}
class Delegate implements Thingable {
public String thing() {
return "delegate implementation";
}
}
public class DelegateExample {
public static void main(String[] args) {
Delegator a = new Delegator();
assert a.operation().equals("default implementation");
Delegate d = new Delegate();
a.delegate = d;
assert a.operation().equals("delegate implementation");
a.delegate = new Thingable() {
public String thing() {
return "anonymous delegate implementation";
}
};
assert a.operation().equals("anonymous delegate implementation");
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def sum_of_divisors(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= (pow(p,k+1) - 1)//(p-1)
return ans
if __name__ == "__main__":
print([sum_of_divisors(n) for n in range(1,101)])
| public class DivisorSum {
private static long divisorSum(long n) {
var total = 1L;
var power = 2L;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (long p = 3; p * p <= n; p += 2) {
long sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%4d", divisorSum(n));
if (n % 10 == 0) {
System.out.println();
}
}
}
}
|
Port the provided Python code into Java while preserving the original functionality. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def sum_of_divisors(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= (pow(p,k+1) - 1)//(p-1)
return ans
if __name__ == "__main__":
print([sum_of_divisors(n) for n in range(1,101)])
| public class DivisorSum {
private static long divisorSum(long n) {
var total = 1L;
var power = 2L;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (long p = 3; p * p <= n; p += 2) {
long sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%4d", divisorSum(n));
if (n % 10 == 0) {
System.out.println();
}
}
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def sum_of_divisors(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= (pow(p,k+1) - 1)//(p-1)
return ans
if __name__ == "__main__":
print([sum_of_divisors(n) for n in range(1,101)])
| public class DivisorSum {
private static long divisorSum(long n) {
var total = 1L;
var power = 2L;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (long p = 3; p * p <= n; p += 2) {
long sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%4d", divisorSum(n));
if (n % 10 == 0) {
System.out.println();
}
}
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | 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()
for word in command_table_text.split():
abbr_len = sum(1 for c in word if c.isupper())
if abbr_len == 0:
abbr_len = len(word)
command_table[word] = abbr_len
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.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | 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()
for word in command_table_text.split():
abbr_len = sum(1 for c in word if c.isupper())
if abbr_len == 0:
abbr_len = len(word)
command_table[word] = abbr_len
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.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | >>> s = "Hello"
>>> s[0] = "h"
Traceback (most recent call last):
File "<pyshell
s[0] = "h"
TypeError: 'str' object does not support item assignment
| final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6;
immutableInt = 6;
|
Convert the following code from Python to Java, ensuring the logic remains intact. | def clip(subjectPolygon, clipPolygon):
def inside(p):
return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
def computeIntersection():
dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
dp = [ s[0] - e[0], s[1] - e[1] ]
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]
outputList = subjectPolygon
cp1 = clipPolygon[-1]
for clipVertex in clipPolygon:
cp2 = clipVertex
inputList = outputList
outputList = []
s = inputList[-1]
for subjectVertex in inputList:
e = subjectVertex
if inside(e):
if not inside(s):
outputList.append(computeIntersection())
outputList.append(e)
elif inside(s):
outputList.append(computeIntersection())
s = e
cp1 = cp2
return(outputList)
| import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class SutherlandHodgman extends JFrame {
SutherlandHodgmanPanel panel;
public static void main(String[] args) {
JFrame f = new SutherlandHodgman();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public SutherlandHodgman() {
Container content = getContentPane();
content.setLayout(new BorderLayout());
panel = new SutherlandHodgmanPanel();
content.add(panel, BorderLayout.CENTER);
setTitle("SutherlandHodgman");
pack();
setLocationRelativeTo(null);
}
}
class SutherlandHodgmanPanel extends JPanel {
List<double[]> subject, clipper, result;
public SutherlandHodgmanPanel() {
setPreferredSize(new Dimension(600, 500));
double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};
double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};
subject = new ArrayList<>(Arrays.asList(subjPoints));
result = new ArrayList<>(subject);
clipper = new ArrayList<>(Arrays.asList(clipPoints));
clipPolygon();
}
private void clipPolygon() {
int len = clipper.size();
for (int i = 0; i < len; i++) {
int len2 = result.size();
List<double[]> input = result;
result = new ArrayList<>(len2);
double[] A = clipper.get((i + len - 1) % len);
double[] B = clipper.get(i);
for (int j = 0; j < len2; j++) {
double[] P = input.get((j + len2 - 1) % len2);
double[] Q = input.get(j);
if (isInside(A, B, Q)) {
if (!isInside(A, B, P))
result.add(intersection(A, B, P, Q));
result.add(Q);
} else if (isInside(A, B, P))
result.add(intersection(A, B, P, Q));
}
}
}
private boolean isInside(double[] a, double[] b, double[] c) {
return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);
}
private double[] intersection(double[] a, double[] b, double[] p, double[] q) {
double A1 = b[1] - a[1];
double B1 = a[0] - b[0];
double C1 = A1 * a[0] + B1 * a[1];
double A2 = q[1] - p[1];
double B2 = p[0] - q[0];
double C2 = A2 * p[0] + B2 * p[1];
double det = A1 * B2 - A2 * B1;
double x = (B2 * C1 - B1 * C2) / det;
double y = (A1 * C2 - A2 * C1) / det;
return new double[]{x, y};
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.translate(80, 60);
g2.setStroke(new BasicStroke(3));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPolygon(g2, subject, Color.blue);
drawPolygon(g2, clipper, Color.red);
drawPolygon(g2, result, Color.green);
}
private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {
g2.setColor(color);
int len = points.size();
Line2D line = new Line2D.Double();
for (int i = 0; i < len; i++) {
double[] p1 = points.get(i);
double[] p2 = points.get((i + 1) % len);
line.setLine(p1[0], p1[1], p2[0], p2[1]);
g2.draw(line);
}
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | import string
sometext = .lower()
lc2bin = {ch: '{:05b}'.format(i)
for i, ch in enumerate(string.ascii_lowercase + ' .')}
bin2lc = {val: key for key, val in lc2bin.items()}
phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()
def to_5binary(msg):
return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))
def encrypt(message, text):
bin5 = to_5binary(message)
textlist = list(text.lower())
out = []
for capitalise in bin5:
while textlist:
ch = textlist.pop(0)
if ch.isalpha():
if capitalise:
ch = ch.upper()
out.append(ch)
break
else:
out.append(ch)
else:
raise Exception('ERROR: Ran out of characters in sometext')
return ''.join(out) + '...'
def decrypt(bacontext):
binary = []
bin5 = []
out = []
for ch in bacontext:
if ch.isalpha():
binary.append('1' if ch.isupper() else '0')
if len(binary) == 5:
bin5 = ''.join(binary)
out.append(bin2lc[bin5])
binary = []
return ''.join(out)
print('PLAINTEXT = \n%s\n' % phrase)
encrypted = encrypt(phrase, sometext)
print('ENCRYPTED = \n%s\n' % encrypted)
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'
| import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | import string
sometext = .lower()
lc2bin = {ch: '{:05b}'.format(i)
for i, ch in enumerate(string.ascii_lowercase + ' .')}
bin2lc = {val: key for key, val in lc2bin.items()}
phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower()
def to_5binary(msg):
return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower()))
def encrypt(message, text):
bin5 = to_5binary(message)
textlist = list(text.lower())
out = []
for capitalise in bin5:
while textlist:
ch = textlist.pop(0)
if ch.isalpha():
if capitalise:
ch = ch.upper()
out.append(ch)
break
else:
out.append(ch)
else:
raise Exception('ERROR: Ran out of characters in sometext')
return ''.join(out) + '...'
def decrypt(bacontext):
binary = []
bin5 = []
out = []
for ch in bacontext:
if ch.isalpha():
binary.append('1' if ch.isupper() else '0')
if len(binary) == 5:
bin5 = ''.join(binary)
out.append(bin2lc[bin5])
binary = []
return ''.join(out)
print('PLAINTEXT = \n%s\n' % phrase)
encrypted = encrypt(phrase, sometext)
print('ENCRYPTED = \n%s\n' % encrypted)
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'
| import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class BaconCipher {
private static final Map<Character, String> codes;
static {
codes = new HashMap<>();
codes.putAll(Map.of(
'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA",
'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB"
));
codes.putAll(Map.of(
'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA",
'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB"
));
codes.putAll(Map.of(
'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA",
'z', "BBAAB", ' ', "BBBAA"
));
}
private static String encode(String plainText, String message) {
String pt = plainText.toLowerCase();
StringBuilder sb = new StringBuilder();
for (char c : pt.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append(codes.get(c));
else sb.append(codes.get(' '));
}
String et = sb.toString();
String mg = message.toLowerCase();
sb.setLength(0);
int count = 0;
for (char c : mg.toCharArray()) {
if ('a' <= c && c <= 'z') {
if (et.charAt(count) == 'A') sb.append(c);
else sb.append(((char) (c - 32)));
count++;
if (count == et.length()) break;
} else sb.append(c);
}
return sb.toString();
}
private static String decode(String message) {
StringBuilder sb = new StringBuilder();
for (char c : message.toCharArray()) {
if ('a' <= c && c <= 'z') sb.append('A');
if ('A' <= c && c <= 'Z') sb.append('B');
}
String et = sb.toString();
sb.setLength(0);
for (int i = 0; i < et.length(); i += 5) {
String quintet = et.substring(i, i + 5);
Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null);
sb.append(key);
}
return sb.toString();
}
public static void main(String[] args) {
String plainText = "the quick brown fox jumps over the lazy dog";
String message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
String cipherText = encode(plainText, message);
System.out.printf("Cipher text ->\n\n%s\n", cipherText);
String decodedText = decode(cipherText);
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | def spiral(n):
dx,dy = 1,0
x,y = 0,0
myarray = [[None]* n for j in range(n)]
for i in xrange(n**2):
myarray[x][y] = i
nx,ny = x+dx, y+dy
if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
x,y = nx,ny
else:
dx,dy = -dy,dx
x,y = x+dx, y+dy
return myarray
def printspiral(myarray):
n = range(len(myarray))
for y in n:
for x in n:
print "%2i" % myarray[x][y],
print
printspiral(spiral(5))
| public class Blah {
public static void main(String[] args) {
print2dArray(getSpiralArray(5));
}
public static int[][] getSpiralArray(int dimension) {
int[][] spiralArray = new int[dimension][dimension];
int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);
int j;
int sideLen = dimension;
int currNum = 0;
for (int i = 0; i < numConcentricSquares; i++) {
for (j = 0; j < sideLen; j++) {
spiralArray[i][i + j] = currNum++;
}
for (j = 1; j < sideLen; j++) {
spiralArray[i + j][dimension - 1 - i] = currNum++;
}
for (j = sideLen - 2; j > -1; j--) {
spiralArray[dimension - 1 - i][i + j] = currNum++;
}
for (j = sideLen - 2; j > 0; j--) {
spiralArray[i + j][i] = currNum++;
}
sideLen -= 2;
}
return spiralArray;
}
public static void print2dArray(int[][] array) {
for (int[] row : array) {
for (int elem : row) {
System.out.printf("%3d", elem);
}
System.out.println();
}
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | >>> def printtable(data):
for row in data:
print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)
>>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]]
>>> printtable(data)
"a" "b" "c"
"" "q" "z"
"zap" "zip" "Zot"
>>> printtable( sorttable(data) )
"" "q" "z"
"a" "b" "c"
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=2) )
"zap" "zip" "Zot"
"a" "b" "c"
"" "q" "z"
>>> printtable( sorttable(data, column=1) )
"a" "b" "c"
"" "q" "z"
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=1, reverse=True) )
"zap" "zip" "Zot"
"" "q" "z"
"a" "b" "c"
>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )
"zap" "zip" "Zot"
"a" "b" "c"
"" "q" "z"
>>>
| module OptionalParameters
{
typedef Type<String >.Orderer as ColumnOrderer;
typedef Type<String[]>.Orderer as RowOrderer;
static String[][] sort(String[][] table,
ColumnOrderer? orderer = Null,
Int column = 0,
Boolean reverse = False,
)
{
orderer ?:= (s1, s2) -> s1 <=> s2;
ColumnOrderer byString = reverse
? ((s1, s2) -> orderer(s1, s2).reversed)
: orderer;
RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]);
return table.sorted(byColumn);
}
void run()
{
String[][] table =
[
["c", "x", "i"],
["a", "y", "p"],
["b", "z", "a"],
];
show("original input", table);
show("by default sort on column 0", sort(table));
show("by column 2", sort(table, column=2));
show("by column 2 reversed", sort(table, column=2, reverse=True));
}
void show(String title, String[][] table)
{
@Inject Console console;
console.print($"{title}:");
for (val row : table)
{
console.print($" {row}");
}
console.print();
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.append(int(random(256)))
ng.append(int(random(256)))
nb.append(int(random(256)))
for y in range(h):
for x in range(w):
dmin = dist(0, 0, w - 1, h - 1)
j = -1
for i in range(num_cells):
d = dist(0, 0, nx[i] - x, ny[i] - y)
if d < dmin:
dmin = d
j = i
set(x, y, color(nr[j], ng[j], nb[j]))
| import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
static double p = 3;
static BufferedImage I;
static int px[], py[], color[], cells = 100, size = 1000;
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.append(int(random(256)))
ng.append(int(random(256)))
nb.append(int(random(256)))
for y in range(h):
for x in range(w):
dmin = dist(0, 0, w - 1, h - 1)
j = -1
for i in range(num_cells):
d = dist(0, 0, nx[i] - x, ny[i] - y)
if d < dmin:
dmin = d
j = i
set(x, y, color(nr[j], ng[j], nb[j]))
| import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Voronoi extends JFrame {
static double p = 3;
static BufferedImage I;
static int px[], py[], color[], cells = 100, size = 1000;
public Voronoi() {
super("Voronoi Diagram");
setBounds(0, 0, size, size);
setDefaultCloseOperation(EXIT_ON_CLOSE);
int n = 0;
Random rand = new Random();
I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
px = new int[cells];
py = new int[cells];
color = new int[cells];
for (int i = 0; i < cells; i++) {
px[i] = rand.nextInt(size);
py[i] = rand.nextInt(size);
color[i] = rand.nextInt(16777215);
}
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
n = 0;
for (byte i = 0; i < cells; i++) {
if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) {
n = i;
}
}
I.setRGB(x, y, color[n]);
}
}
Graphics2D g = I.createGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < cells; i++) {
g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5));
}
try {
ImageIO.write(I, "png", new File("voronoi.png"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
g.drawImage(I, 0, 0, this);
}
static double distance(int x1, int x2, int y1, int y2) {
double d;
d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
return d;
}
public static void main(String[] args) {
new Voronoi().setVisible(true);
}
}
|
Port the provided Python code into Java while preserving the original functionality. | import ctypes
libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def")
libc.strcmp("hello", "hello")
| public class JNIDemo
{
static
{ System.loadLibrary("JNIDemo"); }
public static void main(String[] args)
{
System.out.println(callStrdup("Hello World!"));
}
private static native String callStrdup(String s);
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from random import randrange
def s_of_n_creator(n):
sample, i = [], 0
def s_of_n(item):
nonlocal i
i += 1
if i <= n:
sample.append(item)
elif randrange(i) < n:
sample[randrange(n)] = item
return sample
return s_of_n
if __name__ == '__main__':
bin = [0]* 10
items = range(10)
print("Single run samples for n = 3:")
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
print(" Item: %i -> sample: %s" % (item, sample))
for trial in range(100000):
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
for s in sample:
bin[s] += 1
print("\nTest item frequencies for 100000 runs:\n ",
'\n '.join("%i:%i" % x for x in enumerate(bin)))
| import java.util.*;
class SOfN<T> {
private static final Random rand = new Random();
private List<T> sample;
private int i = 0;
private int n;
public SOfN(int _n) {
n = _n;
sample = new ArrayList<T>(n);
}
public List<T> process(T item) {
if (++i <= n) {
sample.add(item);
} else if (rand.nextInt(i) < n) {
sample.set(rand.nextInt(n), item);
}
return sample;
}
}
public class AlgorithmS {
public static void main(String[] args) {
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
SOfN<Integer> s_of_n = new SOfN<Integer>(3);
for (int i = 0; i < 9; i++) s_of_n.process(i);
for (int s : s_of_n.process(9)) bin[s]++;
}
System.out.println(Arrays.toString(bin));
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | from random import randrange
def s_of_n_creator(n):
sample, i = [], 0
def s_of_n(item):
nonlocal i
i += 1
if i <= n:
sample.append(item)
elif randrange(i) < n:
sample[randrange(n)] = item
return sample
return s_of_n
if __name__ == '__main__':
bin = [0]* 10
items = range(10)
print("Single run samples for n = 3:")
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
print(" Item: %i -> sample: %s" % (item, sample))
for trial in range(100000):
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
for s in sample:
bin[s] += 1
print("\nTest item frequencies for 100000 runs:\n ",
'\n '.join("%i:%i" % x for x in enumerate(bin)))
| import java.util.*;
class SOfN<T> {
private static final Random rand = new Random();
private List<T> sample;
private int i = 0;
private int n;
public SOfN(int _n) {
n = _n;
sample = new ArrayList<T>(n);
}
public List<T> process(T item) {
if (++i <= n) {
sample.add(item);
} else if (rand.nextInt(i) < n) {
sample.set(rand.nextInt(n), item);
}
return sample;
}
}
public class AlgorithmS {
public static void main(String[] args) {
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
SOfN<Integer> s_of_n = new SOfN<Integer>(3);
for (int i = 0; i < 9; i++) s_of_n.process(i);
for (int s : s_of_n.process(9)) bin[s]++;
}
System.out.println(Arrays.toString(bin));
}
}
|
Write the same code in Java as shown below in Python. |
from itertools import accumulate, chain, count, islice
from fractions import Fraction
def faulhaberTriangle(m):
def go(rs, n):
def f(x, y):
return Fraction(n, x) * y
xs = list(map(f, islice(count(2), m), rs))
return [Fraction(1 - sum(xs), 1)] + xs
return list(accumulate(
[[]] + list(islice(count(0), 1 + m)),
go
))[1:]
def faulhaberSum(p, n):
def go(x, y):
return y * (n ** x)
return sum(
map(go, count(1), faulhaberTriangle(p)[-1])
)
def main():
fs = faulhaberTriangle(9)
print(
fTable(__doc__ + ':\n')(str)(
compose(concat)(
fmap(showRatio(3)(3))
)
)(
index(fs)
)(range(0, len(fs)))
)
print('')
print(
faulhaberSum(17, 1000)
)
def fTable(s):
def gox(xShow):
def gofx(fxShow):
def gof(f):
def goxs(xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
def arrowed(x, y):
return y.rjust(w, ' ') + ' -> ' + (
fxShow(f(x))
)
return s + '\n' + '\n'.join(
map(arrowed, xs, ys)
)
return goxs
return gof
return gofx
return gox
def compose(g):
return lambda f: lambda x: g(f(x))
def concat(xs):
def f(ys):
zs = list(chain(*ys))
return ''.join(zs) if isinstance(ys[0], str) else zs
return (
f(xs) if isinstance(xs, list) else (
chain.from_iterable(xs)
)
) if xs else []
def fmap(f):
def go(xs):
return list(map(f, xs))
return go
def index(xs):
return lambda n: None if 0 > n else (
xs[n] if (
hasattr(xs, "__getitem__")
) else next(islice(xs, n, None))
)
def showRatio(m):
def go(n):
def f(r):
d = r.denominator
return str(r.numerator).rjust(m, ' ') + (
('/' + str(d).ljust(n, ' ')) if 1 != d else (
' ' * (1 + n)
)
)
return f
return go
if __name__ == '__main__':
main()
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.stream.LongStream;
public class FaulhabersTriangle {
private static final MathContext MC = new MathContext(256);
private static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
private static class Frac implements Comparable<Frac> {
private long num;
private long denom;
public static final Frac ZERO = new Frac(0, 1);
public Frac(long n, long d) {
if (d == 0) throw new IllegalArgumentException("d must not be zero");
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
} else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.abs(gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
public Frac plus(Frac rhs) {
return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom);
}
public Frac unaryMinus() {
return new Frac(-num, denom);
}
public Frac minus(Frac rhs) {
return this.plus(rhs.unaryMinus());
}
public Frac times(Frac rhs) {
return new Frac(this.num * rhs.num, this.denom * rhs.denom);
}
@Override
public int compareTo(Frac o) {
double diff = toDouble() - o.toDouble();
return Double.compare(diff, 0.0);
}
@Override
public boolean equals(Object obj) {
return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0;
}
@Override
public String toString() {
if (denom == 1) {
return Long.toString(num);
}
return String.format("%d/%d", num, denom);
}
public double toDouble() {
return (double) num / denom;
}
public BigDecimal toBigDecimal() {
return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC);
}
}
private static Frac bernoulli(int n) {
if (n < 0) throw new IllegalArgumentException("n may not be negative or zero");
Frac[] a = new Frac[n + 1];
Arrays.fill(a, Frac.ZERO);
for (int m = 0; m <= n; ++m) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; --j) {
a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1));
}
}
if (n != 1) return a[0];
return a[0].unaryMinus();
}
private static long binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException();
if (n == 0 || k == 0) return 1;
long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b);
long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i);
return num / den;
}
private static Frac[] faulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
Arrays.fill(coeffs, Frac.ZERO);
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; ++j) {
sign *= -1;
coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j));
}
return coeffs;
}
public static void main(String[] args) {
for (int i = 0; i <= 9; ++i) {
Frac[] coeffs = faulhaberTriangle(i);
for (Frac coeff : coeffs) {
System.out.printf("%5s ", coeff);
}
System.out.println();
}
System.out.println();
int k = 17;
Frac[] cc = faulhaberTriangle(k);
int n = 1000;
BigDecimal nn = BigDecimal.valueOf(n);
BigDecimal np = BigDecimal.ONE;
BigDecimal sum = BigDecimal.ZERO;
for (Frac c : cc) {
np = np.multiply(nn);
sum = sum.add(np.multiply(c.toBigDecimal()));
}
System.out.println(sum.toBigInteger());
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
assert arr4 == [1, 2, 3, 4, 5, 6]
arr4.extend(arr3)
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
| String[] fruits = ["apples", "oranges"];
String[] grains = ["wheat", "corn"];
String[] all = fruits + grains;
|
Translate this program into Java but keep the logic exactly as in Python. | string = raw_input("Input a string: ")
| import java.util.Scanner;
public class GetInput {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = s.nextLine();
System.out.print("Enter an integer: ");
int i = Integer.parseInt(s.next());
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>>
|
import processing.sound.*;
float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};
SinOsc sine;
size(500,500);
sine = new SinOsc(this);
for(int i=0;i<frequencies.length;i++){
sine.freq(frequencies[i]);
sine.play();
delay(500);
}
|
Generate an equivalent Java version of this Python code. | >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>>
|
import processing.sound.*;
float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};
SinOsc sine;
size(500,500);
sine = new SinOsc(this);
for(int i=0;i<frequencies.length;i++){
sine.freq(frequencies[i]);
sine.play();
delay(500);
}
|
Write the same code in Java as shown below in Python. | >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>>
|
import processing.sound.*;
float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25};
SinOsc sine;
size(500,500);
sine = new SinOsc(this);
for(int i=0;i<frequencies.length;i++){
sine.freq(frequencies[i]);
sine.play();
delay(500);
}
|
Write a version of this Python function in Java with identical behavior. | from itertools import combinations
def anycomb(items):
' return combinations of any length from the items '
return ( comb
for r in range(1, len(items)+1)
for comb in combinations(items, r)
)
def totalvalue(comb):
' Totalise a particular combination of items'
totwt = totval = 0
for item, wt, val in comb:
totwt += wt
totval += val
return (totval, -totwt) if totwt <= 400 else (0, 0)
items = (
("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160),
("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40),
("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30),
("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40),
("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75),
("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12),
("socks", 4, 50), ("book", 30, 10),
)
bagged = max( anycomb(items), key=totalvalue)
print("Bagged the following items\n " +
'\n '.join(sorted(item for item,_,_ in bagged)))
val, wt = totalvalue(bagged)
print("for a total value of %i and a total weight of %i" % (val, -wt))
| package hu.pj.alg.test;
import hu.pj.alg.ZeroOneKnapsack;
import hu.pj.obj.Item;
import java.util.*;
import java.text.*;
public class ZeroOneKnapsackForTourists {
public ZeroOneKnapsackForTourists() {
ZeroOneKnapsack zok = new ZeroOneKnapsack(400);
zok.add("map", 9, 150);
zok.add("compass", 13, 35);
zok.add("water", 153, 200);
zok.add("sandwich", 50, 160);
zok.add("glucose", 15, 60);
zok.add("tin", 68, 45);
zok.add("banana", 27, 60);
zok.add("apple", 39, 40);
zok.add("cheese", 23, 30);
zok.add("beer", 52, 10);
zok.add("suntan cream", 11, 70);
zok.add("camera", 32, 30);
zok.add("t-shirt", 24, 15);
zok.add("trousers", 48, 10);
zok.add("umbrella", 73, 40);
zok.add("waterproof trousers", 42, 70);
zok.add("waterproof overclothes", 43, 75);
zok.add("note-case", 22, 80);
zok.add("sunglasses", 7, 20);
zok.add("towel", 18, 12);
zok.add("socks", 4, 50);
zok.add("book", 30, 10);
List<Item> itemList = zok.calcSolution();
if (zok.isCalculated()) {
NumberFormat nf = NumberFormat.getInstance();
System.out.println(
"Maximal weight = " +
nf.format(zok.getMaxWeight() / 100.0) + " kg"
);
System.out.println(
"Total weight of solution = " +
nf.format(zok.getSolutionWeight() / 100.0) + " kg"
);
System.out.println(
"Total value = " +
zok.getProfit()
);
System.out.println();
System.out.println(
"You can carry the following materials " +
"in the knapsack:"
);
for (Item item : itemList) {
if (item.getInKnapsack() == 1) {
System.out.format(
"%1$-23s %2$-3s %3$-5s %4$-15s \n",
item.getName(),
item.getWeight(), "dag ",
"(value = " + item.getValue() + ")"
);
}
}
} else {
System.out.println(
"The problem is not solved. " +
"Maybe you gave wrong data."
);
}
}
public static void main(String[] args) {
new ZeroOneKnapsackForTourists();
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from __future__ import print_function
from itertools import takewhile
maxsum = 99
def get_primes(max):
if max < 2:
return []
lprimes = [2]
for x in range(3, max + 1, 2):
for p in lprimes:
if x % p == 0:
break
else:
lprimes.append(x)
return lprimes
descendants = [[] for _ in range(maxsum + 1)]
ancestors = [[] for _ in range(maxsum + 1)]
primes = get_primes(maxsum)
for p in primes:
descendants[p].append(p)
for s in range(1, len(descendants) - p):
descendants[s + p] += [p * pr for pr in descendants[s]]
for p in primes + [4]:
descendants[p].pop()
total = 0
for s in range(1, maxsum + 1):
descendants[s].sort()
for d in takewhile(lambda x: x <= maxsum, descendants[s]):
ancestors[d] = ancestors[s] + [s]
print([s], "Level:", len(ancestors[s]))
print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None")
print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None")
if len(descendants[s]):
print(descendants[s])
print()
total += len(descendants[s])
print("Total descendants", total)
| import java.io.*;
import java.util.*;
public class PrimeDescendants {
public static void main(String[] args) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) {
printPrimeDesc(writer, 100);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private static void printPrimeDesc(Writer writer, int limit) throws IOException {
List<Long> primes = findPrimes(limit);
List<Long> ancestor = new ArrayList<>(limit);
List<List<Long>> descendants = new ArrayList<>(limit);
for (int i = 0; i < limit; ++i) {
ancestor.add(Long.valueOf(0));
descendants.add(new ArrayList<Long>());
}
for (Long prime : primes) {
int p = prime.intValue();
descendants.get(p).add(prime);
for (int i = 0; i + p < limit; ++i) {
int s = i + p;
for (Long n : descendants.get(i)) {
Long prod = n * p;
descendants.get(s).add(prod);
if (prod < limit)
ancestor.set(prod.intValue(), Long.valueOf(s));
}
}
}
int totalDescendants = 0;
for (int i = 1; i < limit; ++i) {
List<Long> ancestors = getAncestors(ancestor, i);
writer.write("[" + i + "] Level: " + ancestors.size() + "\n");
writer.write("Ancestors: ");
Collections.sort(ancestors);
print(writer, ancestors);
writer.write("Descendants: ");
List<Long> desc = descendants.get(i);
if (!desc.isEmpty()) {
Collections.sort(desc);
if (desc.get(0) == i)
desc.remove(0);
}
writer.write(desc.size() + "\n");
totalDescendants += desc.size();
if (!desc.isEmpty())
print(writer, desc);
writer.write("\n");
}
writer.write("Total descendants: " + totalDescendants + "\n");
}
private static List<Long> findPrimes(int limit) {
boolean[] isprime = new boolean[limit];
Arrays.fill(isprime, true);
isprime[0] = isprime[1] = false;
for (int p = 2; p * p < limit; ++p) {
if (isprime[p]) {
for (int i = p * p; i < limit; i += p)
isprime[i] = false;
}
}
List<Long> primes = new ArrayList<>();
for (int p = 2; p < limit; ++p) {
if (isprime[p])
primes.add(Long.valueOf(p));
}
return primes;
}
private static List<Long> getAncestors(List<Long> ancestor, int n) {
List<Long> result = new ArrayList<>();
for (Long a = ancestor.get(n); a != 0 && a != n; ) {
n = a.intValue();
a = ancestor.get(n);
result.add(Long.valueOf(n));
}
return result;
}
private static void print(Writer writer, List<Long> list) throws IOException {
if (list.isEmpty()) {
writer.write("none\n");
return;
}
int i = 0;
writer.write(String.valueOf(list.get(i++)));
for (; i != list.size(); ++i)
writer.write(", " + list.get(i));
writer.write("\n");
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), (500, 100)),
((1, 2, 3), (), (500, 100))]:
print(lists, '=>')
pp(cp(lists), indent=2)
| import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), (500, 100)),
((1, 2, 3), (), (500, 100))]:
print(lists, '=>')
pp(cp(lists), indent=2)
| import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | import itertools
def cp(lsts):
return list(itertools.product(*lsts))
if __name__ == '__main__':
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), (500, 100)),
((1, 2, 3), (), (500, 100))]:
print(lists, '=>')
pp(cp(lists), indent=2)
| import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
List<?> product = a[0];
for (int i = 1; i < a.length; i++) {
product = product(product, a[i]);
}
return product;
}
return emptyList();
}
private <A, B> List<?> product(List<A> a, List<B> b) {
return of(a.stream()
.map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList()))
.flatMap(List::stream)
.collect(toList())).orElse(emptyList());
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | >>>
>>> from math import sin, cos, acos, asin
>>>
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>>
>>>
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>>
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>>
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>>
| import java.util.ArrayList;
public class FirstClass{
public interface Function<A,B>{
B apply(A x);
}
public static <A,B,C> Function<A, C> compose(
final Function<B, C> f, final Function<A, B> g) {
return new Function<A, C>() {
@Override public C apply(A x) {
return f.apply(g.apply(x));
}
};
}
public static void main(String[] args){
ArrayList<Function<Double, Double>> functions =
new ArrayList<Function<Double,Double>>();
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.cos(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.tan(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return x * x;
}
});
ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.acos(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.atan(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.sqrt(x);
}
});
System.out.println("Compositions:");
for(int i = 0; i < functions.size(); i++){
System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
}
System.out.println("Hard-coded compositions:");
System.out.println(Math.cos(Math.acos(0.5)));
System.out.println(Math.tan(Math.atan(0.5)));
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | >>> def proper_divs2(n):
... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}
...
>>> [proper_divs2(n) for n in range(1, 11)]
[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]
>>>
>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])
>>> n
15120
>>> length
79
>>>
| import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Proper{
public static List<Integer> properDivs(int n){
List<Integer> divs = new LinkedList<Integer>();
if(n == 1) return divs;
divs.add(1);
for(int x = 2; x < n; x++){
if(n % x == 0) divs.add(x);
}
Collections.sort(divs);
return divs;
}
public static void main(String[] args){
for(int x = 1; x <= 10; x++){
System.out.println(x + ": " + properDivs(x));
}
int x = 0, count = 0;
for(int n = 1; n <= 20000; n++){
if(properDivs(n).size() > count){
x = n;
count = properDivs(n).size();
}
}
System.out.println(x + ": " + count);
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | >>> from xml.etree import ElementTree as ET
>>> from itertools import izip
>>> def characterstoxml(names, remarks):
root = ET.Element("CharacterRemarks")
for name, remark in izip(names, remarks):
c = ET.SubElement(root, "Character", {'name': name})
c.text = remark
return ET.tostring(root)
>>> print characterstoxml(
names = ["April", "Tam O'Shanter", "Emily"],
remarks = [ "Bubbly: I'm > Tam and <= Emily",
'Burns: "When chapman billies leave the street ..."',
'Short & shrift' ] ).replace('><','>\n<')
| import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XmlCreation {
private static final String[] names = {"April", "Tam O'Shanter", "Emily"};
private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift"};
public static void main(String[] args) {
try {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element root = doc.createElement("CharacterRemarks");
doc.appendChild(root);
for(int i = 0; i < names.length; i++) {
final Element character = doc.createElement("Character");
root.appendChild(character);
character.setAttribute("name", names[i]);
character.appendChild(doc.createTextNode(remarks[i]));
}
final Source source = new DOMSource(doc);
final StringWriter buffer = new StringWriter();
final Result result = new StreamResult(buffer);
final Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.transform(source, result);
System.out.println(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')
| import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Plot2d extends JApplet {
double[] xi;
double[] yi;
public Plot2d(double[] x, double[] y) {
this.xi = x;
this.yi = y;
}
public static double max(double[] t) {
double maximum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > maximum) {
maximum = t[i];
}
}
return maximum;
}
public static double min(double[] t) {
double minimum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] < minimum) {
minimum = t[i];
}
}
return minimum;
}
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.black);
int x0 = 70;
int y0 = 10;
int xm = 670;
int ym = 410;
int xspan = xm - x0;
int yspan = ym - y0;
double xmax = max(xi);
double xmin = min(xi);
double ymax = max(yi);
double ymin = min(yi);
g2.draw(new Line2D.Double(x0, ym, xm, ym));
g2.draw(new Line2D.Double(x0, ym, x0, y0));
for (int j = 0; j < 5; j++) {
int interv = 4;
g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);
g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),
ym - j * yspan / interv + y0 - 5);
g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));
g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));
}
for (int i = 0; i < xi.length; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
g2.drawString("o", x0 + f - 3, h + 14);
}
for (int i = 0; i < xi.length - 1; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));
g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));
}
}
public static void main(String args[]) {
JFrame f = new JFrame("ShapesDemo2D");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};
JApplet applet = new Plot2d(r, t);
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(720, 480));
f.show();
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')
| import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Plot2d extends JApplet {
double[] xi;
double[] yi;
public Plot2d(double[] x, double[] y) {
this.xi = x;
this.yi = y;
}
public static double max(double[] t) {
double maximum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > maximum) {
maximum = t[i];
}
}
return maximum;
}
public static double min(double[] t) {
double minimum = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] < minimum) {
minimum = t[i];
}
}
return minimum;
}
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.black);
int x0 = 70;
int y0 = 10;
int xm = 670;
int ym = 410;
int xspan = xm - x0;
int yspan = ym - y0;
double xmax = max(xi);
double xmin = min(xi);
double ymax = max(yi);
double ymin = min(yi);
g2.draw(new Line2D.Double(x0, ym, xm, ym));
g2.draw(new Line2D.Double(x0, ym, x0, y0));
for (int j = 0; j < 5; j++) {
int interv = 4;
g2.drawString("" + (j * (xmax - xmin) / interv + xmin), j * xspan / interv + x0 - 10, ym + 20);
g2.drawString("" + (j * (ymax - ymin) / interv + ymin), x0 - 20 - (int) (9 * Math.log10(ymax)),
ym - j * yspan / interv + y0 - 5);
g2.draw(new Line2D.Double(j * xspan / interv + x0, ym, j * xspan / interv + x0, ym + 5));
g2.draw(new Line2D.Double(x0 - 5, j * yspan / interv + y0, x0, j * yspan / interv + y0));
}
for (int i = 0; i < xi.length; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
g2.drawString("o", x0 + f - 3, h + 14);
}
for (int i = 0; i < xi.length - 1; i++) {
int f = (int) ((xi[i] - xmin) * xspan / (xmax - xmin));
int f2 = (int) ((xi[i + 1] - xmin) * xspan / (xmax - xmin));
int h = (int) (((ymax - ymin) - (yi[i] - ymin)) * yspan / (ymax - ymin));
int h2 = (int) (((ymax - ymin) - (yi[i + 1] - ymin)) * yspan / (ymax - ymin));
g2.draw(new Line2D.Double(f + x0, h + y0, f2 + x0, h2 + y0));
}
}
public static void main(String args[]) {
JFrame f = new JFrame("ShapesDemo2D");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
double[] r = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double[] t = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.09};
JApplet applet = new Plot2d(r, t);
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(720, 480));
f.show();
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | import re
string = "This is a string"
if re.search('string$', string):
print("Ends with string.")
string = re.sub(" a ", " another ", string)
print(string)
| String str = "I am a string";
if (str.matches(".*string")) {
System.out.println("ends with 'string'");
}
|
Port the provided Python code into Java while preserving the original functionality. | inclusive_range = mn, mx = (1, 10)
print( % inclusive_range)
i = 0
while True:
i += 1
guess = (mn+mx)//2
txt = input("Guess %2i is: %2i. The score for which is (h,l,=): "
% (i, guess)).strip().lower()[0]
if txt not in 'hl=':
print(" I don't understand your input of '%s' ?" % txt)
continue
if txt == 'h':
mx = guess-1
if txt == 'l':
mn = guess+1
if txt == '=':
print(" Ye-Haw!!")
break
if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]):
print("Please check your scoring as I cannot find the value")
break
print("\nThanks for keeping score.")
| import java.util.AbstractList;
import java.util.Collections;
import java.util.Scanner;
public class GuessNumber {
public static final int LOWER = 0, UPPER = 100;
public static void main(String[] args) {
System.out.printf("Instructions:\n" +
"Think of integer number from %d (inclusive) to %d (exclusive) and\n" +
"I will guess it. After each guess, you respond with L, H, or C depending\n" +
"on if my guess was too low, too high, or correct.\n",
LOWER, UPPER);
int result = Collections.binarySearch(new AbstractList<Integer>() {
private final Scanner in = new Scanner(System.in);
public int size() { return UPPER - LOWER; }
public Integer get(int i) {
System.out.printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", LOWER+i);
String s = in.nextLine();
assert s.length() > 0;
switch (Character.toLowerCase(s.charAt(0))) {
case 'l':
return -1;
case 'h':
return 1;
case 'c':
return 0;
}
return -1;
}
}, 0);
if (result < 0)
System.out.println("That is impossible.");
else
System.out.printf("Your number is %d.\n", result);
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}
| import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();
for(int i= 0; i < keys.length; i++){
hash.put(keys[i], vals[i]);
}
}
|
Please provide an equivalent version of this Python code in Java. | keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}
| import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();
for(int i= 0; i < keys.length; i++){
hash.put(keys[i], vals[i]);
}
}
|
Write a version of this Python function in Java with identical behavior. | from bisect import bisect_right
def bin_it(limits: list, data: list) -> list:
"Bin data according to (ascending) limits."
bins = [0] * (len(limits) + 1)
for d in data:
bins[bisect_right(limits, d)] += 1
return bins
def bin_print(limits: list, bins: list) -> list:
print(f" < {limits[0]:3} := {bins[0]:3}")
for lo, hi, count in zip(limits, limits[1:], bins[1:]):
print(f">= {lo:3} .. < {hi:3} := {count:3}")
print(f">= {limits[-1]:3} := {bins[-1]:3}")
if __name__ == "__main__":
print("RC FIRST EXAMPLE\n")
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
bins = bin_it(limits, data)
bin_print(limits, bins)
print("\nRC SECOND EXAMPLE\n")
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
bins = bin_it(limits, data)
bin_print(limits, bins)
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
|
Write a version of this Python function in Java with identical behavior. | from bisect import bisect_right
def bin_it(limits: list, data: list) -> list:
"Bin data according to (ascending) limits."
bins = [0] * (len(limits) + 1)
for d in data:
bins[bisect_right(limits, d)] += 1
return bins
def bin_print(limits: list, bins: list) -> list:
print(f" < {limits[0]:3} := {bins[0]:3}")
for lo, hi, count in zip(limits, limits[1:], bins[1:]):
print(f">= {lo:3} .. < {hi:3} := {count:3}")
print(f">= {limits[-1]:3} := {bins[-1]:3}")
if __name__ == "__main__":
print("RC FIRST EXAMPLE\n")
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
bins = bin_it(limits, data)
bin_print(limits, bins)
print("\nRC SECOND EXAMPLE\n")
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
bins = bin_it(limits, data)
bin_print(limits, bins)
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from bisect import bisect_right
def bin_it(limits: list, data: list) -> list:
"Bin data according to (ascending) limits."
bins = [0] * (len(limits) + 1)
for d in data:
bins[bisect_right(limits, d)] += 1
return bins
def bin_print(limits: list, bins: list) -> list:
print(f" < {limits[0]:3} := {bins[0]:3}")
for lo, hi, count in zip(limits, limits[1:], bins[1:]):
print(f">= {lo:3} .. < {hi:3} := {count:3}")
print(f">= {limits[-1]:3} := {bins[-1]:3}")
if __name__ == "__main__":
print("RC FIRST EXAMPLE\n")
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
bins = bin_it(limits, data)
bin_print(limits, bins)
print("\nRC SECOND EXAMPLE\n")
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
bins = bin_it(limits, data)
bin_print(limits, bins)
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
i = i+1;
} else {
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | def setup():
size(600, 600)
background(0)
stroke(255)
drawTree(300, 550, 9)
def drawTree(x, y, depth):
fork_ang = radians(20)
base_len = 10
if depth > 0:
pushMatrix()
translate(x, y - baseLen * depth)
line(0, baseLen * depth, 0, 0)
rotate(fork_ang)
drawTree(0, 0, depth - 1)
rotate(2 * -fork_ang)
drawTree(0, 0, depth - 1)
popMatrix()
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class FractalTree extends JFrame {
public FractalTree() {
super("Fractal Tree");
setBounds(100, 100, 800, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {
if (depth == 0) return;
int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
g.drawLine(x1, y1, x2, y2);
drawTree(g, x2, y2, angle - 20, depth - 1);
drawTree(g, x2, y2, angle + 20, depth - 1);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
drawTree(g, 400, 500, -90, 9);
}
public static void main(String[] args) {
new FractalTree().setVisible(true);
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from turtle import *
colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]
screen = getscreen()
left_edge = -screen.window_width()//2
right_edge = screen.window_width()//2
quarter_height = screen.window_height()//4
half_height = quarter_height * 2
speed("fastest")
for quarter in range(4):
pensize(quarter+1)
colornum = 0
min_y = half_height - ((quarter + 1) * quarter_height)
max_y = half_height - ((quarter) * quarter_height)
for x in range(left_edge,right_edge,quarter+1):
penup()
pencolor(colors[colornum])
colornum = (colornum + 1) % len(colors)
setposition(x,min_y)
pendown()
setposition(x,max_y)
notused = input("Hit enter to continue: ")
| import java.awt.*;
import static java.awt.Color.*;
import javax.swing.*;
public class ColourPinstripeDisplay extends JPanel {
final static Color[] palette = {black, red, green, blue, magenta,cyan,
yellow, white};
final int bands = 4;
public ColourPinstripeDisplay() {
setPreferredSize(new Dimension(900, 600));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = getHeight();
for (int b = 1; b <= bands; b++) {
for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) {
g.setColor(palette[colIndex % palette.length]);
g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("ColourPinstripeDisplay");
f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | from datetime import date
from calendar import isleap
def weekday(d):
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
dooms = [
[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
]
c = d.year // 100
r = d.year % 100
s = r // 12
t = r % 12
c_anchor = (5 * (c % 4) + 2) % 7
doomsday = (s + t + (t // 4) + c_anchor) % 7
anchorday = dooms[isleap(d.year)][d.month - 1]
weekday = (doomsday + d.day - anchorday + 7) % 7
return days[weekday]
dates = [date(*x) for x in
[(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),
(2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]
]
for d in dates:
tense = "was" if d < date.today() else "is" if d == date.today() else "will be"
print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
| class Doom {
public static void main(String[] args) {
final Date[] dates = {
new Date(1800,1,6),
new Date(1875,3,29),
new Date(1915,12,7),
new Date(1970,12,23),
new Date(2043,5,14),
new Date(2077,2,12),
new Date(2101,4,2)
};
for (Date d : dates)
System.out.println(
String.format("%s: %s", d.format(), d.weekday()));
}
}
class Date {
private int year, month, day;
private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};
private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};
public static final String[] weekdays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean isLeapYear() {
return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
public String format() {
return String.format("%02d/%02d/%04d", month, day, year);
}
public String weekday() {
final int c = year/100;
final int r = year%100;
final int s = r/12;
final int t = r%12;
final int c_anchor = (5 * (c%4) + 2) % 7;
final int doom = (s + t + t/4 + c_anchor) % 7;
final int anchor =
isLeapYear() ? leapdoom[month-1] : normdoom[month-1];
return weekdays[(doom + day - anchor + 7) % 7];
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from datetime import date
from calendar import isleap
def weekday(d):
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
dooms = [
[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
]
c = d.year // 100
r = d.year % 100
s = r // 12
t = r % 12
c_anchor = (5 * (c % 4) + 2) % 7
doomsday = (s + t + (t // 4) + c_anchor) % 7
anchorday = dooms[isleap(d.year)][d.month - 1]
weekday = (doomsday + d.day - anchorday + 7) % 7
return days[weekday]
dates = [date(*x) for x in
[(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),
(2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]
]
for d in dates:
tense = "was" if d < date.today() else "is" if d == date.today() else "will be"
print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
| class Doom {
public static void main(String[] args) {
final Date[] dates = {
new Date(1800,1,6),
new Date(1875,3,29),
new Date(1915,12,7),
new Date(1970,12,23),
new Date(2043,5,14),
new Date(2077,2,12),
new Date(2101,4,2)
};
for (Date d : dates)
System.out.println(
String.format("%s: %s", d.format(), d.weekday()));
}
}
class Date {
private int year, month, day;
private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};
private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};
public static final String[] weekdays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean isLeapYear() {
return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
public String format() {
return String.format("%02d/%02d/%04d", month, day, year);
}
public String weekday() {
final int c = year/100;
final int r = year%100;
final int s = r/12;
final int t = r%12;
final int c_anchor = (5 * (c%4) + 2) % 7;
final int doom = (s + t + t/4 + c_anchor) % 7;
final int anchor =
isLeapYear() ? leapdoom[month-1] : normdoom[month-1];
return weekdays[(doom + day - anchor + 7) % 7];
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | from datetime import date
from calendar import isleap
def weekday(d):
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"]
dooms = [
[3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
[4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
]
c = d.year // 100
r = d.year % 100
s = r // 12
t = r % 12
c_anchor = (5 * (c % 4) + 2) % 7
doomsday = (s + t + (t // 4) + c_anchor) % 7
anchorday = dooms[isleap(d.year)][d.month - 1]
weekday = (doomsday + d.day - anchorday + 7) % 7
return days[weekday]
dates = [date(*x) for x in
[(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),
(2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]
]
for d in dates:
tense = "was" if d < date.today() else "is" if d == date.today() else "will be"
print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
| class Doom {
public static void main(String[] args) {
final Date[] dates = {
new Date(1800,1,6),
new Date(1875,3,29),
new Date(1915,12,7),
new Date(1970,12,23),
new Date(2043,5,14),
new Date(2077,2,12),
new Date(2101,4,2)
};
for (Date d : dates)
System.out.println(
String.format("%s: %s", d.format(), d.weekday()));
}
}
class Date {
private int year, month, day;
private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5};
private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5};
public static final String[] weekdays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean isLeapYear() {
return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
public String format() {
return String.format("%02d/%02d/%04d", month, day, year);
}
public String weekday() {
final int c = year/100;
final int r = year%100;
final int s = r/12;
final int t = r%12;
final int c_anchor = (5 * (c%4) + 2) % 7;
final int doom = (s + t + t/4 + c_anchor) % 7;
final int anchor =
isLeapYear() ? leapdoom[month-1] : normdoom[month-1];
return weekdays[(doom + day - anchor + 7) % 7];
}
}
|
Write the same algorithm in Java as shown in this Python implementation. |
def cocktailshiftingbounds(A):
beginIdx = 0
endIdx = len(A) - 1
while beginIdx <= endIdx:
newBeginIdx = endIdx
newEndIdx = beginIdx
for ii in range(beginIdx,endIdx):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
newEndIdx = ii
endIdx = newEndIdx
for ii in range(endIdx,beginIdx-1,-1):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
newBeginIdx = ii
beginIdx = newBeginIdx + 1
test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailshiftingbounds(test1)
print(test1)
test2=list('big fjords vex quick waltz nymph')
cocktailshiftingbounds(test2)
print(''.join(test2))
| import java.util.*;
public class CocktailSort {
public static void main(String[] args) {
Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };
System.out.println("before: " + Arrays.toString(array));
cocktailSort(array);
System.out.println("after: " + Arrays.toString(array));
}
public static void cocktailSort(Object[] array) {
int begin = 0;
int end = array.length;
if (end == 0)
return;
for (--end; begin < end; ) {
int new_begin = end;
int new_end = begin;
for (int i = begin; i < end; ++i) {
Comparable c1 = (Comparable)array[i];
Comparable c2 = (Comparable)array[i + 1];
if (c1.compareTo(c2) > 0) {
swap(array, i, i + 1);
new_end = i;
}
}
end = new_end;
for (int i = end; i > begin; --i) {
Comparable c1 = (Comparable)array[i - 1];
Comparable c2 = (Comparable)array[i];
if (c1.compareTo(c2) > 0) {
swap(array, i, i - 1);
new_begin = i;
}
}
begin = new_begin;
}
}
private static void swap(Object[] array, int i, int j) {
Object tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? |
def cocktailshiftingbounds(A):
beginIdx = 0
endIdx = len(A) - 1
while beginIdx <= endIdx:
newBeginIdx = endIdx
newEndIdx = beginIdx
for ii in range(beginIdx,endIdx):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
newEndIdx = ii
endIdx = newEndIdx
for ii in range(endIdx,beginIdx-1,-1):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
newBeginIdx = ii
beginIdx = newBeginIdx + 1
test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailshiftingbounds(test1)
print(test1)
test2=list('big fjords vex quick waltz nymph')
cocktailshiftingbounds(test2)
print(''.join(test2))
| import java.util.*;
public class CocktailSort {
public static void main(String[] args) {
Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 };
System.out.println("before: " + Arrays.toString(array));
cocktailSort(array);
System.out.println("after: " + Arrays.toString(array));
}
public static void cocktailSort(Object[] array) {
int begin = 0;
int end = array.length;
if (end == 0)
return;
for (--end; begin < end; ) {
int new_begin = end;
int new_end = begin;
for (int i = begin; i < end; ++i) {
Comparable c1 = (Comparable)array[i];
Comparable c2 = (Comparable)array[i + 1];
if (c1.compareTo(c2) > 0) {
swap(array, i, i + 1);
new_end = i;
}
}
end = new_end;
for (int i = end; i > begin; --i) {
Comparable c1 = (Comparable)array[i - 1];
Comparable c2 = (Comparable)array[i];
if (c1.compareTo(c2) > 0) {
swap(array, i, i - 1);
new_begin = i;
}
}
begin = new_begin;
}
}
private static void swap(Object[] array, int i, int j) {
Object tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
|
Change the following Python code into Java without altering its purpose. | import pygame, sys
from pygame.locals import *
from math import sin, cos, radians
pygame.init()
WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption("Pendulum")
screen = pygame.display.get_surface()
screen.fill((255,255,255))
PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)
SWINGLENGTH = PIVOT[1]*4
class BobMass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.theta = 45
self.dtheta = 0
self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),
PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),
1,1)
self.draw()
def recomputeAngle(self):
scaling = 3000.0/(SWINGLENGTH**2)
firstDDtheta = -sin(radians(self.theta))*scaling
midDtheta = self.dtheta + firstDDtheta
midtheta = self.theta + (self.dtheta + midDtheta)/2.0
midDDtheta = -sin(radians(midtheta))*scaling
midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2
midtheta = self.theta + (self.dtheta + midDtheta)/2
midDDtheta = -sin(radians(midtheta)) * scaling
lastDtheta = midDtheta + midDDtheta
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
lastDDtheta = -sin(radians(lasttheta)) * scaling
lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
self.dtheta = lastDtheta
self.theta = lasttheta
self.rect = pygame.Rect(PIVOT[0]-
SWINGLENGTH*sin(radians(self.theta)),
PIVOT[1]+
SWINGLENGTH*cos(radians(self.theta)),1,1)
def draw(self):
pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)
pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)
pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)
pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))
def update(self):
self.recomputeAngle()
screen.fill((255,255,255))
self.draw()
bob = BobMass()
TICK = USEREVENT + 2
pygame.time.set_timer(TICK, TIMETICK)
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == TICK:
bob.update()
while True:
input(pygame.event.get())
pygame.display.flip()
| import java.awt.*;
import javax.swing.*;
public class Pendulum extends JPanel implements Runnable {
private double angle = Math.PI / 2;
private int length;
public Pendulum(int length) {
this.length = length;
setDoubleBuffered(true);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
int ballX = anchorX + (int) (Math.sin(angle) * length);
int ballY = anchorY + (int) (Math.cos(angle) * length);
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
}
public void run() {
double angleAccel, angleVelocity = 0, dt = 0.1;
while (true) {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try { Thread.sleep(15); } catch (InterruptedException ex) {}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(2 * length + 50, length / 2 * 3);
}
public static void main(String[] args) {
JFrame f = new JFrame("Pendulum");
Pendulum p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | >>> def int2bin(n):
'From positive integer to list of binary bits, msb at index 0'
if n:
bits = []
while n:
n,remainder = divmod(n, 2)
bits.insert(0, remainder)
return bits
else: return [0]
>>> def bin2int(bits):
'From binary bits, msb at index 0 to integer'
i = 0
for bit in bits:
i = i * 2 + bit
return i
| public class Gray {
public static long grayEncode(long n){
return n ^ (n >>> 1);
}
public static long grayDecode(long n) {
long p = n;
while ((n >>>= 1) != 0)
p ^= n;
return p;
}
public static void main(String[] args){
System.out.println("i\tBinary\tGray\tDecoded");
for(int i = -1; i < 32;i++){
System.out.print(i +"\t");
System.out.print(Integer.toBinaryString(i) + "\t");
System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
System.out.println(grayDecode(grayEncode(i)));
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | >>> def int2bin(n):
'From positive integer to list of binary bits, msb at index 0'
if n:
bits = []
while n:
n,remainder = divmod(n, 2)
bits.insert(0, remainder)
return bits
else: return [0]
>>> def bin2int(bits):
'From binary bits, msb at index 0 to integer'
i = 0
for bit in bits:
i = i * 2 + bit
return i
| public class Gray {
public static long grayEncode(long n){
return n ^ (n >>> 1);
}
public static long grayDecode(long n) {
long p = n;
while ((n >>>= 1) != 0)
p ^= n;
return p;
}
public static void main(String[] args){
System.out.println("i\tBinary\tGray\tDecoded");
for(int i = -1; i < 32;i++){
System.out.print(i +"\t");
System.out.print(Integer.toBinaryString(i) + "\t");
System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
System.out.println(grayDecode(grayEncode(i)));
}
}
}
|
Change the following Python code into Java without altering its purpose. | >>> def int2bin(n):
'From positive integer to list of binary bits, msb at index 0'
if n:
bits = []
while n:
n,remainder = divmod(n, 2)
bits.insert(0, remainder)
return bits
else: return [0]
>>> def bin2int(bits):
'From binary bits, msb at index 0 to integer'
i = 0
for bit in bits:
i = i * 2 + bit
return i
| public class Gray {
public static long grayEncode(long n){
return n ^ (n >>> 1);
}
public static long grayDecode(long n) {
long p = n;
while ((n >>>= 1) != 0)
p ^= n;
return p;
}
public static void main(String[] args){
System.out.println("i\tBinary\tGray\tDecoded");
for(int i = -1; i < 32;i++){
System.out.print(i +"\t");
System.out.print(Integer.toBinaryString(i) + "\t");
System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
System.out.println(grayDecode(grayEncode(i)));
}
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | >>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
>>>
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
public class CreateFile {
public static void main(String[] args) throws IOException {
String os = System.getProperty("os.name");
if (os.contains("Windows")) {
Path path = Paths.get("tape.file");
Files.write(path, Collections.singletonList("Hello World!"));
} else {
Path path = Paths.get("/dev/tape");
Files.write(path, Collections.singletonList("Hello World!"));
}
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | def heapsort(lst):
for start in range((len(lst)-2)/2, -1, -1):
siftdown(lst, start, len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
siftdown(lst, 0, end - 1)
return lst
def siftdown(lst, start, end):
root = start
while True:
child = root * 2 + 1
if child > end: break
if child + 1 <= end and lst[child] < lst[child + 1]:
child += 1
if lst[root] < lst[child]:
lst[root], lst[child] = lst[child], lst[root]
root = child
else:
break
| public static void heapSort(int[] a){
int count = a.length;
heapify(a, count);
int end = count - 1;
while(end > 0){
int tmp = a[end];
a[end] = a[0];
a[0] = tmp;
siftDown(a, 0, end - 1);
end--;
}
}
public static void heapify(int[] a, int count){
int start = (count - 2) / 2;
while(start >= 0){
siftDown(a, start, count - 1);
start--;
}
}
public static void siftDown(int[] a, int start, int end){
int root = start;
while((root * 2 + 1) <= end){
int child = root * 2 + 1;
if(child + 1 <= end && a[child] < a[child + 1])
child = child + 1;
if(a[root] < a[child]){
int tmp = a[root];
a[root] = a[child];
a[child] = tmp;
root = child;
}else
return;
}
}
|
Please provide an equivalent version of this Python code in Java. | import random
class Card(object):
suits = ("Clubs","Hearts","Spades","Diamonds")
pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return "%s %s"%(self.pip,self.suit)
class Deck(object):
def __init__(self):
self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]
def __str__(self):
return "[%s]"%", ".join( (str(card) for card in self.deck))
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
self.shuffle()
return self.deck.pop(0)
| public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace }
|
Write the same algorithm in Java as shown in this Python implementation. | array = []
array.append(1)
array.append(3)
array[0] = 2
print array[0]
| Int[] literalArray = [1,2,3];
Int[] fixedLengthArray = new Int[10];
Int[] variableArray = new Int[];
assert literalArray.size == 3;
Int n = literalArray[2];
fixedLengthArray[4] = 12345;
fixedLengthArray += 6789;
variableArray += 6789;
|
Please provide an equivalent version of this Python code in Java. | def setup():
size(729, 729)
fill(0)
background(255)
noStroke()
rect(width / 3, height / 3, width / 3, width / 3)
rectangles(width / 3, height / 3, width / 3)
def rectangles(x, y, s):
if s < 1: return
xc, yc = x - s, y - s
for row in range(3):
for col in range(3):
if not (row == 1 and col == 1):
xx, yy = xc + row * s, yc + col * s
delta = s / 3
rect(xx + delta, yy + delta, delta, delta)
rectangles(xx + s / 3, yy + s / 3, s / 3)
| public static boolean inCarpet(long x, long y) {
while (x!=0 && y!=0) {
if (x % 3 == 1 && y % 3 == 1)
return false;
x /= 3;
y /= 3;
}
return true;
}
public static void carpet(final int n) {
final double power = Math.pow(3,n);
for(long i = 0; i < power; i++) {
for(long j = 0; j < power; j++) {
System.out.print(inCarpet(i, j) ? "*" : " ");
}
System.out.println();
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import random
def bogosort(l):
while not in_order(l):
random.shuffle(l)
return l
def in_order(l):
if not l:
return True
last = l[0]
for x in l[1:]:
if x < last:
return False
last = x
return True
| public class BogoSort
{
public static void main(String[] args)
{
int[] arr={4,5,6,0,7,8,9,1,2,3};
BogoSort now=new BogoSort();
System.out.print("Unsorted: ");
now.display1D(arr);
now.bogo(arr);
System.out.print("Sorted: ");
now.display1D(arr);
}
void bogo(int[] arr)
{
int shuffle=1;
for(;!isSorted(arr);shuffle++)
shuffle(arr);
System.out.println("This took "+shuffle+" shuffles.");
}
void shuffle(int[] arr)
{
int i=arr.length-1;
while(i>0)
swap(arr,i--,(int)(Math.random()*i));
}
void swap(int[] arr,int i,int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
boolean isSorted(int[] arr)
{
for(int i=1;i<arr.length;i++)
if(arr[i]<arr[i-1])
return false;
return true;
}
void display1D(int[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | def euler(f,y0,a,b,h):
t,y = a,y0
while t <= b:
print "%6.3f %6.3f" % (t,y)
t += h
y += h * f(t,y)
def newtoncooling(time, temp):
return -0.07 * (temp - 20)
euler(newtoncooling,100,0,100,10)
| public class Euler {
private static void euler (Callable f, double y0, int a, int b, int h) {
int t = a;
double y = y0;
while (t < b) {
System.out.println ("" + t + " " + y);
t += h;
y += h * f.compute (t, y);
}
System.out.println ("DONE");
}
public static void main (String[] args) {
Callable cooling = new Cooling ();
int[] steps = {2, 5, 10};
for (int stepSize : steps) {
System.out.println ("Step size: " + stepSize);
euler (cooling, 100.0, 0, 100, stepSize);
}
}
}
interface Callable {
public double compute (int time, double t);
}
class Cooling implements Callable {
public double compute (int time, double t) {
return -0.07 * (t - 20);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.