Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this Python function in Java with identical behavior. | print "Goodbye, World!"
| public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)
class Circle(object):
def __init__(self, center=None, radius=1.0):
self.center = center or Point()
self.radius = radius
def __repr__(self):
return '<Circle 0x%x x: %f y: %f radius: %f>' % (
id(self), self.center.x, self.center.y, self.radius)
| class Point {
protected int x, y;
public Point() { this(0); }
public Point(int x) { this(x, 0); }
public Point(int x, int y) { this.x = x; this.y = y; }
public Point(Point p) { this(p.x, p.y); }
public int getX() { return this.x; }
public int getY() { return this.y; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); }
}
class Circle extends Point {
private int r;
public Circle(Point p) { this(p, 0); }
public Circle(Point p, int r) { super(p); this.r = r; }
public Circle() { this(0); }
public Circle(int x) { this(x, 0); }
public Circle(int x, int y) { this(x, y, 0); }
public Circle(int x, int y, int r) { super(x, y); this.r = r; }
public Circle(Circle c) { this(c.x, c.y, c.r); }
public int getR() { return this.r; }
public void setR(int r) { this.r = r; }
public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); }
}
public class test {
public static void main(String args[]) {
Point p = new Point();
Point c = new Circle();
p.print();
c.print();
}
}
|
Change the following Python code into Java without altering its purpose. |
from sympy import isprime
def wagstaff(N):
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')
wagstaff(24)
| import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
}
|
Translate this program into Java but keep the logic exactly as in Python. |
from sympy import isprime
def wagstaff(N):
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')
wagstaff(24)
| import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. |
from sympy import isprime
def wagstaff(N):
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')
wagstaff(24)
| import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger d = new BigInteger("3"), a;
int lmt = 25, sl, c = 0;
for (int i = 3; i < 5808; ) {
a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
if (a.isProbablePrime(1)) {
System.out.printf("%2d %4d ", ++c, i);
String s = a.toString(); sl = s.length();
if (sl < lmt) System.out.println(a);
else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
}
i = BigInteger.valueOf(i).nextProbablePrime().intValue();
}
}
}
|
Generate an equivalent Java version of this Python code. | from collections import UserDict
import copy
class Dict(UserDict):
def __init__(self, dict=None, **kwargs):
self.__init = True
super().__init__(dict, **kwargs)
self.default = copy.deepcopy(self.data)
self.__init = False
def __delitem__(self, key):
if key in self.default:
self.data[key] = self.default[key]
else:
raise NotImplementedError
def __setitem__(self, key, item):
if self.__init:
super().__setitem__(key, item)
elif key in self.data:
self.data[key] = item
else:
raise KeyError
def __repr__(self):
return "%s(%s)" % (type(self).__name__, super().__repr__())
def fromkeys(cls, iterable, value=None):
if self.__init:
super().fromkeys(cls, iterable, value)
else:
for key in iterable:
if key in self.data:
self.data[key] = value
else:
raise KeyError
def clear(self):
self.data.update(copy.deepcopy(self.default))
def pop(self, key, default=None):
raise NotImplementedError
def popitem(self):
raise NotImplementedError
def update(self, E, **F):
if self.__init:
super().update(E, **F)
else:
haskeys = False
try:
keys = E.keys()
haskeys = Ture
except AttributeError:
pass
if haskeys:
for key in keys:
self[key] = E[key]
else:
for key, val in E:
self[key] = val
for key in F:
self[key] = F[key]
def setdefault(self, key, default=None):
if key not in self.data:
raise KeyError
else:
return super().setdefault(key, default)
| import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class ImmutableMap {
public static void main(String[] args) {
Map<String,Integer> hashMap = getImmutableMap();
try {
hashMap.put("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put new value.");
}
try {
hashMap.clear();
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to clear map.");
}
try {
hashMap.putIfAbsent("Test", 23);
}
catch (UnsupportedOperationException e) {
System.out.println("ERROR: Unable to put if absent.");
}
for ( String key : hashMap.keySet() ) {
System.out.printf("key = %s, value = %s%n", key, hashMap.get(key));
}
}
private static Map<String,Integer> getImmutableMap() {
Map<String,Integer> hashMap = new HashMap<>();
hashMap.put("Key 1", 34);
hashMap.put("Key 2", 105);
hashMap.put("Key 3", 144);
return Collections.unmodifiableMap(hashMap);
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. |
from math import floor, sqrt
from datetime import datetime
def main():
start = datetime.now()
for i in xrange(1, 10 ** 11):
if rare(i):
print "found a rare:", i
end = datetime.now()
print "time elapsed:", end - start
def is_square(n):
s = floor(sqrt(n + 0.5))
return s * s == n
def reverse(n):
return int(str(n)[::-1])
def is_palindrome(n):
return n == reverse(n)
def rare(n):
r = reverse(n)
return (
not is_palindrome(n) and
n > r and
is_square(n+r) and is_square(n-r)
)
if __name__ == '__main__':
main()
| import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class RareNumbers {
public interface Consumer5<A, B, C, D, E> {
void apply(A a, B b, C c, D d, E e);
}
public interface Consumer7<A, B, C, D, E, F, G> {
void apply(A a, B b, C c, D d, E e, F f, G g);
}
public interface Recursable5<A, B, C, D, E> {
void apply(A a, B b, C c, D d, E e, Recursable5<A, B, C, D, E> r);
}
public interface Recursable7<A, B, C, D, E, F, G> {
void apply(A a, B b, C c, D d, E e, F f, G g, Recursable7<A, B, C, D, E, F, G> r);
}
public static <A, B, C, D, E> Consumer5<A, B, C, D, E> recurse(Recursable5<A, B, C, D, E> r) {
return (a, b, c, d, e) -> r.apply(a, b, c, d, e, r);
}
public static <A, B, C, D, E, F, G> Consumer7<A, B, C, D, E, F, G> recurse(Recursable7<A, B, C, D, E, F, G> r) {
return (a, b, c, d, e, f, g) -> r.apply(a, b, c, d, e, f, g, r);
}
private static class Term {
long coeff;
byte ix1, ix2;
public Term(long coeff, byte ix1, byte ix2) {
this.coeff = coeff;
this.ix1 = ix1;
this.ix2 = ix2;
}
}
private static final int MAX_DIGITS = 16;
private static long toLong(List<Byte> digits, boolean reverse) {
long sum = 0;
if (reverse) {
for (int i = digits.size() - 1; i >= 0; --i) {
sum = sum * 10 + digits.get(i);
}
} else {
for (Byte digit : digits) {
sum = sum * 10 + digit;
}
}
return sum;
}
private static boolean isNotSquare(long n) {
long root = (long) Math.sqrt(n);
return root * root != n;
}
private static List<Byte> seq(byte from, byte to, byte step) {
List<Byte> res = new ArrayList<>();
for (byte i = from; i <= to; i += step) {
res.add(i);
}
return res;
}
private static String commatize(long n) {
String s = String.valueOf(n);
int le = s.length();
int i = le - 3;
while (i >= 1) {
s = s.substring(0, i) + "," + s.substring(i);
i -= 3;
}
return s;
}
public static void main(String[] args) {
final LocalDateTime startTime = LocalDateTime.now();
long pow = 1L;
System.out.println("Aggregate timings to process all numbers up to:");
List<List<Term>> allTerms = new ArrayList<>();
for (int i = 0; i < MAX_DIGITS - 1; ++i) {
allTerms.add(new ArrayList<>());
}
for (int r = 2; r <= MAX_DIGITS; ++r) {
List<Term> terms = new ArrayList<>();
pow *= 10;
long pow1 = pow;
long pow2 = 1;
byte i1 = 0;
byte i2 = (byte) (r - 1);
while (i1 < i2) {
terms.add(new Term(pow1 - pow2, i1, i2));
pow1 /= 10;
pow2 *= 10;
i1++;
i2--;
}
allTerms.set(r - 2, terms);
}
Map<Byte, List<List<Byte>>> fml = Map.of(
(byte) 0, List.of(List.of((byte) 2, (byte) 2), List.of((byte) 8, (byte) 8)),
(byte) 1, List.of(List.of((byte) 6, (byte) 5), List.of((byte) 8, (byte) 7)),
(byte) 4, List.of(List.of((byte) 4, (byte) 0)),
(byte) 6, List.of(List.of((byte) 6, (byte) 0), List.of((byte) 8, (byte) 2))
);
Map<Byte, List<List<Byte>>> dmd = new HashMap<>();
for (int i = 0; i < 100; ++i) {
List<Byte> a = List.of((byte) (i / 10), (byte) (i % 10));
int d = a.get(0) - a.get(1);
dmd.computeIfAbsent((byte) d, k -> new ArrayList<>()).add(a);
}
List<Byte> fl = List.of((byte) 0, (byte) 1, (byte) 4, (byte) 6);
List<Byte> dl = seq((byte) -9, (byte) 9, (byte) 1);
List<Byte> zl = List.of((byte) 0);
List<Byte> el = seq((byte) -8, (byte) 8, (byte) 2);
List<Byte> ol = seq((byte) -9, (byte) 9, (byte) 2);
List<Byte> il = seq((byte) 0, (byte) 9, (byte) 1);
List<Long> rares = new ArrayList<>();
List<List<List<Byte>>> lists = new ArrayList<>();
for (int i = 0; i < 4; ++i) {
lists.add(new ArrayList<>());
}
for (int i = 0; i < fl.size(); ++i) {
List<List<Byte>> temp1 = new ArrayList<>();
List<Byte> temp2 = new ArrayList<>();
temp2.add(fl.get(i));
temp1.add(temp2);
lists.set(i, temp1);
}
final AtomicReference<List<Byte>> digits = new AtomicReference<>(new ArrayList<>());
AtomicInteger count = new AtomicInteger();
Consumer7<List<Byte>, List<Byte>, List<List<Byte>>, List<List<Byte>>, Long, Integer, Integer> fnpr = recurse((cand, di, dis, indicies, nmr, nd, level, func) -> {
if (level == dis.size()) {
digits.get().set(indicies.get(0).get(0), fml.get(cand.get(0)).get(di.get(0)).get(0));
digits.get().set(indicies.get(0).get(1), fml.get(cand.get(0)).get(di.get(0)).get(1));
int le = di.size();
if (nd % 2 == 1) {
le--;
digits.get().set(nd / 2, di.get(le));
}
for (int i = 1; i < le; ++i) {
digits.get().set(indicies.get(i).get(0), dmd.get(cand.get(i)).get(di.get(i)).get(0));
digits.get().set(indicies.get(i).get(1), dmd.get(cand.get(i)).get(di.get(i)).get(1));
}
long r = toLong(digits.get(), true);
long npr = nmr + 2 * r;
if (isNotSquare(npr)) {
return;
}
count.getAndIncrement();
System.out.printf(" R/N %2d:", count.get());
LocalDateTime checkPoint = LocalDateTime.now();
long elapsed = Duration.between(startTime, checkPoint).toMillis();
System.out.printf(" %9sms", elapsed);
long n = toLong(digits.get(), false);
System.out.printf(" (%s)\n", commatize(n));
rares.add(n);
} else {
for (Byte num : dis.get(level)) {
di.set(level, num);
func.apply(cand, di, dis, indicies, nmr, nd, level + 1, func);
}
}
});
Consumer5<List<Byte>, List<List<Byte>>, List<List<Byte>>, Integer, Integer> fnmr = recurse((cand, list, indicies, nd, level, func) -> {
if (level == list.size()) {
long nmr = 0;
long nmr2 = 0;
List<Term> terms = allTerms.get(nd - 2);
for (int i = 0; i < terms.size(); ++i) {
Term t = terms.get(i);
if (cand.get(i) >= 0) {
nmr += t.coeff * cand.get(i);
} else {
nmr2 += t.coeff * -cand.get(i);
if (nmr >= nmr2) {
nmr -= nmr2;
nmr2 = 0;
} else {
nmr2 -= nmr;
nmr = 0;
}
}
}
if (nmr2 >= nmr) {
return;
}
nmr -= nmr2;
if (isNotSquare(nmr)) {
return;
}
List<List<Byte>> dis = new ArrayList<>();
dis.add(seq((byte) 0, (byte) (fml.get(cand.get(0)).size() - 1), (byte) 1));
for (int i = 1; i < cand.size(); ++i) {
dis.add(seq((byte) 0, (byte) (dmd.get(cand.get(i)).size() - 1), (byte) 1));
}
if (nd % 2 == 1) {
dis.add(il);
}
List<Byte> di = new ArrayList<>();
for (int i = 0; i < dis.size(); ++i) {
di.add((byte) 0);
}
fnpr.apply(cand, di, dis, indicies, nmr, nd, 0);
} else {
for (Byte num : list.get(level)) {
cand.set(level, num);
func.apply(cand, list, indicies, nd, level + 1, func);
}
}
});
for (int nd = 2; nd <= MAX_DIGITS; ++nd) {
digits.set(new ArrayList<>());
for (int i = 0; i < nd; ++i) {
digits.get().add((byte) 0);
}
if (nd == 4) {
lists.get(0).add(zl);
lists.get(1).add(ol);
lists.get(2).add(el);
lists.get(3).add(ol);
} else if (allTerms.get(nd - 2).size() > lists.get(0).size()) {
for (int i = 0; i < 4; ++i) {
lists.get(i).add(dl);
}
}
List<List<Byte>> indicies = new ArrayList<>();
for (Term t : allTerms.get(nd - 2)) {
indicies.add(List.of(t.ix1, t.ix2));
}
for (List<List<Byte>> list : lists) {
List<Byte> cand = new ArrayList<>();
for (int i = 0; i < list.size(); ++i) {
cand.add((byte) 0);
}
fnmr.apply(cand, list, indicies, nd, 0);
}
LocalDateTime checkPoint = LocalDateTime.now();
long elapsed = Duration.between(startTime, checkPoint).toMillis();
System.out.printf(" %2d digits: %9sms\n", nd, elapsed);
}
Collections.sort(rares);
System.out.printf("\nThe rare numbers with up to %d digits are:\n", MAX_DIGITS);
for (int i = 0; i < rares.size(); ++i) {
System.out.printf(" %2d: %25s\n", i + 1, commatize(rares.get(i)));
}
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(self):
return self.v
class Yaccer(object):
def __init__(self):
self.operstak = []
self.nodestak =[]
self.__dict__.update(self.state1)
def v1( self, valStrg ):
self.nodestak.append( LeafNode(valStrg))
self.__dict__.update(self.state2)
def o2( self, operchar ):
def openParen(a,b):
return 0
opDict= { '+': ( operator.add, 2, 2 ),
'-': (operator.sub, 2, 2 ),
'*': (operator.mul, 3, 3 ),
'/': (operator.div, 3, 3 ),
'^': ( pow, 4, 5 ),
'(': ( openParen, 0, 8 )
}
operPrecidence = opDict[operchar][2]
self.redeuce(operPrecidence)
self.operstak.append(opDict[operchar])
self.__dict__.update(self.state1)
def syntaxErr(self, char ):
print 'parse error - near operator "%s"' %char
def pc2( self,operchar ):
self.redeuce( 1 )
if len(self.operstak)>0:
self.operstak.pop()
else:
print 'Error - no open parenthesis matches close parens.'
self.__dict__.update(self.state2)
def end(self):
self.redeuce(0)
return self.nodestak.pop()
def redeuce(self, precidence):
while len(self.operstak)>0:
tailOper = self.operstak[-1]
if tailOper[1] < precidence: break
tailOper = self.operstak.pop()
vrgt = self.nodestak.pop()
vlft= self.nodestak.pop()
self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }
def Lex( exprssn, p ):
bgn = None
cp = -1
for c in exprssn:
cp += 1
if c in '+-/*^()':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if c=='(': p.po(p, c)
elif c==')':p.pc(p, c)
else: p.o(p, c)
elif c in ' \t':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
elif c in '0123456789':
if bgn is None:
bgn = cp
else:
print 'Invalid character in expression'
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if bgn is not None:
p.v(p, exprssn[bgn:cp+1])
bgn = None
return p.end()
expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()
| import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(self):
return self.v
class Yaccer(object):
def __init__(self):
self.operstak = []
self.nodestak =[]
self.__dict__.update(self.state1)
def v1( self, valStrg ):
self.nodestak.append( LeafNode(valStrg))
self.__dict__.update(self.state2)
def o2( self, operchar ):
def openParen(a,b):
return 0
opDict= { '+': ( operator.add, 2, 2 ),
'-': (operator.sub, 2, 2 ),
'*': (operator.mul, 3, 3 ),
'/': (operator.div, 3, 3 ),
'^': ( pow, 4, 5 ),
'(': ( openParen, 0, 8 )
}
operPrecidence = opDict[operchar][2]
self.redeuce(operPrecidence)
self.operstak.append(opDict[operchar])
self.__dict__.update(self.state1)
def syntaxErr(self, char ):
print 'parse error - near operator "%s"' %char
def pc2( self,operchar ):
self.redeuce( 1 )
if len(self.operstak)>0:
self.operstak.pop()
else:
print 'Error - no open parenthesis matches close parens.'
self.__dict__.update(self.state2)
def end(self):
self.redeuce(0)
return self.nodestak.pop()
def redeuce(self, precidence):
while len(self.operstak)>0:
tailOper = self.operstak[-1]
if tailOper[1] < precidence: break
tailOper = self.operstak.pop()
vrgt = self.nodestak.pop()
vlft= self.nodestak.pop()
self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }
def Lex( exprssn, p ):
bgn = None
cp = -1
for c in exprssn:
cp += 1
if c in '+-/*^()':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if c=='(': p.po(p, c)
elif c==')':p.pc(p, c)
else: p.o(p, c)
elif c in ' \t':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
elif c in '0123456789':
if bgn is None:
bgn = cp
else:
print 'Invalid character in expression'
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if bgn is not None:
p.v(p, exprssn[bgn:cp+1])
bgn = None
return p.end()
expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()
| import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
}
|
Write a version of this Python function in Java with identical behavior. | names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
| import java.util.Arrays;
public class SpecialVariables {
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
System.out.println(SpecialVariables.class);
System.out.println(System.getenv());
System.out.println(System.getProperties());
System.out.println(Runtime.getRuntime().availableProcessors());
}
}
|
Keep all operations the same but rewrite the snippet in Java. | import sys
def fatal_error(errtext):
print("%" + errtext)
print("usage: " + sys.argv[0] + " [filename.cp]")
sys.exit(1)
fname = None
source = None
try:
fname = sys.argv[1]
source = open(fname).read()
except:
fatal_error("error while trying to read from specified file")
lines = source.split("\n")
clipboard = ""
loc = 0
while(loc < len(lines)):
command = lines[loc].strip()
try:
if(command == "Copy"):
clipboard += lines[loc + 1]
elif(command == "CopyFile"):
if(lines[loc + 1] == "TheF*ckingCode"):
clipboard += source
else:
filetext = open(lines[loc+1]).read()
clipboard += filetext
elif(command == "Duplicate"):
clipboard += clipboard * ((int(lines[loc + 1])) - 1)
elif(command == "Pasta!"):
print(clipboard)
sys.exit(0)
else:
fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1))
except Exception as e:
fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e)
loc += 2
| import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
public class Copypasta
{
public static void fatal_error(String errtext)
{
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
StackTraceElement main = stack[stack.length - 1];
String mainClass = main.getClassName();
System.out.println("%" + errtext);
System.out.println("usage: " + mainClass + " [filename.cp]");
System.exit(1);
}
public static void main(String[] args)
{
String fname = null;
String source = null;
try
{
fname = args[0];
source = new String(Files.readAllBytes(new File(fname).toPath()));
}
catch(Exception e)
{
fatal_error("error while trying to read from specified file");
}
ArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split("\n")));
String clipboard = "";
int loc = 0;
while(loc < lines.size())
{
String command = lines.get(loc).trim();
try
{
if(command.equals("Copy"))
clipboard += lines.get(loc + 1);
else if(command.equals("CopyFile"))
{
if(lines.get(loc + 1).equals("TheF*ckingCode"))
clipboard += source;
else
{
String filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));
clipboard += filetext;
}
}
else if(command.equals("Duplicate"))
{
String origClipboard = clipboard;
int amount = Integer.parseInt(lines.get(loc + 1)) - 1;
for(int i = 0; i < amount; i++)
clipboard += origClipboard;
}
else if(command.equals("Pasta!"))
{
System.out.println(clipboard);
System.exit(0);
}
else
fatal_error("unknown command '" + command + "' encountered on line " + new Integer(loc + 1).toString());
}
catch(Exception e)
{
fatal_error("error while executing command '" + command + "' on line " + new Integer(loc + 1).toString());
}
loc += 2;
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
__rePrivate = re.compile('^_(Child|Parent)__')
__reBleh = re.compile('\Wbleh$')
@property
def reBleh(self):
return self.__reBleh
def __init__(self, name, *args):
super(Child, self).__init__(name)
self.args = args
def __dir__(self):
myDir = filter(
lambda p: not self.__rePrivate.match(p),
list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
)))
return myDir + map(
lambda p: p + '_bleh',
filter(
lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),
myDir))
def __getattr__(self, name):
if name[-5:] == '_bleh':
return str(getattr(self, name[:-5])) + ' bleh'
if hasattr(super(Child, chld), '__getattr__'):
return super(Child, self).__getattr__(name)
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __setattr__(self, name, value):
if name[-5:] == '_bleh':
if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):
setattr(self, name[:-5], self.reBleh.sub('', value))
elif hasattr(super(Child, self), '__setattr__'):
super(Child, self).__setattr__(name, value)
elif hasattr(self, '__dict__'):
self.__dict__[name] = value
def __repr__(self):
return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))
def doStuff(self):
return (1+1.0/1e6) ** 1e6
par = Parent('par')
par.parent = True
dir(par)
inspect.getmembers(par)
chld = Child('chld', 0, 'I', 'two')
chld.own = "chld's own"
dir(chld)
inspect.getmembers(chld)
| import java.lang.reflect.Field;
public class ListFields {
public int examplePublicField = 42;
private boolean examplePrivateField = true;
public static void main(String[] args) throws IllegalAccessException {
ListFields obj = new ListFields();
Class clazz = obj.getClass();
System.out.println("All public fields (including inherited):");
for (Field f : clazz.getFields()) {
System.out.printf("%s\t%s\n", f, f.get(obj));
}
System.out.println();
System.out.println("All declared fields (excluding inherited):");
for (Field f : clazz.getDeclaredFields()) {
System.out.printf("%s\t%s\n", f, f.get(obj));
}
}
}
|
Change the following Python code into Java without altering its purpose. | from functools import lru_cache
DIVS = {2, 3}
SUBS = {1}
class Minrec():
"Recursive, memoised minimised steps to 1"
def __init__(self, divs=DIVS, subs=SUBS):
self.divs, self.subs = divs, subs
@lru_cache(maxsize=None)
def _minrec(self, n):
"Recursive, memoised"
if n == 1:
return 0, ['=1']
possibles = {}
for d in self.divs:
if n % d == 0:
possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)
for s in self.subs:
if n > s:
possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)
thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])
ret = 1 + count, [thiskind] + otherkinds
return ret
def __call__(self, n):
"Recursive, memoised"
ans = self._minrec(n)[1][:-1]
return len(ans), ans
if __name__ == '__main__':
for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:
minrec = Minrec(DIVS, SUBS)
print('\nMINIMUM STEPS TO 1: Recursive algorithm')
print(' Possible divisors: ', DIVS)
print(' Possible decrements:', SUBS)
for n in range(1, 11):
steps, how = minrec(n)
print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how))
upto = 2000
print(f'\n Those numbers up to {upto} that take the maximum, "minimal steps down to 1":')
stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))
mx = stepn[-1][0]
ans = [x[1] for x in stepn if x[0] == mx]
print(' Taking', mx, f'steps is/are the {len(ans)} numbers:',
', '.join(str(n) for n in sorted(ans)))
print()
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MinimalStepsDownToOne {
public static void main(String[] args) {
runTasks(getFunctions1());
runTasks(getFunctions2());
runTasks(getFunctions3());
}
private static void runTasks(List<Function> functions) {
Map<Integer,List<String>> minPath = getInitialMap(functions, 5);
int max = 10;
populateMap(minPath, functions, max);
System.out.printf("%nWith functions: %s%n", functions);
System.out.printf(" Minimum steps to 1:%n");
for ( int n = 2 ; n <= max ; n++ ) {
int steps = minPath.get(n).size();
System.out.printf(" %2d: %d step%1s: %s%n", n, steps, steps == 1 ? "" : "s", minPath.get(n));
}
displayMaxMin(minPath, functions, 2000);
displayMaxMin(minPath, functions, 20000);
displayMaxMin(minPath, functions, 100000);
}
private static void displayMaxMin(Map<Integer,List<String>> minPath, List<Function> functions, int max) {
populateMap(minPath, functions, max);
List<Integer> maxIntegers = getMaxMin(minPath, max);
int maxSteps = maxIntegers.remove(0);
int numCount = maxIntegers.size();
System.out.printf(" There %s %d number%s in the range 1-%d that have maximum 'minimal steps' of %d:%n %s%n", numCount == 1 ? "is" : "are", numCount, numCount == 1 ? "" : "s", max, maxSteps, maxIntegers);
}
private static List<Integer> getMaxMin(Map<Integer,List<String>> minPath, int max) {
int maxSteps = Integer.MIN_VALUE;
List<Integer> maxIntegers = new ArrayList<Integer>();
for ( int n = 2 ; n <= max ; n++ ) {
int len = minPath.get(n).size();
if ( len > maxSteps ) {
maxSteps = len;
maxIntegers.clear();
maxIntegers.add(n);
}
else if ( len == maxSteps ) {
maxIntegers.add(n);
}
}
maxIntegers.add(0, maxSteps);
return maxIntegers;
}
private static void populateMap(Map<Integer,List<String>> minPath, List<Function> functions, int max) {
for ( int n = 2 ; n <= max ; n++ ) {
if ( minPath.containsKey(n) ) {
continue;
}
Function minFunction = null;
int minSteps = Integer.MAX_VALUE;
for ( Function f : functions ) {
if ( f.actionOk(n) ) {
int result = f.action(n);
int steps = 1 + minPath.get(result).size();
if ( steps < minSteps ) {
minFunction = f;
minSteps = steps;
}
}
}
int result = minFunction.action(n);
List<String> path = new ArrayList<String>();
path.add(minFunction.toString(n));
path.addAll(minPath.get(result));
minPath.put(n, path);
}
}
private static Map<Integer,List<String>> getInitialMap(List<Function> functions, int max) {
Map<Integer,List<String>> minPath = new HashMap<>();
for ( int i = 2 ; i <= max ; i++ ) {
for ( Function f : functions ) {
if ( f.actionOk(i) ) {
int result = f.action(i);
if ( result == 1 ) {
List<String> path = new ArrayList<String>();
path.add(f.toString(i));
minPath.put(i, path);
}
}
}
}
return minPath;
}
private static List<Function> getFunctions3() {
List<Function> functions = new ArrayList<>();
functions.add(new Divide2Function());
functions.add(new Divide3Function());
functions.add(new Subtract2Function());
functions.add(new Subtract1Function());
return functions;
}
private static List<Function> getFunctions2() {
List<Function> functions = new ArrayList<>();
functions.add(new Divide3Function());
functions.add(new Divide2Function());
functions.add(new Subtract2Function());
return functions;
}
private static List<Function> getFunctions1() {
List<Function> functions = new ArrayList<>();
functions.add(new Divide3Function());
functions.add(new Divide2Function());
functions.add(new Subtract1Function());
return functions;
}
public abstract static class Function {
abstract public int action(int n);
abstract public boolean actionOk(int n);
abstract public String toString(int n);
}
public static class Divide2Function extends Function {
@Override public int action(int n) {
return n/2;
}
@Override public boolean actionOk(int n) {
return n % 2 == 0;
}
@Override public String toString(int n) {
return "/2 -> " + n/2;
}
@Override public String toString() {
return "Divisor 2";
}
}
public static class Divide3Function extends Function {
@Override public int action(int n) {
return n/3;
}
@Override public boolean actionOk(int n) {
return n % 3 == 0;
}
@Override public String toString(int n) {
return "/3 -> " + n/3;
}
@Override public String toString() {
return "Divisor 3";
}
}
public static class Subtract1Function extends Function {
@Override public int action(int n) {
return n-1;
}
@Override public boolean actionOk(int n) {
return true;
}
@Override public String toString(int n) {
return "-1 -> " + (n-1);
}
@Override public String toString() {
return "Subtractor 1";
}
}
public static class Subtract2Function extends Function {
@Override public int action(int n) {
return n-2;
}
@Override public boolean actionOk(int n) {
return n > 2;
}
@Override public String toString(int n) {
return "-2 -> " + (n-2);
}
@Override public String toString() {
return "Subtractor 2";
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | from itertools import zip_longest
txt =
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col)
for col in zip_longest(*parts, fillvalue='')]
for justify in "<_Left ^_Center >_Right".split():
j, jtext = justify.split('_')
print(f"{jtext} column-aligned output:\n")
for line in parts:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
| import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class ColumnAligner {
private List<String[]> words = new ArrayList<>();
private int columns = 0;
private List<Integer> columnWidths = new ArrayList<>();
public ColumnAligner(String s) {
String[] lines = s.split("\\n");
for (String line : lines) {
processInputLine(line);
}
}
public ColumnAligner(List<String> lines) {
for (String line : lines) {
processInputLine(line);
}
}
private void processInputLine(String line) {
String[] lineWords = line.split("\\$");
words.add(lineWords);
columns = Math.max(columns, lineWords.length);
for (int i = 0; i < lineWords.length; i++) {
String word = lineWords[i];
if (i >= columnWidths.size()) {
columnWidths.add(word.length());
} else {
columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));
}
}
}
interface AlignFunction {
String align(String s, int length);
}
public String alignLeft() {
return align(new AlignFunction() {
@Override
public String align(String s, int length) {
return StringUtils.rightPad(s, length);
}
});
}
public String alignRight() {
return align(new AlignFunction() {
@Override
public String align(String s, int length) {
return StringUtils.leftPad(s, length);
}
});
}
public String alignCenter() {
return align(new AlignFunction() {
@Override
public String align(String s, int length) {
return StringUtils.center(s, length);
}
});
}
private String align(AlignFunction a) {
StringBuilder result = new StringBuilder();
for (String[] lineWords : words) {
for (int i = 0; i < lineWords.length; i++) {
String word = lineWords[i];
if (i == 0) {
result.append("|");
}
result.append(a.align(word, columnWidths.get(i)) + "|");
}
result.append("\n");
}
return result.toString();
}
public static void main(String args[]) throws IOException {
if (args.length < 1) {
System.out.println("Usage: ColumnAligner file [left|right|center]");
return;
}
String filePath = args[0];
String alignment = "left";
if (args.length >= 2) {
alignment = args[1];
}
ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));
switch (alignment) {
case "left":
System.out.print(ca.alignLeft());
break;
case "right":
System.out.print(ca.alignRight());
break;
case "center":
System.out.print(ca.alignCenter());
break;
default:
System.err.println(String.format("Error! Unknown alignment: '%s'", alignment));
break;
}
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | import urllib.parse as up
url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1
print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
print('url.query = ', url.query)
print('url.fragment = ', url.fragment)
print('url.username = ', url.username)
print('url.password = ', url.password)
| import java.net.URI;
import java.net.URISyntaxException;
public class WebAddressParser{
public static void main(String[] args){
parseAddress("foo:
parseAddress("urn:example:animal:ferret:nose");
}
static void parseAddress(String a){
System.out.println("Parsing " + a);
try{
URI u = new URI(a);
System.out.println("\tscheme = " + u.getScheme());
System.out.println("\tdomain = " + u.getHost());
System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort()));
System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));
System.out.println("\tquery = " + u.getQuery());
System.out.println("\tfragment = " + u.getFragment());
}
catch (URISyntaxException x){
System.err.println("Oops: " + x);
}
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | import urllib.parse as up
url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1
print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
print('url.query = ', url.query)
print('url.fragment = ', url.fragment)
print('url.username = ', url.username)
print('url.password = ', url.password)
| import java.net.URI;
import java.net.URISyntaxException;
public class WebAddressParser{
public static void main(String[] args){
parseAddress("foo:
parseAddress("urn:example:animal:ferret:nose");
}
static void parseAddress(String a){
System.out.println("Parsing " + a);
try{
URI u = new URI(a);
System.out.println("\tscheme = " + u.getScheme());
System.out.println("\tdomain = " + u.getHost());
System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort()));
System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));
System.out.println("\tquery = " + u.getQuery());
System.out.println("\tfragment = " + u.getFragment());
}
catch (URISyntaxException x){
System.err.println("Oops: " + x);
}
}
}
|
Write the same code in Java as shown below in Python. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("%-56d -> %s" % (s, b))
hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]
for num in hash_arr:
b = convertToBase58(num)
print("0x%-54x -> %s" % (num, b))
| import java.math.BigInteger;
import java.util.List;
public class Base58CheckEncoding {
private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
private static final BigInteger BIG0 = BigInteger.ZERO;
private static final BigInteger BIG58 = BigInteger.valueOf(58);
private static String convertToBase58(String hash) {
return convertToBase58(hash, 16);
}
private static String convertToBase58(String hash, int base) {
BigInteger x;
if (base == 16 && hash.substring(0, 2).equals("0x")) {
x = new BigInteger(hash.substring(2), 16);
} else {
x = new BigInteger(hash, base);
}
StringBuilder sb = new StringBuilder();
while (x.compareTo(BIG0) > 0) {
int r = x.mod(BIG58).intValue();
sb.append(ALPHABET.charAt(r));
x = x.divide(BIG58);
}
return sb.reverse().toString();
}
public static void main(String[] args) {
String s = "25420294593250030202636073700053352635053786165627414518";
String b = convertToBase58(s, 10);
System.out.printf("%s -> %s\n", s, b);
List<String> hashes = List.of(
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e"
);
for (String hash : hashes) {
String b58 = convertToBase58(hash);
System.out.printf("%-56s -> %s\n", hash, b58);
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("%-56d -> %s" % (s, b))
hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]
for num in hash_arr:
b = convertToBase58(num)
print("0x%-54x -> %s" % (num, b))
| import java.math.BigInteger;
import java.util.List;
public class Base58CheckEncoding {
private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
private static final BigInteger BIG0 = BigInteger.ZERO;
private static final BigInteger BIG58 = BigInteger.valueOf(58);
private static String convertToBase58(String hash) {
return convertToBase58(hash, 16);
}
private static String convertToBase58(String hash, int base) {
BigInteger x;
if (base == 16 && hash.substring(0, 2).equals("0x")) {
x = new BigInteger(hash.substring(2), 16);
} else {
x = new BigInteger(hash, base);
}
StringBuilder sb = new StringBuilder();
while (x.compareTo(BIG0) > 0) {
int r = x.mod(BIG58).intValue();
sb.append(ALPHABET.charAt(r));
x = x.divide(BIG58);
}
return sb.reverse().toString();
}
public static void main(String[] args) {
String s = "25420294593250030202636073700053352635053786165627414518";
String b = convertToBase58(s, 10);
System.out.printf("%s -> %s\n", s, b);
List<String> hashes = List.of(
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e"
);
for (String hash : hashes) {
String b58 = convertToBase58(hash);
System.out.printf("%-56s -> %s\n", hash, b58);
}
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
| public static void main(String... args){
HashMap<String, Integer> vars = new HashMap<String, Integer>();
vars.put("Variable name", 3);
vars.put("Next variable name", 5);
Scanner sc = new Scanner(System.in);
String str = sc.next();
vars.put(str, sc.nextInt());
System.out.println(vars.get("Variable name"));
System.out.println(vars.get(str));
}
|
Produce a functionally identical Java code for the snippet given in Python. |
IP = (
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
)
IP_INV = (
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
)
PC1 = (
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
)
PC2 = (
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
)
E = (
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1
)
Sboxes = {
0: (
14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13
),
1: (
15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9
),
2: (
10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12
),
3: (
7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14
),
4: (
2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3
),
5: (
12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13
),
6: (
4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12
),
7: (
13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
)
}
P = (
16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25
)
def encrypt(msg, key, decrypt=False):
assert isinstance(msg, int) and isinstance(key, int)
assert not msg.bit_length() > 64
assert not key.bit_length() > 64
key = permutation_by_table(key, 64, PC1)
C0 = key >> 28
D0 = key & (2**28-1)
round_keys = generate_round_keys(C0, D0)
msg_block = permutation_by_table(msg, 64, IP)
L0 = msg_block >> 32
R0 = msg_block & (2**32-1)
L_last = L0
R_last = R0
for i in range(1,17):
if decrypt:
i = 17-i
L_round = R_last
R_round = L_last ^ round_function(R_last, round_keys[i])
L_last = L_round
R_last = R_round
cipher_block = (R_round<<32) + L_round
cipher_block = permutation_by_table(cipher_block, 64, IP_INV)
return cipher_block
def round_function(Ri, Ki):
Ri = permutation_by_table(Ri, 32, E)
Ri ^= Ki
Ri_blocks = [((Ri & (0b111111 << shift_val)) >> shift_val) for shift_val in (42,36,30,24,18,12,6,0)]
for i, block in enumerate(Ri_blocks):
row = ((0b100000 & block) >> 4) + (0b1 & block)
col = (0b011110 & block) >> 1
Ri_blocks[i] = Sboxes[i][16*row+col]
Ri_blocks = zip(Ri_blocks, (28,24,20,16,12,8,4,0))
Ri = 0
for block, lshift_val in Ri_blocks:
Ri += (block << lshift_val)
Ri = permutation_by_table(Ri, 32, P)
return Ri
def permutation_by_table(block, block_len, table):
block_str = bin(block)[2:].zfill(block_len)
perm = []
for pos in range(len(table)):
perm.append(block_str[table[pos]-1])
return int(''.join(perm), 2)
def generate_round_keys(C0, D0):
round_keys = dict.fromkeys(range(0,17))
lrot_values = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1)
lrot = lambda val, r_bits, max_bits: \
(val << r_bits%max_bits) & (2**max_bits-1) | \
((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits)))
C0 = lrot(C0, 0, 28)
D0 = lrot(D0, 0, 28)
round_keys[0] = (C0, D0)
for i, rot_val in enumerate(lrot_values):
i+=1
Ci = lrot(round_keys[i-1][0], rot_val, 28)
Di = lrot(round_keys[i-1][1], rot_val, 28)
round_keys[i] = (Ci, Di)
del round_keys[0]
for i, (Ci, Di) in round_keys.items():
Ki = (Ci << 28) + Di
round_keys[i] = permutation_by_table(Ki, 56, PC2)
return round_keys
k = 0x0e329232ea6d0d73
k2 = 0x133457799BBCDFF1
m = 0x8787878787878787
m2 = 0x0123456789ABCDEF
def prove(key, msg):
print('key: {:x}'.format(key))
print('message: {:x}'.format(msg))
cipher_text = encrypt(msg, key)
print('encrypted: {:x}'.format(cipher_text))
plain_text = encrypt(cipher_text, key, decrypt=True)
print('decrypted: {:x}'.format(plain_text))
prove(k, m)
print('----------')
prove(k2, m2)
| import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class DataEncryptionStandard {
private static byte[] toHexByteArray(String self) {
byte[] bytes = new byte[self.length() / 2];
for (int i = 0; i < bytes.length; ++i) {
bytes[i] = ((byte) Integer.parseInt(self.substring(i * 2, i * 2 + 2), 16));
}
return bytes;
}
private static void printHexBytes(byte[] self, String label) {
System.out.printf("%s: ", label);
for (byte b : self) {
int bb = (b >= 0) ? ((int) b) : b + 256;
String ts = Integer.toString(bb, 16);
if (ts.length() < 2) {
ts = "0" + ts;
}
System.out.print(ts);
}
System.out.println();
}
public static void main(String[] args) throws Exception {
String strKey = "0e329232ea6d0d73";
byte[] keyBytes = toHexByteArray(strKey);
SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
Cipher encCipher = Cipher.getInstance("DES");
encCipher.init(Cipher.ENCRYPT_MODE, key);
String strPlain = "8787878787878787";
byte[] plainBytes = toHexByteArray(strPlain);
byte[] encBytes = encCipher.doFinal(plainBytes);
printHexBytes(encBytes, "Encoded");
Cipher decCipher = Cipher.getInstance("DES");
decCipher.init(Cipher.DECRYPT_MODE, key);
byte[] decBytes = decCipher.doFinal(encBytes);
printHexBytes(decBytes, "Decoded");
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | class Head():
def __init__(self, lo, hi=None, shift=0):
if hi is None: hi = lo
d = hi - lo
ds, ls, hs = str(d), str(lo), str(hi)
if d and len(ls) > len(ds):
assert(len(ls) - len(ds) + 1 > 21)
lo = int(str(lo)[:len(ls) - len(ds) + 1])
hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1
shift += len(ds) - 1
elif len(ls) > 100:
lo = int(str(ls)[:100])
hi = lo + 1
shift = len(ls) - 100
self.lo, self.hi, self.shift = lo, hi, shift
def __mul__(self, other):
lo = self.lo*other.lo
hi = self.hi*other.hi
shift = self.shift + other.shift
return Head(lo, hi, shift)
def __add__(self, other):
if self.shift < other.shift:
return other + self
sh = self.shift - other.shift
if sh >= len(str(other.hi)):
return Head(self.lo, self.hi, self.shift)
ls = str(other.lo)
hs = str(other.hi)
lo = self.lo + int(ls[:len(ls)-sh])
hi = self.hi + int(hs[:len(hs)-sh])
return Head(lo, hi, self.shift)
def __repr__(self):
return str(self.hi)[:20]
class Tail():
def __init__(self, v):
self.v = int(f'{v:020d}'[-20:])
def __add__(self, other):
return Tail(self.v + other.v)
def __mul__(self, other):
return Tail(self.v*other.v)
def __repr__(self):
return f'{self.v:020d}'[-20:]
def mul(a, b):
return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]
def fibo(n, cls):
n -= 1
zero, one = cls(0), cls(1)
m = (one, one, zero)
e = (one, zero, one)
while n:
if n&1: e = mul(m, e)
m = mul(m, m)
n >>= 1
return f'{e[0]}'
for i in range(2, 10):
n = 10**i
print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))
for i in range(3, 8):
n = 2**i
s = f'2^{n}'
print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
| import java.math.BigInteger;
import java.util.Arrays;
public class FibonacciMatrixExponentiation {
public static void main(String[] args) {
BigInteger mod = BigInteger.TEN.pow(20);
for ( int exp : Arrays.asList(32, 64) ) {
System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));
}
for ( int i = 1 ; i <= 7 ; i++ ) {
BigInteger n = BigInteger.TEN.pow(i);
System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n)));
}
}
private static String displayFib(BigInteger fib) {
String s = fib.toString();
if ( s.length() <= 40 ) {
return s;
}
return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length());
}
private static BigInteger fib(BigInteger k) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes;
}
private static BigInteger fibMod(BigInteger k, BigInteger mod) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes.mod(mod);
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | class Head():
def __init__(self, lo, hi=None, shift=0):
if hi is None: hi = lo
d = hi - lo
ds, ls, hs = str(d), str(lo), str(hi)
if d and len(ls) > len(ds):
assert(len(ls) - len(ds) + 1 > 21)
lo = int(str(lo)[:len(ls) - len(ds) + 1])
hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1
shift += len(ds) - 1
elif len(ls) > 100:
lo = int(str(ls)[:100])
hi = lo + 1
shift = len(ls) - 100
self.lo, self.hi, self.shift = lo, hi, shift
def __mul__(self, other):
lo = self.lo*other.lo
hi = self.hi*other.hi
shift = self.shift + other.shift
return Head(lo, hi, shift)
def __add__(self, other):
if self.shift < other.shift:
return other + self
sh = self.shift - other.shift
if sh >= len(str(other.hi)):
return Head(self.lo, self.hi, self.shift)
ls = str(other.lo)
hs = str(other.hi)
lo = self.lo + int(ls[:len(ls)-sh])
hi = self.hi + int(hs[:len(hs)-sh])
return Head(lo, hi, self.shift)
def __repr__(self):
return str(self.hi)[:20]
class Tail():
def __init__(self, v):
self.v = int(f'{v:020d}'[-20:])
def __add__(self, other):
return Tail(self.v + other.v)
def __mul__(self, other):
return Tail(self.v*other.v)
def __repr__(self):
return f'{self.v:020d}'[-20:]
def mul(a, b):
return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2]
def fibo(n, cls):
n -= 1
zero, one = cls(0), cls(1)
m = (one, one, zero)
e = (one, zero, one)
while n:
if n&1: e = mul(m, e)
m = mul(m, m)
n >>= 1
return f'{e[0]}'
for i in range(2, 10):
n = 10**i
print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail))
for i in range(3, 8):
n = 2**i
s = f'2^{n}'
print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
| import java.math.BigInteger;
import java.util.Arrays;
public class FibonacciMatrixExponentiation {
public static void main(String[] args) {
BigInteger mod = BigInteger.TEN.pow(20);
for ( int exp : Arrays.asList(32, 64) ) {
System.out.printf("Last 20 digits of fib(2^%d) = %s%n", exp, fibMod(BigInteger.valueOf(2).pow(exp), mod));
}
for ( int i = 1 ; i <= 7 ; i++ ) {
BigInteger n = BigInteger.TEN.pow(i);
System.out.printf("fib(%,d) = %s%n", n, displayFib(fib(n)));
}
}
private static String displayFib(BigInteger fib) {
String s = fib.toString();
if ( s.length() <= 40 ) {
return s;
}
return s.substring(0, 20) + " ... " + s.subSequence(s.length()-20, s.length());
}
private static BigInteger fib(BigInteger k) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase));
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes));
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes));
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase));
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase));
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase));
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes;
}
private static BigInteger fibMod(BigInteger k, BigInteger mod) {
BigInteger aRes = BigInteger.ZERO;
BigInteger bRes = BigInteger.ONE;
BigInteger cRes = BigInteger.ONE;
BigInteger aBase = BigInteger.ZERO;
BigInteger bBase = BigInteger.ONE;
BigInteger cBase = BigInteger.ONE;
while ( k.compareTo(BigInteger.ZERO) > 0 ) {
if ( k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ONE) == 0 ) {
BigInteger temp1 = aRes.multiply(aBase).add(bRes.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bRes).add(bBase.multiply(cRes)).mod(mod);
BigInteger temp3 = bBase.multiply(bRes).add(cBase.multiply(cRes)).mod(mod);
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
k = k.shiftRight(1);
BigInteger temp1 = aBase.multiply(aBase).add(bBase.multiply(bBase)).mod(mod);
BigInteger temp2 = aBase.multiply(bBase).add(bBase.multiply(cBase)).mod(mod);
BigInteger temp3 = bBase.multiply(bBase).add(cBase.multiply(cBase)).mod(mod);
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes.mod(mod);
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | import re as RegEx
def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
outString = ""
strPos = 0
matches = RegEx.findall( "[0-9]*", _string )
for match in matches[:-1]:
if not match:
outString += _string[ strPos ]
strPos += 1
else:
if len(match) > _periodLen:
leadIn = match[:_startPos]
periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]
outString += leadIn + _separator.join( periods )
else:
outString += match
strPos += len( match )
return outString
print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) )
print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." ))
print ( Commatize( "\"-in Aus$+1411.8millions\"" ))
print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" ))
print ( Commatize( "123.e8000 is pretty big." ))
print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." ))
print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." ))
print ( Commatize( "James was never known as 0000000007" ))
print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." ))
print ( Commatize( "␢␢␢$-140000±100 millions." ))
print ( Commatize( "6/9/1946 was a good year for some." ))
| import java.io.File;
import java.util.*;
import java.util.regex.*;
public class CommatizingNumbers {
public static void main(String[] args) throws Exception {
commatize("pi=3.14159265358979323846264338327950288419716939937510582"
+ "097494459231", 6, 5, " ");
commatize("The author has two Z$100000000000000 Zimbabwe notes (100 "
+ "trillion).", 0, 3, ".");
try (Scanner sc = new Scanner(new File("input.txt"))) {
while(sc.hasNext())
commatize(sc.nextLine());
}
}
static void commatize(String s) {
commatize(s, 0, 3, ",");
}
static void commatize(String s, int start, int step, String ins) {
if (start < 0 || start > s.length() || step < 1 || step > s.length())
return;
Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start));
StringBuffer result = new StringBuffer(s.substring(0, start));
if (m.find()) {
StringBuilder sb = new StringBuilder(m.group(1)).reverse();
for (int i = step; i < sb.length(); i += step)
sb.insert(i++, ins);
m.appendReplacement(result, sb.reverse().toString());
}
System.out.println(m.appendTail(result));
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from collections import Counter
def cumulative_freq(freq):
cf = {}
total = 0
for b in range(256):
if b in freq:
cf[b] = total
total += freq[b]
return cf
def arithmethic_coding(bytes, radix):
freq = Counter(bytes)
cf = cumulative_freq(freq)
base = len(bytes)
lower = 0
pf = 1
for b in bytes:
lower = lower*base + cf[b]*pf
pf *= freq[b]
upper = lower+pf
pow = 0
while True:
pf //= radix
if pf==0: break
pow += 1
enc = (upper-1) // radix**pow
return enc, pow, freq
def arithmethic_decoding(enc, radix, pow, freq):
enc *= radix**pow;
base = sum(freq.values())
cf = cumulative_freq(freq)
dict = {}
for k,v in cf.items():
dict[v] = k
lchar = None
for i in range(base):
if i in dict:
lchar = dict[i]
elif lchar is not None:
dict[i] = lchar
decoded = bytearray()
for i in range(base-1, -1, -1):
pow = base**i
div = enc//pow
c = dict[div]
fv = freq[c]
cv = cf[c]
rem = (enc - pow*cv) // fv
enc = rem
decoded.append(c)
return bytes(decoded)
radix = 10
for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split():
enc, pow, freq = arithmethic_coding(str, radix)
dec = arithmethic_decoding(enc, radix, pow, freq)
print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow))
if str != dec:
raise Exception("\tHowever that is incorrect!")
| import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class ArithmeticCoding {
private static class Triple<A, B, C> {
A a;
B b;
C c;
Triple(A a, B b, C c) {
this.a = a;
this.b = b;
this.c = c;
}
}
private static class Freq extends HashMap<Character, Long> {
}
private static Freq cumulativeFreq(Freq freq) {
long total = 0;
Freq cf = new Freq();
for (int i = 0; i < 256; ++i) {
char c = (char) i;
Long v = freq.get(c);
if (v != null) {
cf.put(c, total);
total += v;
}
}
return cf;
}
private static Triple<BigInteger, Integer, Freq> arithmeticCoding(String str, Long radix) {
char[] chars = str.toCharArray();
Freq freq = new Freq();
for (char c : chars) {
if (!freq.containsKey(c))
freq.put(c, 1L);
else
freq.put(c, freq.get(c) + 1);
}
Freq cf = cumulativeFreq(freq);
BigInteger base = BigInteger.valueOf(chars.length);
BigInteger lower = BigInteger.ZERO;
BigInteger pf = BigInteger.ONE;
for (char c : chars) {
BigInteger x = BigInteger.valueOf(cf.get(c));
lower = lower.multiply(base).add(x.multiply(pf));
pf = pf.multiply(BigInteger.valueOf(freq.get(c)));
}
BigInteger upper = lower.add(pf);
int powr = 0;
BigInteger bigRadix = BigInteger.valueOf(radix);
while (true) {
pf = pf.divide(bigRadix);
if (pf.equals(BigInteger.ZERO)) break;
powr++;
}
BigInteger diff = upper.subtract(BigInteger.ONE).divide(bigRadix.pow(powr));
return new Triple<>(diff, powr, freq);
}
private static String arithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {
BigInteger powr = BigInteger.valueOf(radix);
BigInteger enc = num.multiply(powr.pow(pwr));
long base = 0;
for (Long v : freq.values()) base += v;
Freq cf = cumulativeFreq(freq);
Map<Long, Character> dict = new HashMap<>();
for (Map.Entry<Character, Long> entry : cf.entrySet()) dict.put(entry.getValue(), entry.getKey());
long lchar = -1;
for (long i = 0; i < base; ++i) {
Character v = dict.get(i);
if (v != null) {
lchar = v;
} else if (lchar != -1) {
dict.put(i, (char) lchar);
}
}
StringBuilder decoded = new StringBuilder((int) base);
BigInteger bigBase = BigInteger.valueOf(base);
for (long i = base - 1; i >= 0; --i) {
BigInteger pow = bigBase.pow((int) i);
BigInteger div = enc.divide(pow);
Character c = dict.get(div.longValue());
BigInteger fv = BigInteger.valueOf(freq.get(c));
BigInteger cv = BigInteger.valueOf(cf.get(c));
BigInteger diff = enc.subtract(pow.multiply(cv));
enc = diff.divide(fv);
decoded.append(c);
}
return decoded.toString();
}
public static void main(String[] args) {
long radix = 10;
String[] strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"};
String fmt = "%-25s=> %19s * %d^%s\n";
for (String str : strings) {
Triple<BigInteger, Integer, Freq> encoded = arithmeticCoding(str, radix);
String dec = arithmeticDecoding(encoded.a, radix, encoded.b, encoded.c);
System.out.printf(fmt, str, encoded.a, radix, encoded.b);
if (!Objects.equals(str, dec)) throw new RuntimeException("\tHowever that is incorrect!");
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | def kosaraju(g):
class nonlocal: pass
size = len(g)
vis = [False]*size
l = [0]*size
nonlocal.x = size
t = [[]]*size
def visit(u):
if not vis[u]:
vis[u] = True
for v in g[u]:
visit(v)
t[v] = t[v] + [u]
nonlocal.x = nonlocal.x - 1
l[nonlocal.x] = u
for u in range(len(g)):
visit(u)
c = [0]*size
def assign(u, root):
if vis[u]:
vis[u] = False
c[u] = root
for v in t[u]:
assign(v, root)
for u in l:
assign(u, u)
return c
g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g)
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Kosaraju {
static class Recursive<I> {
I func;
}
private static List<Integer> kosaraju(List<List<Integer>> g) {
int size = g.size();
boolean[] vis = new boolean[size];
int[] l = new int[size];
AtomicInteger x = new AtomicInteger(size);
List<List<Integer>> t = new ArrayList<>();
for (int i = 0; i < size; ++i) {
t.add(new ArrayList<>());
}
Recursive<IntConsumer> visit = new Recursive<>();
visit.func = (int u) -> {
if (!vis[u]) {
vis[u] = true;
for (Integer v : g.get(u)) {
visit.func.accept(v);
t.get(v).add(u);
}
int xval = x.decrementAndGet();
l[xval] = u;
}
};
for (int i = 0; i < size; ++i) {
visit.func.accept(i);
}
int[] c = new int[size];
Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();
assign.func = (Integer u, Integer root) -> {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (Integer v : t.get(u)) {
assign.func.accept(v, root);
}
}
};
for (int u : l) {
assign.func.accept(u, u);
}
return Arrays.stream(c).boxed().collect(Collectors.toList());
}
public static void main(String[] args) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < 8; ++i) {
g.add(new ArrayList<>());
}
g.get(0).add(1);
g.get(1).add(2);
g.get(2).add(0);
g.get(3).add(1);
g.get(3).add(2);
g.get(3).add(4);
g.get(4).add(3);
g.get(4).add(5);
g.get(5).add(2);
g.get(5).add(6);
g.get(6).add(5);
g.get(7).add(4);
g.get(7).add(6);
g.get(7).add(7);
List<Integer> output = kosaraju(g);
System.out.println(output);
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | import inspect
class Super(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "Super(%s)" % (self.name,)
def doSup(self):
return 'did super stuff'
@classmethod
def cls(cls):
return 'cls method (in sup)'
@classmethod
def supCls(cls):
return 'Super method'
@staticmethod
def supStatic():
return 'static method'
class Other(object):
def otherMethod(self):
return 'other method'
class Sub(Other, Super):
def __init__(self, name, *args):
super(Sub, self).__init__(name);
self.rest = args;
self.methods = {}
def __dir__(self):
return list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
+ self.methods.keys() \
))
def __getattr__(self, name):
if name in self.methods:
if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
if self.methods[name].__code__.co_varnames[0] == 'self':
return self.methods[name].__get__(self, type(self))
if self.methods[name].__code__.co_varnames[0] == 'cls':
return self.methods[name].__get__(type(self), type)
return self.methods[name]
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __str__(self):
return "Sub(%s)" % self.name
def doSub():
return 'did sub stuff'
@classmethod
def cls(cls):
return 'cls method (in Sub)'
@classmethod
def subCls(cls):
return 'Sub method'
@staticmethod
def subStatic():
return 'Sub method'
sup = Super('sup')
sub = Sub('sub', 0, 'I', 'two')
sub.methods['incr'] = lambda x: x+1
sub.methods['strs'] = lambda self, x: str(self) * x
[method for method in dir(sub) if callable(getattr(sub, method))]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]
[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]
inspect.getmembers(sub, predicate=inspect.ismethod)
map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
| import java.lang.reflect.Method;
public class ListMethods {
public int examplePublicInstanceMethod(char c, double d) {
return 42;
}
private boolean examplePrivateInstanceMethod(String s) {
return true;
}
public static void main(String[] args) {
Class clazz = ListMethods.class;
System.out.println("All public methods (including inherited):");
for (Method m : clazz.getMethods()) {
System.out.println(m);
}
System.out.println();
System.out.println("All declared methods (excluding inherited):");
for (Method m : clazz.getDeclaredMethods()) {
System.out.println(m);
}
}
}
|
Please provide an equivalent version of this Python code in Java. |
var x = 0
var y = 0
There are also multi-line comments
Everything inside of
]
discard
|
Int i = 0;
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | from itertools import product
minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),
((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),
((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),
((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),
((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),
((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),
((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),
((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),
((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),
((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),
((4311810305, 8, 4), (31, 4, 8)),
((132866, 6, 6),))
boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'
boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]
patterns = boxchar_single_width
tiles = []
for row in reversed(minos):
tiles.append([])
for n, x, y in row:
for shift in (b*8 + a for a, b in product(range(x), range(y))):
tiles[-1].append(n << shift)
def img(seq):
b = [[0]*10 for _ in range(10)]
for i, s in enumerate(seq):
for j, k in product(range(8), range(8)):
if s & (1<<(j*8 + k)):
b[j + 1][k + 1] = i + 1
idices = [[0]*9 for _ in range(9)]
for i, j in product(range(9), range(9)):
n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])
idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))
return '\n'.join(''.join(patterns[i] for i in row) for row in idices)
def tile(board=0, seq=tuple(), tiles=tiles):
if not tiles:
yield img(seq)
return
for c in tiles[0]:
b = board | c
tnext = []
for t in tiles[1:]:
tnext.append(tuple(n for n in t if not n&b))
if not tnext[-1]: break
else:
yield from tile(b, seq + (c,), tnext)
for x in tile():
print(x)
| package pentominotiling;
import java.util.*;
public class PentominoTiling {
static final char[] symbols = "FILNPTUVWXYZ-".toCharArray();
static final Random rand = new Random();
static final int nRows = 8;
static final int nCols = 8;
static final int blank = 12;
static int[][] grid = new int[nRows][nCols];
static boolean[] placed = new boolean[symbols.length - 1];
public static void main(String[] args) {
shuffleShapes();
for (int r = 0; r < nRows; r++)
Arrays.fill(grid[r], -1);
for (int i = 0; i < 4; i++) {
int randRow, randCol;
do {
randRow = rand.nextInt(nRows);
randCol = rand.nextInt(nCols);
} while (grid[randRow][randCol] == blank);
grid[randRow][randCol] = blank;
}
if (solve(0, 0)) {
printResult();
} else {
System.out.println("no solution");
}
}
static void shuffleShapes() {
int n = shapes.length;
while (n > 1) {
int r = rand.nextInt(n--);
int[][] tmp = shapes[r];
shapes[r] = shapes[n];
shapes[n] = tmp;
char tmpSymbol = symbols[r];
symbols[r] = symbols[n];
symbols[n] = tmpSymbol;
}
}
static void printResult() {
for (int[] r : grid) {
for (int i : r)
System.out.printf("%c ", symbols[i]);
System.out.println();
}
}
static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {
for (int i = 0; i < o.length; i += 2) {
int x = c + o[i + 1];
int y = r + o[i];
if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)
return false;
}
grid[r][c] = shapeIndex;
for (int i = 0; i < o.length; i += 2)
grid[r + o[i]][c + o[i + 1]] = shapeIndex;
return true;
}
static void removeOrientation(int[] o, int r, int c) {
grid[r][c] = -1;
for (int i = 0; i < o.length; i += 2)
grid[r + o[i]][c + o[i + 1]] = -1;
}
static boolean solve(int pos, int numPlaced) {
if (numPlaced == shapes.length)
return true;
int row = pos / nCols;
int col = pos % nCols;
if (grid[row][col] != -1)
return solve(pos + 1, numPlaced);
for (int i = 0; i < shapes.length; i++) {
if (!placed[i]) {
for (int[] orientation : shapes[i]) {
if (!tryPlaceOrientation(orientation, row, col, i))
continue;
placed[i] = true;
if (solve(pos + 1, numPlaced + 1))
return true;
removeOrientation(orientation, row, col);
placed[i] = false;
}
}
}
return false;
}
static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},
{1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},
{0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};
static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};
static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};
static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},
{1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};
static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},
{1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},
{1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};
static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},
{1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};
static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},
{0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};
static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},
{1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};
static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},
{0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};
static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};
static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},
{1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};
static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},
{0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};
static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};
}
|
Change the following Python code into Java without altering its purpose. | from itertools import product
minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),
((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),
((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),
((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),
((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),
((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),
((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),
((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),
((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),
((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),
((4311810305, 8, 4), (31, 4, 8)),
((132866, 6, 6),))
boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'
boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]
patterns = boxchar_single_width
tiles = []
for row in reversed(minos):
tiles.append([])
for n, x, y in row:
for shift in (b*8 + a for a, b in product(range(x), range(y))):
tiles[-1].append(n << shift)
def img(seq):
b = [[0]*10 for _ in range(10)]
for i, s in enumerate(seq):
for j, k in product(range(8), range(8)):
if s & (1<<(j*8 + k)):
b[j + 1][k + 1] = i + 1
idices = [[0]*9 for _ in range(9)]
for i, j in product(range(9), range(9)):
n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])
idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))
return '\n'.join(''.join(patterns[i] for i in row) for row in idices)
def tile(board=0, seq=tuple(), tiles=tiles):
if not tiles:
yield img(seq)
return
for c in tiles[0]:
b = board | c
tnext = []
for t in tiles[1:]:
tnext.append(tuple(n for n in t if not n&b))
if not tnext[-1]: break
else:
yield from tile(b, seq + (c,), tnext)
for x in tile():
print(x)
| package pentominotiling;
import java.util.*;
public class PentominoTiling {
static final char[] symbols = "FILNPTUVWXYZ-".toCharArray();
static final Random rand = new Random();
static final int nRows = 8;
static final int nCols = 8;
static final int blank = 12;
static int[][] grid = new int[nRows][nCols];
static boolean[] placed = new boolean[symbols.length - 1];
public static void main(String[] args) {
shuffleShapes();
for (int r = 0; r < nRows; r++)
Arrays.fill(grid[r], -1);
for (int i = 0; i < 4; i++) {
int randRow, randCol;
do {
randRow = rand.nextInt(nRows);
randCol = rand.nextInt(nCols);
} while (grid[randRow][randCol] == blank);
grid[randRow][randCol] = blank;
}
if (solve(0, 0)) {
printResult();
} else {
System.out.println("no solution");
}
}
static void shuffleShapes() {
int n = shapes.length;
while (n > 1) {
int r = rand.nextInt(n--);
int[][] tmp = shapes[r];
shapes[r] = shapes[n];
shapes[n] = tmp;
char tmpSymbol = symbols[r];
symbols[r] = symbols[n];
symbols[n] = tmpSymbol;
}
}
static void printResult() {
for (int[] r : grid) {
for (int i : r)
System.out.printf("%c ", symbols[i]);
System.out.println();
}
}
static boolean tryPlaceOrientation(int[] o, int r, int c, int shapeIndex) {
for (int i = 0; i < o.length; i += 2) {
int x = c + o[i + 1];
int y = r + o[i];
if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1)
return false;
}
grid[r][c] = shapeIndex;
for (int i = 0; i < o.length; i += 2)
grid[r + o[i]][c + o[i + 1]] = shapeIndex;
return true;
}
static void removeOrientation(int[] o, int r, int c) {
grid[r][c] = -1;
for (int i = 0; i < o.length; i += 2)
grid[r + o[i]][c + o[i + 1]] = -1;
}
static boolean solve(int pos, int numPlaced) {
if (numPlaced == shapes.length)
return true;
int row = pos / nCols;
int col = pos % nCols;
if (grid[row][col] != -1)
return solve(pos + 1, numPlaced);
for (int i = 0; i < shapes.length; i++) {
if (!placed[i]) {
for (int[] orientation : shapes[i]) {
if (!tryPlaceOrientation(orientation, row, col, i))
continue;
placed[i] = true;
if (solve(pos + 1, numPlaced + 1))
return true;
removeOrientation(orientation, row, col);
placed[i] = false;
}
}
}
return false;
}
static final int[][] F = {{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},
{1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1},
{0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}};
static final int[][] I = {{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}};
static final int[][] L = {{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}};
static final int[][] N = {{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},
{1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}};
static final int[][] P = {{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},
{1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},
{1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}};
static final int[][] T = {{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},
{1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}};
static final int[][] U = {{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},
{0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}};
static final int[][] V = {{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},
{1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}};
static final int[][] W = {{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},
{0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}};
static final int[][] X = {{1, -1, 1, 0, 1, 1, 2, 0}};
static final int[][] Y = {{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},
{1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}};
static final int[][] Z = {{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},
{0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}};
static final int[][][] shapes = {F, I, L, N, P, T, U, V, W, X, Y, Z};
}
|
Maintain the same structure and functionality when rewriting this code in Java. | class Example(object):
def foo(self, x):
return 42 + x
name = "foo"
getattr(Example(), name)(5)
| import java.lang.reflect.Method;
class Example {
public int foo(int x) {
return 42 + x;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Object example = new Example();
String name = "foo";
Class<?> clazz = example.getClass();
Method meth = clazz.getMethod(name, int.class);
Object result = meth.invoke(example, 5);
System.out.println(result);
}
}
|
Please provide an equivalent version of this Python code in Java. |
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"
example1 = "goodbye"
| int a;
double b;
AClassNameHere c;
|
Write the same algorithm in Java as shown in this Python implementation. | import math
import random
INFINITY = 1 << 127
MAX_INT = 1 << 31
class Parameters:
def __init__(self, omega, phip, phig):
self.omega = omega
self.phip = phip
self.phig = phig
class State:
def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims):
self.iter = iter
self.gbpos = gbpos
self.gbval = gbval
self.min = min
self.max = max
self.parameters = parameters
self.pos = pos
self.vel = vel
self.bpos = bpos
self.bval = bval
self.nParticles = nParticles
self.nDims = nDims
def report(self, testfunc):
print "Test Function :", testfunc
print "Iterations :", self.iter
print "Global Best Position :", self.gbpos
print "Global Best Value : %.16f" % self.gbval
def uniform01():
v = random.random()
assert 0.0 <= v and v < 1.0
return v
def psoInit(min, max, parameters, nParticles):
nDims = len(min)
pos = [min[:]] * nParticles
vel = [[0.0] * nDims] * nParticles
bpos = [min[:]] * nParticles
bval = [INFINITY] * nParticles
iter = 0
gbpos = [INFINITY] * nDims
gbval = INFINITY
return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);
def pso(fn, y):
p = y.parameters
v = [0.0] * (y.nParticles)
bpos = [y.min[:]] * (y.nParticles)
bval = [0.0] * (y.nParticles)
gbpos = [0.0] * (y.nDims)
gbval = INFINITY
for j in xrange(0, y.nParticles):
v[j] = fn(y.pos[j])
if v[j] < y.bval[j]:
bpos[j] = y.pos[j][:]
bval[j] = v[j]
else:
bpos[j] = y.bpos[j][:]
bval[j] = y.bval[j]
if bval[j] < gbval:
gbval = bval[j]
gbpos = bpos[j][:]
rg = uniform01()
pos = [[None] * (y.nDims)] * (y.nParticles)
vel = [[None] * (y.nDims)] * (y.nParticles)
for j in xrange(0, y.nParticles):
rp = uniform01()
ok = True
vel[j] = [0.0] * (len(vel[j]))
pos[j] = [0.0] * (len(pos[j]))
for k in xrange(0, y.nDims):
vel[j][k] = p.omega * y.vel[j][k] \
+ p.phip * rp * (bpos[j][k] - y.pos[j][k]) \
+ p.phig * rg * (gbpos[k] - y.pos[j][k])
pos[j][k] = y.pos[j][k] + vel[j][k]
ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k]
if not ok:
for k in xrange(0, y.nDims):
pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01()
iter = 1 + y.iter
return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims);
def iterate(fn, n, y):
r = y
old = y
if n == MAX_INT:
while True:
r = pso(fn, r)
if r == old:
break
old = r
else:
for _ in xrange(0, n):
r = pso(fn, r)
return r
def mccormick(x):
(a, b) = x
return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a
def michalewicz(x):
m = 10
d = len(x)
sum = 0.0
for i in xrange(1, d):
j = x[i - 1]
k = math.sin(i * j * j / math.pi)
sum += math.sin(j) * k ** (2.0 * m)
return -sum
def main():
state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100)
state = iterate(mccormick, 40, state)
state.report("McCormick")
print "f(-.54719, -1.54719) : %.16f" % (mccormick([-.54719, -1.54719]))
print
state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000)
state = iterate(michalewicz, 30, state)
state.report("Michalewicz (2D)")
print "f(2.20, 1.57) : %.16f" % (michalewicz([2.2, 1.57]))
main()
| import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.function.Function;
public class App {
static class Parameters {
double omega;
double phip;
double phig;
Parameters(double omega, double phip, double phig) {
this.omega = omega;
this.phip = phip;
this.phig = phig;
}
}
static class State {
int iter;
double[] gbpos;
double gbval;
double[] min;
double[] max;
Parameters parameters;
double[][] pos;
double[][] vel;
double[][] bpos;
double[] bval;
int nParticles;
int nDims;
State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) {
this.iter = iter;
this.gbpos = gbpos;
this.gbval = gbval;
this.min = min;
this.max = max;
this.parameters = parameters;
this.pos = pos;
this.vel = vel;
this.bpos = bpos;
this.bval = bval;
this.nParticles = nParticles;
this.nDims = nDims;
}
void report(String testfunc) {
System.out.printf("Test Function : %s\n", testfunc);
System.out.printf("Iterations : %d\n", iter);
System.out.printf("Global Best Position : %s\n", Arrays.toString(gbpos));
System.out.printf("Global Best value : %.15f\n", gbval);
}
}
private static State psoInit(double[] min, double[] max, Parameters parameters, int nParticles) {
int nDims = min.length;
double[][] pos = new double[nParticles][];
for (int i = 0; i < nParticles; ++i) {
pos[i] = min.clone();
}
double[][] vel = new double[nParticles][nDims];
double[][] bpos = new double[nParticles][];
for (int i = 0; i < nParticles; ++i) {
bpos[i] = min.clone();
}
double[] bval = new double[nParticles];
for (int i = 0; i < bval.length; ++i) {
bval[i] = Double.POSITIVE_INFINITY;
}
int iter = 0;
double[] gbpos = new double[nDims];
for (int i = 0; i < gbpos.length; ++i) {
gbpos[i] = Double.POSITIVE_INFINITY;
}
double gbval = Double.POSITIVE_INFINITY;
return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims);
}
private static Random r = new Random();
private static State pso(Function<double[], Double> fn, State y) {
Parameters p = y.parameters;
double[] v = new double[y.nParticles];
double[][] bpos = new double[y.nParticles][];
for (int i = 0; i < y.nParticles; ++i) {
bpos[i] = y.min.clone();
}
double[] bval = new double[y.nParticles];
double[] gbpos = new double[y.nDims];
double gbval = Double.POSITIVE_INFINITY;
for (int j = 0; j < y.nParticles; ++j) {
v[j] = fn.apply(y.pos[j]);
if (v[j] < y.bval[j]) {
bpos[j] = y.pos[j];
bval[j] = v[j];
} else {
bpos[j] = y.bpos[j];
bval[j] = y.bval[j];
}
if (bval[j] < gbval) {
gbval = bval[j];
gbpos = bpos[j];
}
}
double rg = r.nextDouble();
double[][] pos = new double[y.nParticles][y.nDims];
double[][] vel = new double[y.nParticles][y.nDims];
for (int j = 0; j < y.nParticles; ++j) {
double rp = r.nextDouble();
boolean ok = true;
Arrays.fill(vel[j], 0.0);
Arrays.fill(pos[j], 0.0);
for (int k = 0; k < y.nDims; ++k) {
vel[j][k] = p.omega * y.vel[j][k] +
p.phip * rp * (bpos[j][k] - y.pos[j][k]) +
p.phig * rg * (gbpos[k] - y.pos[j][k]);
pos[j][k] = y.pos[j][k] + vel[j][k];
ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k];
}
if (!ok) {
for (int k = 0; k < y.nDims; ++k) {
pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.nextDouble();
}
}
}
int iter = 1 + y.iter;
return new State(
iter, gbpos, gbval, y.min, y.max, y.parameters,
pos, vel, bpos, bval, y.nParticles, y.nDims
);
}
private static State iterate(Function<double[], Double> fn, int n, State y) {
State r = y;
if (n == Integer.MAX_VALUE) {
State old = y;
while (true) {
r = pso(fn, r);
if (Objects.equals(r, old)) break;
old = r;
}
} else {
for (int i = 0; i < n; ++i) {
r = pso(fn, r);
}
}
return r;
}
private static double mccormick(double[] x) {
double a = x[0];
double b = x[1];
return Math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a;
}
private static double michalewicz(double[] x) {
int m = 10;
int d = x.length;
double sum = 0.0;
for (int i = 1; i < d; ++i) {
double j = x[i - 1];
double k = Math.sin(i * j * j / Math.PI);
sum += Math.sin(j) * Math.pow(k, 2.0 * m);
}
return -sum;
}
public static void main(String[] args) {
State state = psoInit(
new double[]{-1.5, -3.0},
new double[]{4.0, 4.0},
new Parameters(0.0, 0.6, 0.3),
100
);
state = iterate(App::mccormick, 40, state);
state.report("McCormick");
System.out.printf("f(-.54719, -1.54719) : %.15f\n", mccormick(new double[]{-.54719, -1.54719}));
System.out.println();
state = psoInit(
new double[]{0.0, 0.0},
new double[]{Math.PI, Math.PI},
new Parameters(0.3, 3.0, 0.3),
1000
);
state = iterate(App::michalewicz, 30, state);
state.report("Michalewicz (2D)");
System.out.printf("f(2.20, 1.57) : %.15f\n", michalewicz(new double[]{2.20, 1.57}));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | python
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(string1, string2, separator):
return separator.join([string1, '', string2])
>>> f('Rosetta', 'Code', ':')
'Rosetta::Code'
>>>
| public static void main(String[] args) {
System.out.println(concat("Rosetta", "Code", ":"));
}
public static String concat(String a, String b, String c) {
return a + c + c + b;
}
Rosetta::Code
|
Change the following Python code into Java without altering its purpose. | def rank(x): return int('a'.join(map(str, [1] + x)), 11)
def unrank(n):
s = ''
while n: s,n = "0123456789a"[n%11] + s, n//11
return map(int, s.split('a'))[1:]
l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l
| import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.Collectors.*;
public class Test3 {
static BigInteger rank(int[] x) {
String s = stream(x).mapToObj(String::valueOf).collect(joining("F"));
return new BigInteger(s, 16);
}
static List<BigInteger> unrank(BigInteger n) {
BigInteger sixteen = BigInteger.valueOf(16);
String s = "";
while (!n.equals(BigInteger.ZERO)) {
s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s;
n = n.divide(sixteen);
}
return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList());
}
public static void main(String[] args) {
int[] s = {1, 2, 3, 10, 100, 987654321};
System.out.println(Arrays.toString(s));
System.out.println(rank(s));
System.out.println(unrank(rank(s)));
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | import os
targetfile = "pycon-china"
os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak")
f = open(os.path.realpath(targetfile), "w")
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.close()
| import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
public class Backup {
public static void saveWithBackup(String filename, String... data)
throws IOException {
Path file = Paths.get(filename).toRealPath();
File backFile = new File(filename + ".backup");
if(!backFile.exists()) {
backFile.createNewFile();
}
Path back = Paths.get(filename + ".backup").toRealPath();
Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
try(PrintWriter out = new PrintWriter(file.toFile())){
for(int i = 0; i < data.length; i++) {
out.print(data[i]);
if(i < data.length - 1) {
out.println();
}
}
}
}
public static void main(String[] args) {
try {
saveWithBackup("original.txt", "fourth", "fifth", "sixth");
} catch (IOException e) {
System.err.println(e);
}
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | import os
targetfile = "pycon-china"
os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak")
f = open(os.path.realpath(targetfile), "w")
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.close()
| import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
public class Backup {
public static void saveWithBackup(String filename, String... data)
throws IOException {
Path file = Paths.get(filename).toRealPath();
File backFile = new File(filename + ".backup");
if(!backFile.exists()) {
backFile.createNewFile();
}
Path back = Paths.get(filename + ".backup").toRealPath();
Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
try(PrintWriter out = new PrintWriter(file.toFile())){
for(int i = 0; i < data.length; i++) {
out.print(data[i]);
if(i < data.length - 1) {
out.println();
}
}
}
}
public static void main(String[] args) {
try {
saveWithBackup("original.txt", "fourth", "fifth", "sixth");
} catch (IOException e) {
System.err.println(e);
}
}
}
|
Generate an equivalent Java version of this Python code. |
import re
male2female=u
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
switch={}
words=[]
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
def gen_pluralize(m,f):
yield re_plural.sub("",m),re_plural.sub("",f)
yield re_ES.sub("es",m),re_ES.sub("es",f)
yield re_plural.sub("s",m),re_plural.sub("s",f)
def gen_capitalize_pluralize(m,f):
for m,f in gen_pluralize(m,f):
yield m.capitalize(), f.capitalize()
yield m,f
def gen_switch_role_capitalize_pluralize(m,f):
for m,f in gen_capitalize_pluralize(m,f):
yield m,f
yield f,m
for m,f in m2f:
for xy,xx in gen_switch_role_capitalize_pluralize(m,f):
if xy not in switch:
switch[xy]=xx
words.append(xy)
words="|".join(words)
re_word=re.compile(ur"\b("+words+ur")\b")
text=u
def rev_gender(text):
text=re_word.split(text)
return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]
print rev_gender(text)
| public class ReallyLameTranslationOfJ {
public static void main(String[] args) {
String s = "She was a soul stripper. She took my heart!";
System.out.println(cheapTrick(s));
System.out.println(cheapTrick(cheapTrick(s)));
}
static String cheapTrick(String s) {
if (s.contains("She"))
return s.replaceAll("She", "He");
else if(s.contains("He"))
return s.replaceAll("He", "She");
return s;
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. |
import re
male2female=u
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
switch={}
words=[]
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
def gen_pluralize(m,f):
yield re_plural.sub("",m),re_plural.sub("",f)
yield re_ES.sub("es",m),re_ES.sub("es",f)
yield re_plural.sub("s",m),re_plural.sub("s",f)
def gen_capitalize_pluralize(m,f):
for m,f in gen_pluralize(m,f):
yield m.capitalize(), f.capitalize()
yield m,f
def gen_switch_role_capitalize_pluralize(m,f):
for m,f in gen_capitalize_pluralize(m,f):
yield m,f
yield f,m
for m,f in m2f:
for xy,xx in gen_switch_role_capitalize_pluralize(m,f):
if xy not in switch:
switch[xy]=xx
words.append(xy)
words="|".join(words)
re_word=re.compile(ur"\b("+words+ur")\b")
text=u
def rev_gender(text):
text=re_word.split(text)
return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]
print rev_gender(text)
| public class ReallyLameTranslationOfJ {
public static void main(String[] args) {
String s = "She was a soul stripper. She took my heart!";
System.out.println(cheapTrick(s));
System.out.println(cheapTrick(cheapTrick(s)));
}
static String cheapTrick(String s) {
if (s.contains("She"))
return s.replaceAll("She", "He");
else if(s.contains("He"))
return s.replaceAll("He", "She");
return s;
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import time
import os
seconds = input("Enter a number of seconds: ")
sound = input("Enter an mp3 filename: ")
time.sleep(float(seconds))
os.startfile(sound + ".mp3")
| import com.sun.javafx.application.PlatformImpl;
import java.io.File;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class AudioAlarm {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number of seconds: ");
int seconds = Integer.parseInt(input.nextLine());
System.out.print("Enter a filename (must end with .mp3 or .wav): ");
String audio = input.nextLine();
TimeUnit.SECONDS.sleep(seconds);
Media media = new Media(new File(audio).toURI().toString());
AtomicBoolean stop = new AtomicBoolean();
Runnable onEnd = () -> stop.set(true);
PlatformImpl.startup(() -> {});
MediaPlayer player = new MediaPlayer(media);
player.setOnEndOfMedia(onEnd);
player.setOnError(onEnd);
player.setOnHalted(onEnd);
player.play();
while (!stop.get()) {
Thread.sleep(100);
}
System.exit(0);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])
return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]
+ bin(int(hx[p+2:]))[2:])
def float_bin2dec(bn):
neg = False
if bn[0] == '-':
bn = bn[1:]
neg = True
dp = bn.index('.')
extra0 = '0' * (4 - (dp % 4))
bn2 = extra0 + bn
dp = bn2.index('.')
p = bn2.index('p')
hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])
for i in range(0, dp+1, 4))
bn3 = bn2[dp+1:p]
extra0 = '0' * (4 - (len(bn3) % 4))
bn4 = bn3 + extra0
hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))
for i in range(0, len(bn4), 4))
hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]
+ str(int('0b' + bn2[p+2:], 2)))
return float.fromhex(hx)
| import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class DecimalToBinary {
public static void main(String[] args) {
for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) {
String binary = decimalToBinary(new BigDecimal(s));
System.out.printf("%s => %s%n", s, binary);
System.out.printf("%s => %s%n", binary, binaryToDecimal(binary));
}
}
private static BigDecimal binaryToDecimal(String binary) {
return binaryToDecimal(binary, 50);
}
private static BigDecimal binaryToDecimal(String binary, int digits) {
int decimalPosition = binary.indexOf(".");
String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;
String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : "";
BigDecimal result = BigDecimal.ZERO;
BigDecimal powTwo = BigDecimal.ONE;
BigDecimal two = BigDecimal.valueOf(2);
for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));
powTwo = powTwo.multiply(two);
}
MathContext mc = new MathContext(digits);
powTwo = BigDecimal.ONE;
for ( char c : fractional.toCharArray() ) {
powTwo = powTwo.divide(two);
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);
}
return result;
}
private static String decimalToBinary(BigDecimal decimal) {
return decimalToBinary(decimal, 50);
}
private static String decimalToBinary(BigDecimal decimal, int digits) {
BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);
BigDecimal fractional = decimal.subtract(integer);
StringBuilder sb = new StringBuilder();
BigDecimal two = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.ZERO;
while ( integer.compareTo(zero) > 0 ) {
BigDecimal[] result = integer.divideAndRemainder(two);
sb.append(result[1]);
integer = result[0];
}
sb.reverse();
int count = 0;
if ( fractional.compareTo(zero) != 0 ) {
sb.append(".");
}
while ( fractional.compareTo(zero) != 0 ) {
count++;
fractional = fractional.multiply(two);
sb.append(fractional.setScale(0, RoundingMode.FLOOR));
if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {
fractional = fractional.subtract(BigDecimal.ONE);
}
if ( count >= digits ) {
break;
}
}
return sb.toString();
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])
return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]
+ bin(int(hx[p+2:]))[2:])
def float_bin2dec(bn):
neg = False
if bn[0] == '-':
bn = bn[1:]
neg = True
dp = bn.index('.')
extra0 = '0' * (4 - (dp % 4))
bn2 = extra0 + bn
dp = bn2.index('.')
p = bn2.index('p')
hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])
for i in range(0, dp+1, 4))
bn3 = bn2[dp+1:p]
extra0 = '0' * (4 - (len(bn3) % 4))
bn4 = bn3 + extra0
hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))
for i in range(0, len(bn4), 4))
hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]
+ str(int('0b' + bn2[p+2:], 2)))
return float.fromhex(hx)
| import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class DecimalToBinary {
public static void main(String[] args) {
for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) {
String binary = decimalToBinary(new BigDecimal(s));
System.out.printf("%s => %s%n", s, binary);
System.out.printf("%s => %s%n", binary, binaryToDecimal(binary));
}
}
private static BigDecimal binaryToDecimal(String binary) {
return binaryToDecimal(binary, 50);
}
private static BigDecimal binaryToDecimal(String binary, int digits) {
int decimalPosition = binary.indexOf(".");
String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;
String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : "";
BigDecimal result = BigDecimal.ZERO;
BigDecimal powTwo = BigDecimal.ONE;
BigDecimal two = BigDecimal.valueOf(2);
for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));
powTwo = powTwo.multiply(two);
}
MathContext mc = new MathContext(digits);
powTwo = BigDecimal.ONE;
for ( char c : fractional.toCharArray() ) {
powTwo = powTwo.divide(two);
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);
}
return result;
}
private static String decimalToBinary(BigDecimal decimal) {
return decimalToBinary(decimal, 50);
}
private static String decimalToBinary(BigDecimal decimal, int digits) {
BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);
BigDecimal fractional = decimal.subtract(integer);
StringBuilder sb = new StringBuilder();
BigDecimal two = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.ZERO;
while ( integer.compareTo(zero) > 0 ) {
BigDecimal[] result = integer.divideAndRemainder(two);
sb.append(result[1]);
integer = result[0];
}
sb.reverse();
int count = 0;
if ( fractional.compareTo(zero) != 0 ) {
sb.append(".");
}
while ( fractional.compareTo(zero) != 0 ) {
count++;
fractional = fractional.multiply(two);
sb.append(fractional.setScale(0, RoundingMode.FLOOR));
if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {
fractional = fractional.subtract(BigDecimal.ONE);
}
if ( count >= digits ) {
break;
}
}
return sb.toString();
}
}
|
Please provide an equivalent version of this Python code in Java. | >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
| import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string:
m_sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
return m_sourceCode;
}
private boolean compile() {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
null, null, null, Arrays.asList( this )
).call();
}
private double callEval( final double x )
throws Exception {
final Class<?> clarse = Class.forName( CLASS_NAME );
final Method eval = clarse.getMethod( "eval", double.class );
return ( Double ) eval.invoke( null, x );
}
}
public static double evalWithX( final String code, final double x )
throws Exception {
final StringCompiler sc = new StringCompiler(
"class "
+ CLASS_NAME
+ "{public static double eval(double x){return ("
+ code
+ ");}}"
);
if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
return sc.callEval( x );
}
public static void main( final String [] args )
throws Exception {
final String expression = args [ 0 ];
final double x1 = Double.parseDouble( args [ 1 ] );
final double x2 = Double.parseDouble( args [ 2 ] );
System.out.println(
evalWithX( expression, x1 )
- evalWithX( expression, x2 )
);
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
| import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string:
m_sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
return m_sourceCode;
}
private boolean compile() {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
null, null, null, Arrays.asList( this )
).call();
}
private double callEval( final double x )
throws Exception {
final Class<?> clarse = Class.forName( CLASS_NAME );
final Method eval = clarse.getMethod( "eval", double.class );
return ( Double ) eval.invoke( null, x );
}
}
public static double evalWithX( final String code, final double x )
throws Exception {
final StringCompiler sc = new StringCompiler(
"class "
+ CLASS_NAME
+ "{public static double eval(double x){return ("
+ code
+ ");}}"
);
if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
return sc.callEval( x );
}
public static void main( final String [] args )
throws Exception {
final String expression = args [ 0 ];
final double x1 = Double.parseDouble( args [ 1 ] );
final double x2 = Double.parseDouble( args [ 2 ] );
System.out.println(
evalWithX( expression, x1 )
- evalWithX( expression, x2 )
);
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | import re
from fractions import Fraction
from pprint import pprint as pp
equationtext =
def parse_eqn(equationtext=equationtext):
eqn_re = re.compile(r)
found = eqn_re.findall(equationtext)
machins, part = [], []
for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
if lhs and part:
machins.append(part)
part = []
part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),
Fraction(int(numer), (int(denom) if denom else 1)) ) )
machins.append(part)
return machins
def tans(xs):
xslen = len(xs)
if xslen == 1:
return tanEval(*xs[0])
aa, bb = xs[:xslen//2], xs[xslen//2:]
a, b = tans(aa), tans(bb)
return (a + b) / (1 - a * b)
def tanEval(coef, f):
if coef == 1:
return f
if coef < 0:
return -tanEval(-coef, f)
ca = coef // 2
cb = coef - ca
a, b = tanEval(ca, f), tanEval(cb, f)
return (a + b) / (1 - a * b)
if __name__ == '__main__':
machins = parse_eqn()
for machin, eqn in zip(machins, equationtext.split('\n')):
ans = tans(machin)
print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMachinFormula {
private static String FILE_NAME = "MachinFormula.txt";
public static void main(String[] args) {
try {
runPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runPrivate() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("=");
System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
}
}
}
private static String tanLeft(String formula) {
if ( formula.compareTo("pi/4") == 0 ) {
return "1";
}
throw new RuntimeException("ERROR 104: Unknown left side: " + formula);
}
private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");
private static Fraction tanRight(String formula) {
Matcher matcher = ARCTAN_PATTERN.matcher(formula);
List<Term> terms = new ArrayList<>();
while ( matcher.find() ) {
terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
}
return evaluateArctan(terms);
}
private static Fraction evaluateArctan(List<Term> terms) {
if ( terms.size() == 1 ) {
Term term = terms.get(0);
return evaluateArctan(term.coefficient, term.fraction);
}
int size = terms.size();
List<Term> left = terms.subList(0, (size+1) / 2);
List<Term> right = terms.subList((size+1) / 2, size);
return arctanFormula(evaluateArctan(left), evaluateArctan(right));
}
private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
if ( coefficient == 1 ) {
return fraction;
}
else if ( coefficient < 0 ) {
return evaluateArctan(-coefficient, fraction).negate();
}
if ( coefficient % 2 == 0 ) {
Fraction f = evaluateArctan(coefficient/2, fraction);
return arctanFormula(f, f);
}
Fraction a = evaluateArctan(coefficient/2, fraction);
Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
return arctanFormula(a, b);
}
private static Fraction arctanFormula(Fraction f1, Fraction f2) {
return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
}
private static class Fraction {
public static final Fraction ONE = new Fraction("1", "1");
private BigInteger numerator;
private BigInteger denominator;
public Fraction(String num, String den) {
numerator = new BigInteger(num);
denominator = new BigInteger(den);
}
public Fraction(BigInteger num, BigInteger den) {
numerator = num;
denominator = den;
}
public Fraction negate() {
return new Fraction(numerator.negate(), denominator);
}
public Fraction add(Fraction f) {
BigInteger gcd = denominator.gcd(f.denominator);
BigInteger first = numerator.multiply(f.denominator.divide(gcd));
BigInteger second = f.numerator.multiply(denominator.divide(gcd));
return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
}
public Fraction subtract(Fraction f) {
return add(f.negate());
}
public Fraction multiply(Fraction f) {
BigInteger num = numerator.multiply(f.numerator);
BigInteger den = denominator.multiply(f.denominator);
BigInteger gcd = num.gcd(den);
return new Fraction(num.divide(gcd), den.divide(gcd));
}
public Fraction divide(Fraction f) {
return multiply(new Fraction(f.denominator, f.numerator));
}
@Override
public String toString() {
if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
return numerator.toString();
}
return numerator + " / " + denominator;
}
}
private static class Term {
private int coefficient;
private Fraction fraction;
public Term(int c, Fraction f) {
coefficient = c;
fraction = f;
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | import re
from fractions import Fraction
from pprint import pprint as pp
equationtext =
def parse_eqn(equationtext=equationtext):
eqn_re = re.compile(r)
found = eqn_re.findall(equationtext)
machins, part = [], []
for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
if lhs and part:
machins.append(part)
part = []
part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),
Fraction(int(numer), (int(denom) if denom else 1)) ) )
machins.append(part)
return machins
def tans(xs):
xslen = len(xs)
if xslen == 1:
return tanEval(*xs[0])
aa, bb = xs[:xslen//2], xs[xslen//2:]
a, b = tans(aa), tans(bb)
return (a + b) / (1 - a * b)
def tanEval(coef, f):
if coef == 1:
return f
if coef < 0:
return -tanEval(-coef, f)
ca = coef // 2
cb = coef - ca
a, b = tanEval(ca, f), tanEval(cb, f)
return (a + b) / (1 - a * b)
if __name__ == '__main__':
machins = parse_eqn()
for machin, eqn in zip(machins, equationtext.split('\n')):
ans = tans(machin)
print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMachinFormula {
private static String FILE_NAME = "MachinFormula.txt";
public static void main(String[] args) {
try {
runPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runPrivate() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("=");
System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
}
}
}
private static String tanLeft(String formula) {
if ( formula.compareTo("pi/4") == 0 ) {
return "1";
}
throw new RuntimeException("ERROR 104: Unknown left side: " + formula);
}
private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");
private static Fraction tanRight(String formula) {
Matcher matcher = ARCTAN_PATTERN.matcher(formula);
List<Term> terms = new ArrayList<>();
while ( matcher.find() ) {
terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
}
return evaluateArctan(terms);
}
private static Fraction evaluateArctan(List<Term> terms) {
if ( terms.size() == 1 ) {
Term term = terms.get(0);
return evaluateArctan(term.coefficient, term.fraction);
}
int size = terms.size();
List<Term> left = terms.subList(0, (size+1) / 2);
List<Term> right = terms.subList((size+1) / 2, size);
return arctanFormula(evaluateArctan(left), evaluateArctan(right));
}
private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
if ( coefficient == 1 ) {
return fraction;
}
else if ( coefficient < 0 ) {
return evaluateArctan(-coefficient, fraction).negate();
}
if ( coefficient % 2 == 0 ) {
Fraction f = evaluateArctan(coefficient/2, fraction);
return arctanFormula(f, f);
}
Fraction a = evaluateArctan(coefficient/2, fraction);
Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
return arctanFormula(a, b);
}
private static Fraction arctanFormula(Fraction f1, Fraction f2) {
return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
}
private static class Fraction {
public static final Fraction ONE = new Fraction("1", "1");
private BigInteger numerator;
private BigInteger denominator;
public Fraction(String num, String den) {
numerator = new BigInteger(num);
denominator = new BigInteger(den);
}
public Fraction(BigInteger num, BigInteger den) {
numerator = num;
denominator = den;
}
public Fraction negate() {
return new Fraction(numerator.negate(), denominator);
}
public Fraction add(Fraction f) {
BigInteger gcd = denominator.gcd(f.denominator);
BigInteger first = numerator.multiply(f.denominator.divide(gcd));
BigInteger second = f.numerator.multiply(denominator.divide(gcd));
return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
}
public Fraction subtract(Fraction f) {
return add(f.negate());
}
public Fraction multiply(Fraction f) {
BigInteger num = numerator.multiply(f.numerator);
BigInteger den = denominator.multiply(f.denominator);
BigInteger gcd = num.gcd(den);
return new Fraction(num.divide(gcd), den.divide(gcd));
}
public Fraction divide(Fraction f) {
return multiply(new Fraction(f.denominator, f.numerator));
}
@Override
public String toString() {
if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
return numerator.toString();
}
return numerator + " / " + denominator;
}
}
private static class Term {
private int coefficient;
private Fraction fraction;
public Term(int c, Fraction f) {
coefficient = c;
fraction = f;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | import math
rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]
init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \
16*[lambda b, c, d: (d & b) | (~d & c)] + \
16*[lambda b, c, d: b ^ c ^ d] + \
16*[lambda b, c, d: c ^ (b | ~d)]
index_functions = 16*[lambda i: i] + \
16*[lambda i: (5*i + 1)%16] + \
16*[lambda i: (3*i + 5)%16] + \
16*[lambda i: (7*i)%16]
def left_rotate(x, amount):
x &= 0xFFFFFFFF
return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF
def md5(message):
message = bytearray(message)
orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message.append(0x80)
while len(message)%64 != 56:
message.append(0)
message += orig_len_in_bits.to_bytes(8, byteorder='little')
hash_pieces = init_values[:]
for chunk_ofst in range(0, len(message), 64):
a, b, c, d = hash_pieces
chunk = message[chunk_ofst:chunk_ofst+64]
for i in range(64):
f = functions[i](b, c, d)
g = index_functions[i](i)
to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
a, b, c, d = d, new_b, b, c
for i, val in enumerate([a, b, c, d]):
hash_pieces[i] += val
hash_pieces[i] &= 0xFFFFFFFF
return sum(x<<(32*i) for i, x in enumerate(hash_pieces))
def md5_to_hex(digest):
raw = digest.to_bytes(16, byteorder='little')
return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))
if __name__=='__main__':
demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz",
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"]
for message in demo:
print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')
| class MD5
{
private static final int INIT_A = 0x67452301;
private static final int INIT_B = (int)0xEFCDAB89L;
private static final int INIT_C = (int)0x98BADCFEL;
private static final int INIT_D = 0x10325476;
private static final int[] SHIFT_AMTS = {
7, 12, 17, 22,
5, 9, 14, 20,
4, 11, 16, 23,
6, 10, 15, 21
};
private static final int[] TABLE_T = new int[64];
static
{
for (int i = 0; i < 64; i++)
TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));
}
public static byte[] computeMD5(byte[] message)
{
int messageLenBytes = message.length;
int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
int totalLen = numBlocks << 6;
byte[] paddingBytes = new byte[totalLen - messageLenBytes];
paddingBytes[0] = (byte)0x80;
long messageLenBits = (long)messageLenBytes << 3;
for (int i = 0; i < 8; i++)
{
paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;
messageLenBits >>>= 8;
}
int a = INIT_A;
int b = INIT_B;
int c = INIT_C;
int d = INIT_D;
int[] buffer = new int[16];
for (int i = 0; i < numBlocks; i ++)
{
int index = i << 6;
for (int j = 0; j < 64; j++, index++)
buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);
int originalA = a;
int originalB = b;
int originalC = c;
int originalD = d;
for (int j = 0; j < 64; j++)
{
int div16 = j >>> 4;
int f = 0;
int bufferIndex = j;
switch (div16)
{
case 0:
f = (b & c) | (~b & d);
break;
case 1:
f = (b & d) | (c & ~d);
bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
break;
case 2:
f = b ^ c ^ d;
bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
break;
case 3:
f = c ^ (b | ~d);
bufferIndex = (bufferIndex * 7) & 0x0F;
break;
}
int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);
a = d;
d = c;
c = b;
b = temp;
}
a += originalA;
b += originalB;
c += originalC;
d += originalD;
}
byte[] md5 = new byte[16];
int count = 0;
for (int i = 0; i < 4; i++)
{
int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
for (int j = 0; j < 4; j++)
{
md5[count++] = (byte)n;
n >>>= 8;
}
}
return md5;
}
public static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
sb.append(String.format("%02X", b[i] & 0xFF));
}
return sb.toString();
}
public static void main(String[] args)
{
String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" };
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"");
return;
}
}
|
Please provide an equivalent version of this Python code in Java. | from math import pi, sin, cos
from collections import namedtuple
from random import random, choice
from copy import copy
try:
import psyco
psyco.full()
except ImportError:
pass
FLOAT_MAX = 1e100
class Point:
__slots__ = ["x", "y", "group"]
def __init__(self, x=0.0, y=0.0, group=0):
self.x, self.y, self.group = x, y, group
def generate_points(npoints, radius):
points = [Point() for _ in xrange(npoints)]
for p in points:
r = random() * radius
ang = random() * 2 * pi
p.x = r * cos(ang)
p.y = r * sin(ang)
return points
def nearest_cluster_center(point, cluster_centers):
def sqr_distance_2D(a, b):
return (a.x - b.x) ** 2 + (a.y - b.y) ** 2
min_index = point.group
min_dist = FLOAT_MAX
for i, cc in enumerate(cluster_centers):
d = sqr_distance_2D(cc, point)
if min_dist > d:
min_dist = d
min_index = i
return (min_index, min_dist)
def kpp(points, cluster_centers):
cluster_centers[0] = copy(choice(points))
d = [0.0 for _ in xrange(len(points))]
for i in xrange(1, len(cluster_centers)):
sum = 0
for j, p in enumerate(points):
d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]
sum += d[j]
sum *= random()
for j, di in enumerate(d):
sum -= di
if sum > 0:
continue
cluster_centers[i] = copy(points[j])
break
for p in points:
p.group = nearest_cluster_center(p, cluster_centers)[0]
def lloyd(points, nclusters):
cluster_centers = [Point() for _ in xrange(nclusters)]
kpp(points, cluster_centers)
lenpts10 = len(points) >> 10
changed = 0
while True:
for cc in cluster_centers:
cc.x = 0
cc.y = 0
cc.group = 0
for p in points:
cluster_centers[p.group].group += 1
cluster_centers[p.group].x += p.x
cluster_centers[p.group].y += p.y
for cc in cluster_centers:
cc.x /= cc.group
cc.y /= cc.group
changed = 0
for p in points:
min_i = nearest_cluster_center(p, cluster_centers)[0]
if min_i != p.group:
changed += 1
p.group = min_i
if changed <= lenpts10:
break
for i, cc in enumerate(cluster_centers):
cc.group = i
return cluster_centers
def print_eps(points, cluster_centers, W=400, H=400):
Color = namedtuple("Color", "r g b");
colors = []
for i in xrange(len(cluster_centers)):
colors.append(Color((3 * (i + 1) % 11) / 11.0,
(7 * i % 11) / 11.0,
(9 * i % 11) / 11.0))
max_x = max_y = -FLOAT_MAX
min_x = min_y = FLOAT_MAX
for p in points:
if max_x < p.x: max_x = p.x
if min_x > p.x: min_x = p.x
if max_y < p.y: max_y = p.y
if min_y > p.y: min_y = p.y
scale = min(W / (max_x - min_x),
H / (max_y - min_y))
cx = (max_x + min_x) / 2
cy = (max_y + min_y) / 2
print "%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %d %d" % (W + 10, H + 10)
print ("/l {rlineto} def /m {rmoveto} def\n" +
"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n" +
"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath " +
" gsave 1 setgray fill grestore gsave 3 setlinewidth" +
" 1 setgray stroke grestore 0 setgray stroke }def")
for i, cc in enumerate(cluster_centers):
print ("%g %g %g setrgbcolor" %
(colors[i].r, colors[i].g, colors[i].b))
for p in points:
if p.group != i:
continue
print ("%.3f %.3f c" % ((p.x - cx) * scale + W / 2,
(p.y - cy) * scale + H / 2))
print ("\n0 setgray %g %g s" % ((cc.x - cx) * scale + W / 2,
(cc.y - cy) * scale + H / 2))
print "\n%%%%EOF"
def main():
npoints = 30000
k = 7
points = generate_points(npoints, 10)
cluster_centers = lloyd(points, k)
print_eps(points, cluster_centers)
main()
| import java.util.Random;
public class KMeansWithKpp{
public Point[] points;
public Point[] centroids;
Random rand;
public int n;
public int k;
private KMeansWithKpp(){
}
KMeansWithKpp(Point[] p, int clusters){
points = p;
n = p.length;
k = Math.max(1, clusters);
centroids = new Point[k];
rand = new Random();
}
private static double distance(Point a, Point b){
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
private static int nearest(Point pt, Point[] others, int len){
double minD = Double.MAX_VALUE;
int index = pt.group;
len = Math.min(others.length, len);
double dist;
for (int i = 0; i < len; i++) {
if (minD > (dist = distance(pt, others[i]))) {
minD = dist;
index = i;
}
}
return index;
}
private static double nearestDistance(Point pt, Point[] others, int len){
double minD = Double.MAX_VALUE;
len = Math.min(others.length, len);
double dist;
for (int i = 0; i < len; i++) {
if (minD > (dist = distance(pt, others[i]))) {
minD = dist;
}
}
return minD;
}
private void kpp(){
centroids[0] = points[rand.nextInt(n)];
double[] dist = new double[n];
double sum = 0;
for (int i = 1; i < k; i++) {
for (int j = 0; j < n; j++) {
dist[j] = nearestDistance(points[j], centroids, i);
sum += dist[j];
}
sum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if ((sum -= dist[j]) > 0)
continue;
centroids[i].x = points[j].x;
centroids[i].y = points[j].y;
}
}
for (int i = 0; i < n; i++) {
points[i].group = nearest(points[i], centroids, k);
}
}
public void kMeans(int maxTimes){
if (k == 1 || n <= 0) {
return;
}
if(k >= n){
for(int i =0; i < n; i++){
points[i].group = i;
}
return;
}
maxTimes = Math.max(1, maxTimes);
int changed;
int bestPercent = n/1000;
int minIndex;
kpp();
do {
for (Point c : centroids) {
c.x = 0.0;
c.y = 0.0;
c.group = 0;
}
for (Point pt : points) {
if(pt.group < 0 || pt.group > centroids.length){
pt.group = rand.nextInt(centroids.length);
}
centroids[pt.group].x += pt.x;
centroids[pt.group].y = pt.y;
centroids[pt.group].group++;
}
for (Point c : centroids) {
c.x /= c.group;
c.y /= c.group;
}
changed = 0;
for (Point pt : points) {
minIndex = nearest(pt, centroids, k);
if (k != pt.group) {
changed++;
pt.group = minIndex;
}
}
maxTimes--;
} while (changed > bestPercent && maxTimes > 0);
}
}
class Point{
public double x;
public double y;
public int group;
Point(){
x = y = 0.0;
group = 0;
}
public Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){
if (size <= 0)
return null;
double xdiff, ydiff;
xdiff = maxX - minX;
ydiff = maxY - minY;
if (minX > maxX) {
xdiff = minX - maxX;
minX = maxX;
}
if (maxY < minY) {
ydiff = minY - maxY;
minY = maxY;
}
Point[] data = new Point[size];
Random rand = new Random();
for (int i = 0; i < size; i++) {
data[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
data[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
}
return data;
}
public Point[] getRandomPolarData(double radius, int size){
if (size <= 0) {
return null;
}
Point[] data = new Point[size];
double radi, arg;
Random rand = new Random();
for (int i = 0; i < size; i++) {
radi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
arg = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
data[i].x = radi * Math.cos(arg);
data[i].y = radi * Math.sin(arg);
}
return data;
}
}
|
Change the following Python code into Java without altering its purpose. | from math import pi, sin, cos
from collections import namedtuple
from random import random, choice
from copy import copy
try:
import psyco
psyco.full()
except ImportError:
pass
FLOAT_MAX = 1e100
class Point:
__slots__ = ["x", "y", "group"]
def __init__(self, x=0.0, y=0.0, group=0):
self.x, self.y, self.group = x, y, group
def generate_points(npoints, radius):
points = [Point() for _ in xrange(npoints)]
for p in points:
r = random() * radius
ang = random() * 2 * pi
p.x = r * cos(ang)
p.y = r * sin(ang)
return points
def nearest_cluster_center(point, cluster_centers):
def sqr_distance_2D(a, b):
return (a.x - b.x) ** 2 + (a.y - b.y) ** 2
min_index = point.group
min_dist = FLOAT_MAX
for i, cc in enumerate(cluster_centers):
d = sqr_distance_2D(cc, point)
if min_dist > d:
min_dist = d
min_index = i
return (min_index, min_dist)
def kpp(points, cluster_centers):
cluster_centers[0] = copy(choice(points))
d = [0.0 for _ in xrange(len(points))]
for i in xrange(1, len(cluster_centers)):
sum = 0
for j, p in enumerate(points):
d[j] = nearest_cluster_center(p, cluster_centers[:i])[1]
sum += d[j]
sum *= random()
for j, di in enumerate(d):
sum -= di
if sum > 0:
continue
cluster_centers[i] = copy(points[j])
break
for p in points:
p.group = nearest_cluster_center(p, cluster_centers)[0]
def lloyd(points, nclusters):
cluster_centers = [Point() for _ in xrange(nclusters)]
kpp(points, cluster_centers)
lenpts10 = len(points) >> 10
changed = 0
while True:
for cc in cluster_centers:
cc.x = 0
cc.y = 0
cc.group = 0
for p in points:
cluster_centers[p.group].group += 1
cluster_centers[p.group].x += p.x
cluster_centers[p.group].y += p.y
for cc in cluster_centers:
cc.x /= cc.group
cc.y /= cc.group
changed = 0
for p in points:
min_i = nearest_cluster_center(p, cluster_centers)[0]
if min_i != p.group:
changed += 1
p.group = min_i
if changed <= lenpts10:
break
for i, cc in enumerate(cluster_centers):
cc.group = i
return cluster_centers
def print_eps(points, cluster_centers, W=400, H=400):
Color = namedtuple("Color", "r g b");
colors = []
for i in xrange(len(cluster_centers)):
colors.append(Color((3 * (i + 1) % 11) / 11.0,
(7 * i % 11) / 11.0,
(9 * i % 11) / 11.0))
max_x = max_y = -FLOAT_MAX
min_x = min_y = FLOAT_MAX
for p in points:
if max_x < p.x: max_x = p.x
if min_x > p.x: min_x = p.x
if max_y < p.y: max_y = p.y
if min_y > p.y: min_y = p.y
scale = min(W / (max_x - min_x),
H / (max_y - min_y))
cx = (max_x + min_x) / 2
cy = (max_y + min_y) / 2
print "%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %d %d" % (W + 10, H + 10)
print ("/l {rlineto} def /m {rmoveto} def\n" +
"/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n" +
"/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath " +
" gsave 1 setgray fill grestore gsave 3 setlinewidth" +
" 1 setgray stroke grestore 0 setgray stroke }def")
for i, cc in enumerate(cluster_centers):
print ("%g %g %g setrgbcolor" %
(colors[i].r, colors[i].g, colors[i].b))
for p in points:
if p.group != i:
continue
print ("%.3f %.3f c" % ((p.x - cx) * scale + W / 2,
(p.y - cy) * scale + H / 2))
print ("\n0 setgray %g %g s" % ((cc.x - cx) * scale + W / 2,
(cc.y - cy) * scale + H / 2))
print "\n%%%%EOF"
def main():
npoints = 30000
k = 7
points = generate_points(npoints, 10)
cluster_centers = lloyd(points, k)
print_eps(points, cluster_centers)
main()
| import java.util.Random;
public class KMeansWithKpp{
public Point[] points;
public Point[] centroids;
Random rand;
public int n;
public int k;
private KMeansWithKpp(){
}
KMeansWithKpp(Point[] p, int clusters){
points = p;
n = p.length;
k = Math.max(1, clusters);
centroids = new Point[k];
rand = new Random();
}
private static double distance(Point a, Point b){
return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
}
private static int nearest(Point pt, Point[] others, int len){
double minD = Double.MAX_VALUE;
int index = pt.group;
len = Math.min(others.length, len);
double dist;
for (int i = 0; i < len; i++) {
if (minD > (dist = distance(pt, others[i]))) {
minD = dist;
index = i;
}
}
return index;
}
private static double nearestDistance(Point pt, Point[] others, int len){
double minD = Double.MAX_VALUE;
len = Math.min(others.length, len);
double dist;
for (int i = 0; i < len; i++) {
if (minD > (dist = distance(pt, others[i]))) {
minD = dist;
}
}
return minD;
}
private void kpp(){
centroids[0] = points[rand.nextInt(n)];
double[] dist = new double[n];
double sum = 0;
for (int i = 1; i < k; i++) {
for (int j = 0; j < n; j++) {
dist[j] = nearestDistance(points[j], centroids, i);
sum += dist[j];
}
sum = (sum * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if ((sum -= dist[j]) > 0)
continue;
centroids[i].x = points[j].x;
centroids[i].y = points[j].y;
}
}
for (int i = 0; i < n; i++) {
points[i].group = nearest(points[i], centroids, k);
}
}
public void kMeans(int maxTimes){
if (k == 1 || n <= 0) {
return;
}
if(k >= n){
for(int i =0; i < n; i++){
points[i].group = i;
}
return;
}
maxTimes = Math.max(1, maxTimes);
int changed;
int bestPercent = n/1000;
int minIndex;
kpp();
do {
for (Point c : centroids) {
c.x = 0.0;
c.y = 0.0;
c.group = 0;
}
for (Point pt : points) {
if(pt.group < 0 || pt.group > centroids.length){
pt.group = rand.nextInt(centroids.length);
}
centroids[pt.group].x += pt.x;
centroids[pt.group].y = pt.y;
centroids[pt.group].group++;
}
for (Point c : centroids) {
c.x /= c.group;
c.y /= c.group;
}
changed = 0;
for (Point pt : points) {
minIndex = nearest(pt, centroids, k);
if (k != pt.group) {
changed++;
pt.group = minIndex;
}
}
maxTimes--;
} while (changed > bestPercent && maxTimes > 0);
}
}
class Point{
public double x;
public double y;
public int group;
Point(){
x = y = 0.0;
group = 0;
}
public Point[] getRandomPlaneData(double minX, double maxX, double minY, double maxY, int size){
if (size <= 0)
return null;
double xdiff, ydiff;
xdiff = maxX - minX;
ydiff = maxY - minY;
if (minX > maxX) {
xdiff = minX - maxX;
minX = maxX;
}
if (maxY < minY) {
ydiff = minY - maxY;
minY = maxY;
}
Point[] data = new Point[size];
Random rand = new Random();
for (int i = 0; i < size; i++) {
data[i].x = minX + (xdiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
data[i].y = minY + (ydiff * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
}
return data;
}
public Point[] getRandomPolarData(double radius, int size){
if (size <= 0) {
return null;
}
Point[] data = new Point[size];
double radi, arg;
Random rand = new Random();
for (int i = 0; i < size; i++) {
radi = (radius * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
arg = (2 * Math.PI * rand.nextInt(Integer.MAX_VALUE)) / Integer.MAX_VALUE;
data[i].x = radi * Math.cos(arg);
data[i].y = radi * Math.sin(arg);
}
return data;
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. |
def Dijkstra(Graph, source):
infinity = float('infinity')
n = len(graph)
dist = [infinity]*n
previous = [infinity]*n
dist[source] = 0
Q = list(range(n))
while Q:
u = min(Q, key=lambda n:dist[n])
Q.remove(u)
if dist[u] == infinity:
break
for v in range(n):
if Graph[u][v] and (v in Q):
alt = dist[u] + Graph[u][v]
if alt < dist[v]:
dist[v] = alt
previous[v] = u
return dist,previous
def display_solution(predecessor):
cell = len(predecessor)-1
while cell:
print(cell,end='<')
cell = predecessor[cell]
print(0)
| import java.io.*;
import java.util.*;
public class MazeSolver
{
private static String[] readLines (InputStream f) throws IOException
{
BufferedReader r =
new BufferedReader (new InputStreamReader (f, "US-ASCII"));
ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = r.readLine()) != null)
lines.add (line);
return lines.toArray(new String[0]);
}
private static char[][] decimateHorizontally (String[] lines)
{
final int width = (lines[0].length() + 1) / 2;
char[][] c = new char[lines.length][width];
for (int i = 0 ; i < lines.length ; i++)
for (int j = 0 ; j < width ; j++)
c[i][j] = lines[i].charAt (j * 2);
return c;
}
private static boolean solveMazeRecursively (char[][] maze,
int x, int y, int d)
{
boolean ok = false;
for (int i = 0 ; i < 4 && !ok ; i++)
if (i != d)
switch (i)
{
case 0:
if (maze[y-1][x] == ' ')
ok = solveMazeRecursively (maze, x, y - 2, 2);
break;
case 1:
if (maze[y][x+1] == ' ')
ok = solveMazeRecursively (maze, x + 2, y, 3);
break;
case 2:
if (maze[y+1][x] == ' ')
ok = solveMazeRecursively (maze, x, y + 2, 0);
break;
case 3:
if (maze[y][x-1] == ' ')
ok = solveMazeRecursively (maze, x - 2, y, 1);
break;
}
if (x == 1 && y == 1)
ok = true;
if (ok)
{
maze[y][x] = '*';
switch (d)
{
case 0:
maze[y-1][x] = '*';
break;
case 1:
maze[y][x+1] = '*';
break;
case 2:
maze[y+1][x] = '*';
break;
case 3:
maze[y][x-1] = '*';
break;
}
}
return ok;
}
private static void solveMaze (char[][] maze)
{
solveMazeRecursively (maze, maze[0].length - 2, maze.length - 2, -1);
}
private static String[] expandHorizontally (char[][] maze)
{
char[] tmp = new char[3];
String[] lines = new String[maze.length];
for (int i = 0 ; i < maze.length ; i++)
{
StringBuilder sb = new StringBuilder(maze[i].length * 2);
for (int j = 0 ; j < maze[i].length ; j++)
if (j % 2 == 0)
sb.append (maze[i][j]);
else
{
tmp[0] = tmp[1] = tmp[2] = maze[i][j];
if (tmp[1] == '*')
tmp[0] = tmp[2] = ' ';
sb.append (tmp);
}
lines[i] = sb.toString();
}
return lines;
}
public static void main (String[] args) throws IOException
{
InputStream f = (args.length > 0
? new FileInputStream (args[0])
: System.in);
String[] lines = readLines (f);
char[][] maze = decimateHorizontally (lines);
solveMaze (maze);
String[] solvedLines = expandHorizontally (maze);
for (int i = 0 ; i < solvedLines.length ; i++)
System.out.println (solvedLines[i]);
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | import random
print(random.sample(range(1, 21), 20))
| import java.util.*;
public class RandomShuffle {
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
for (int j = 1; j <= 20; ++j)
list.add(j);
Collections.shuffle(list, rand);
System.out.println(list);
}
}
|
Translate the given Python code snippet into Java without altering its behavior. |
def DrawBoard(board):
peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for n in xrange(1,16):
peg[n] = '.'
if n in board:
peg[n] = "%X" % n
print " %s" % peg[1]
print " %s %s" % (peg[2],peg[3])
print " %s %s %s" % (peg[4],peg[5],peg[6])
print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10])
print " %s %s %s %s %s" % (peg[11],peg[12],peg[13],peg[14],peg[15])
def RemovePeg(board,n):
board.remove(n)
def AddPeg(board,n):
board.append(n)
def IsPeg(board,n):
return n in board
JumpMoves = { 1: [ (2,4),(3,6) ],
2: [ (4,7),(5,9) ],
3: [ (5,8),(6,10) ],
4: [ (2,1),(5,6),(7,11),(8,13) ],
5: [ (8,12),(9,14) ],
6: [ (3,1),(5,4),(9,13),(10,15) ],
7: [ (4,2),(8,9) ],
8: [ (5,3),(9,10) ],
9: [ (5,2),(8,7) ],
10: [ (9,8) ],
11: [ (12,13) ],
12: [ (8,5),(13,14) ],
13: [ (8,4),(9,6),(12,11),(14,15) ],
14: [ (9,5),(13,12) ],
15: [ (10,6),(14,13) ]
}
Solution = []
def Solve(board):
if len(board) == 1:
return board
for peg in xrange(1,16):
if IsPeg(board,peg):
movelist = JumpMoves[peg]
for over,land in movelist:
if IsPeg(board,over) and not IsPeg(board,land):
saveboard = board[:]
RemovePeg(board,peg)
RemovePeg(board,over)
AddPeg(board,land)
Solution.append((peg,over,land))
board = Solve(board)
if len(board) == 1:
return board
board = saveboard[:]
del Solution[-1]
return board
def InitSolve(empty):
board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
RemovePeg(board,empty_start)
Solve(board)
empty_start = 1
InitSolve(empty_start)
board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
RemovePeg(board,empty_start)
for peg,over,land in Solution:
RemovePeg(board,peg)
RemovePeg(board,over)
AddPeg(board,land)
DrawBoard(board)
print "Peg %X jumped over %X to land on %X\n" % (peg,over,land)
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class IQPuzzle {
public static void main(String[] args) {
System.out.printf(" ");
for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {
System.out.printf(" %,6d", start);
}
System.out.printf("%n");
for ( int start = 1 ; start < Puzzle.MAX_PEGS ; start++ ) {
System.out.printf("%2d", start);
Map<Integer,Integer> solutions = solve(start);
for ( int end = 1 ; end < Puzzle.MAX_PEGS ; end++ ) {
System.out.printf(" %,6d", solutions.containsKey(end) ? solutions.get(end) : 0);
}
System.out.printf("%n");
}
int moveNum = 0;
System.out.printf("%nOne Solution:%n");
for ( Move m : oneSolution ) {
moveNum++;
System.out.printf("Move %d = %s%n", moveNum, m);
}
}
private static List<Move> oneSolution = null;
private static Map<Integer, Integer> solve(int emptyPeg) {
Puzzle puzzle = new Puzzle(emptyPeg);
Map<Integer,Integer> solutions = new HashMap<>();
Stack<Puzzle> stack = new Stack<Puzzle>();
stack.push(puzzle);
while ( ! stack.isEmpty() ) {
Puzzle p = stack.pop();
if ( p.solved() ) {
solutions.merge(p.getLastPeg(), 1, (v1,v2) -> v1 + v2);
if ( oneSolution == null ) {
oneSolution = p.moves;
}
continue;
}
for ( Move move : p.getValidMoves() ) {
Puzzle pMove = p.move(move);
stack.add(pMove);
}
}
return solutions;
}
private static class Puzzle {
public static int MAX_PEGS = 16;
private boolean[] pegs = new boolean[MAX_PEGS];
private List<Move> moves;
public Puzzle(int emptyPeg) {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
pegs[i] = true;
}
pegs[emptyPeg] = false;
moves = new ArrayList<>();
}
public Puzzle() {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
pegs[i] = true;
}
moves = new ArrayList<>();
}
private static Map<Integer,List<Move>> validMoves = new HashMap<>();
static {
validMoves.put(1, Arrays.asList(new Move(1, 2, 4), new Move(1, 3, 6)));
validMoves.put(2, Arrays.asList(new Move(2, 4, 7), new Move(2, 5, 9)));
validMoves.put(3, Arrays.asList(new Move(3, 5, 8), new Move(3, 6, 10)));
validMoves.put(4, Arrays.asList(new Move(4, 2, 1), new Move(4, 5, 6), new Move(4, 8, 13), new Move(4, 7, 11)));
validMoves.put(5, Arrays.asList(new Move(5, 8, 12), new Move(5, 9, 14)));
validMoves.put(6, Arrays.asList(new Move(6, 3, 1), new Move(6, 5, 4), new Move(6, 9, 13), new Move(6, 10, 15)));
validMoves.put(7, Arrays.asList(new Move(7, 4, 2), new Move(7, 8, 9)));
validMoves.put(8, Arrays.asList(new Move(8, 5, 3), new Move(8, 9, 10)));
validMoves.put(9, Arrays.asList(new Move(9, 5, 2), new Move(9, 8, 7)));
validMoves.put(10, Arrays.asList(new Move(10, 6, 3), new Move(10, 9, 8)));
validMoves.put(11, Arrays.asList(new Move(11, 7, 4), new Move(11, 12, 13)));
validMoves.put(12, Arrays.asList(new Move(12, 8, 5), new Move(12, 13, 14)));
validMoves.put(13, Arrays.asList(new Move(13, 12, 11), new Move(13, 8, 4), new Move(13, 9, 6), new Move(13, 14, 15)));
validMoves.put(14, Arrays.asList(new Move(14, 13, 12), new Move(14, 9, 5)));
validMoves.put(15, Arrays.asList(new Move(15, 14, 13), new Move(15, 10, 6)));
}
public List<Move> getValidMoves() {
List<Move> moves = new ArrayList<Move>();
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
for ( Move testMove : validMoves.get(i) ) {
if ( pegs[testMove.jump] && ! pegs[testMove.end] ) {
moves.add(testMove);
}
}
}
}
return moves;
}
public boolean solved() {
boolean foundFirstPeg = false;
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
if ( foundFirstPeg ) {
return false;
}
foundFirstPeg = true;
}
}
return true;
}
public Puzzle move(Move move) {
Puzzle p = new Puzzle();
if ( ! pegs[move.start] || ! pegs[move.jump] || pegs[move.end] ) {
throw new RuntimeException("Invalid move.");
}
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
p.pegs[i] = pegs[i];
}
p.pegs[move.start] = false;
p.pegs[move.jump] = false;
p.pegs[move.end] = true;
for ( Move m : moves ) {
p.moves.add(new Move(m.start, m.jump, m.end));
}
p.moves.add(new Move(move.start, move.jump, move.end));
return p;
}
public int getLastPeg() {
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
if ( pegs[i] ) {
return i;
}
}
throw new RuntimeException("ERROR: Illegal position.");
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for ( int i = 1 ; i < MAX_PEGS ; i++ ) {
sb.append(pegs[i] ? 1 : 0);
sb.append(",");
}
sb.setLength(sb.length()-1);
sb.append("]");
return sb.toString();
}
}
private static class Move {
int start;
int jump;
int end;
public Move(int s, int j, int e) {
start = s; jump = j; end = e;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("s=" + start);
sb.append(", j=" + jump);
sb.append(", e=" + end);
sb.append("}");
return sb.toString();
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | from itertools import combinations_with_replacement as cmbr
from time import time
def dice_gen(n, faces, m):
dice = list(cmbr(faces, n))
succ = [set(j for j, b in enumerate(dice)
if sum((x>y) - (x<y) for x in a for y in b) > 0)
for a in dice]
def loops(seq):
s = succ[seq[-1]]
if len(seq) == m:
if seq[0] in s: yield seq
return
for d in (x for x in s if x > seq[0] and not x in seq):
yield from loops(seq + (d,))
yield from (tuple(''.join(dice[s]) for s in x)
for i, v in enumerate(succ)
for x in loops((i,)))
t = time()
for n, faces, loop_len in [(4, '1234', 3), (4, '1234', 4), (6, '123456', 3), (6, '1234567', 3)]:
for i, x in enumerate(dice_gen(n, faces, loop_len)): pass
print(f'{n}-sided, markings {faces}, loop length {loop_len}:')
print(f'\t{i + 1}*{loop_len} solutions, e.g. {" > ".join(x)} > [loop]')
t, t0 = time(), t
print(f'\ttime: {t - t0:.4f} seconds\n')
| import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
private static List<List<Integer>> fourFaceCombos() {
List<List<Integer>> res = new ArrayList<>();
Set<Integer> found = new HashSet<>();
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
for (int k = 1; k <= 4; k++) {
for (int l = 1; l <= 4; l++) {
List<Integer> c = IntStream.of(i, j, k, l).sorted().boxed().collect(Collectors.toList());
int key = 64 * (c.get(0) - 1) + 16 * (c.get(1) - 1) + 4 * (c.get(2) - 1) + (c.get(3) - 1);
if (found.add(key)) {
res.add(c);
}
}
}
}
}
return res;
}
private static int cmp(List<Integer> x, List<Integer> y) {
int xw = 0;
int yw = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (x.get(i) > y.get(j)) {
xw++;
} else if (x.get(i) < y.get(j)) {
yw++;
}
}
}
return Integer.compare(xw, yw);
}
private static List<List<List<Integer>>> findIntransitive3(List<List<Integer>> cs) {
int c = cs.size();
List<List<List<Integer>>> res = new ArrayList<>();
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
if (cmp(cs.get(i), cs.get(j)) == -1) {
for (List<Integer> kl : cs) {
if (cmp(cs.get(j), kl) == -1 && cmp(kl, cs.get(i)) == -1) {
res.add(List.of(cs.get(i), cs.get(j), kl));
}
}
}
}
}
return res;
}
private static List<List<List<Integer>>> findIntransitive4(List<List<Integer>> cs) {
int c = cs.size();
List<List<List<Integer>>> res = new ArrayList<>();
for (int i = 0; i < c; i++) {
for (int j = 0; j < c; j++) {
if (cmp(cs.get(i), cs.get(j)) == -1) {
for (int k = 0; k < cs.size(); k++) {
if (cmp(cs.get(j), cs.get(k)) == -1) {
for (List<Integer> ll : cs) {
if (cmp(cs.get(k), ll) == -1 && cmp(ll, cs.get(i)) == -1) {
res.add(List.of(cs.get(i), cs.get(j), cs.get(k), ll));
}
}
}
}
}
}
}
return res;
}
public static void main(String[] args) {
List<List<Integer>> combos = fourFaceCombos();
System.out.printf("Number of eligible 4-faced dice: %d%n", combos.size());
System.out.println();
List<List<List<Integer>>> it3 = findIntransitive3(combos);
System.out.printf("%d ordered lists of 3 non-transitive dice found, namely:%n", it3.size());
for (List<List<Integer>> a : it3) {
System.out.println(a);
}
System.out.println();
List<List<List<Integer>>> it4 = findIntransitive4(combos);
System.out.printf("%d ordered lists of 4 non-transitive dice found, namely:%n", it4.size());
for (List<List<Integer>> a : it4) {
System.out.println(a);
}
}
}
|
Change the following Python code into Java without altering its purpose. | import sys
HIST = {}
def trace(frame, event, arg):
for name,val in frame.f_locals.items():
if name not in HIST:
HIST[name] = []
else:
if HIST[name][-1] is val:
continue
HIST[name].append(val)
return trace
def undo(name):
HIST[name].pop(-1)
return HIST[name][-1]
def main():
a = 10
a = 20
for i in range(5):
c = i
print "c:", c, "-> undo x3 ->",
c = undo('c')
c = undo('c')
c = undo('c')
print c
print 'HIST:', HIST
sys.settrace(trace)
main()
| public class HistoryVariable
{
private Object value;
public HistoryVariable(Object v)
{
value = v;
}
public void update(Object v)
{
value = v;
}
public Object undo()
{
return value;
}
@Override
public String toString()
{
return value.toString();
}
public void dispose()
{
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import random
TRAINING_LENGTH = 2000
class Perceptron:
def __init__(self,n):
self.c = .01
self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)]
def feed_forward(self, inputs):
vars = []
for i in range(len(inputs)):
vars.append(inputs[i] * self.weights[i])
return self.activate(sum(vars))
def activate(self, value):
return 1 if value > 0 else -1
def train(self, inputs, desired):
guess = self.feed_forward(inputs)
error = desired - guess
for i in range(len(inputs)):
self.weights[i] += self.c * error * inputs[i]
class Trainer():
def __init__(self, x, y, a):
self.inputs = [x, y, 1]
self.answer = a
def F(x):
return 2 * x + 1
if __name__ == "__main__":
ptron = Perceptron(3)
training = []
for i in range(TRAINING_LENGTH):
x = random.uniform(-10,10)
y = random.uniform(-10,10)
answer = 1
if y < F(x): answer = -1
training.append(Trainer(x,y,answer))
result = []
for y in range(-10,10):
temp = []
for x in range(-10,10):
if ptron.feed_forward([x,y,1]) == 1:
temp.append('^')
else:
temp.append('.')
result.append(temp)
print('Untrained')
for row in result:
print(''.join(v for v in row))
for t in training:
ptron.train(t.inputs, t.answer)
result = []
for y in range(-10,10):
temp = []
for x in range(-10,10):
if ptron.feed_forward([x,y,1]) == 1:
temp.append('^')
else:
temp.append('.')
result.append(temp)
print('Trained')
for row in result:
print(''.join(v for v in row))
| import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class Perceptron extends JPanel {
class Trainer {
double[] inputs;
int answer;
Trainer(double x, double y, int a) {
inputs = new double[]{x, y, 1};
answer = a;
}
}
Trainer[] training = new Trainer[2000];
double[] weights;
double c = 0.00001;
int count;
public Perceptron(int n) {
Random r = new Random();
Dimension dim = new Dimension(640, 360);
setPreferredSize(dim);
setBackground(Color.white);
weights = new double[n];
for (int i = 0; i < weights.length; i++) {
weights[i] = r.nextDouble() * 2 - 1;
}
for (int i = 0; i < training.length; i++) {
double x = r.nextDouble() * dim.width;
double y = r.nextDouble() * dim.height;
int answer = y < f(x) ? -1 : 1;
training[i] = new Trainer(x, y, answer);
}
new Timer(10, (ActionEvent e) -> {
repaint();
}).start();
}
private double f(double x) {
return x * 0.7 + 40;
}
int feedForward(double[] inputs) {
assert inputs.length == weights.length : "weights and input length mismatch";
double sum = 0;
for (int i = 0; i < weights.length; i++) {
sum += inputs[i] * weights[i];
}
return activate(sum);
}
int activate(double s) {
return s > 0 ? 1 : -1;
}
void train(double[] inputs, int desired) {
int guess = feedForward(inputs);
double error = desired - guess;
for (int i = 0; i < weights.length; i++) {
weights[i] += c * error * inputs[i];
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int x = getWidth();
int y = (int) f(x);
g.setStroke(new BasicStroke(2));
g.setColor(Color.orange);
g.drawLine(0, (int) f(0), x, y);
train(training[count].inputs, training[count].answer);
count = (count + 1) % training.length;
g.setStroke(new BasicStroke(1));
g.setColor(Color.black);
for (int i = 0; i < count; i++) {
int guess = feedForward(training[i].inputs);
x = (int) training[i].inputs[0] - 4;
y = (int) training[i].inputs[1] - 4;
if (guess > 0)
g.drawOval(x, y, 8, 8);
else
g.fillOval(x, y, 8, 8);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Perceptron");
f.setResizable(false);
f.add(new Perceptron(3), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | >>> exec
10
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
}
|
Write the same code in Java as shown below in Python. | >>> exec
10
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
public class Evaluator{
public static void main(String[] args){
new Evaluator().eval(
"SayHello",
"public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
"speak"
);
}
void eval(String className, String classCode, String methodName){
Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if ( null == compiler )
throw new RuntimeException("Could not get a compiler.");
StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null);
ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
throws IOException{
if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
return new SimpleJavaFileObject(URI.create("mem:
@Override
public OutputStream openOutputStream()
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
classCache.put(className, baos);
return baos;
}
};
else
throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
}
};
List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
add(
new SimpleJavaFileObject(URI.create("string:
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors){
return classCode;
}
}
);
}};
compiler.getTask(null, fjfm, null, null, null, files).call();
try{
Class<?> clarse = new ClassLoader(){
@Override
public Class<?> findClass(String name){
if (! name.startsWith(className))
throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
byte[] bytes = classCache.get(name).toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
}.loadClass(className);
clarse.getMethod(methodName).invoke(clarse.newInstance());
}catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
throw new RuntimeException("Run failed: " + x, x);
}
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | from sympy import isprime, lcm, factorint, primerange
from functools import reduce
def pisano1(m):
"Simple definition"
if m < 2:
return 1
lastn, n = 0, 1
for i in range(m ** 2):
lastn, n = n, (lastn + n) % m
if lastn == 0 and n == 1:
return i + 1
return 1
def pisanoprime(p, k):
"Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1"
assert isprime(p) and k > 0
return p ** (k - 1) * pisano1(p)
def pisano_mult(m, n):
"pisano(m*n) where m and n assumed coprime integers"
return lcm(pisano1(m), pisano1(n))
def pisano2(m):
"Uses prime factorization of m"
return reduce(lcm, (pisanoprime(prime, mult)
for prime, mult in factorint(m).items()), 1)
if __name__ == '__main__':
for n in range(1, 181):
assert pisano1(n) == pisano2(n), "Wall-Sun-Sun prime exists??!!"
print("\nPisano period (p, 2) for primes less than 50\n ",
[pisanoprime(prime, 2) for prime in primerange(1, 50)])
print("\nPisano period (p, 1) for primes less than 180\n ",
[pisanoprime(prime, 1) for prime in primerange(1, 180)])
print("\nPisano period (p) for integers 1 to 180")
for i in range(1, 181):
print(" %3d" % pisano2(i), end="" if i % 10 else "\n")
| import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class PisanoPeriod {
public static void main(String[] args) {
System.out.printf("Print pisano(p^2) for every prime p lower than 15%n");
for ( long i = 2 ; i < 15 ; i++ ) {
if ( isPrime(i) ) {
long n = i*i;
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(p) for every prime p lower than 180%n");
for ( long n = 2 ; n < 180 ; n++ ) {
if ( isPrime(n) ) {
System.out.printf("pisano(%d) = %d%n", n, pisano(n));
}
}
System.out.printf("%nPrint pisano(n) for every integer from 1 to 180%n");
for ( long n = 1 ; n <= 180 ; n++ ) {
System.out.printf("%3d ", pisano(n));
if ( n % 10 == 0 ) {
System.out.printf("%n");
}
}
}
private static final boolean isPrime(long test) {
if ( test == 2 ) {
return true;
}
if ( test % 2 == 0 ) {
return false;
}
for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
if ( test % i == 0 ) {
return false;
}
}
return true;
}
private static Map<Long,Long> PERIOD_MEMO = new HashMap<>();
static {
PERIOD_MEMO.put(2L, 3L);
PERIOD_MEMO.put(3L, 8L);
PERIOD_MEMO.put(5L, 20L);
}
private static long pisano(long n) {
if ( PERIOD_MEMO.containsKey(n) ) {
return PERIOD_MEMO.get(n);
}
if ( n == 1 ) {
return 1;
}
Map<Long,Long> factors = getFactors(n);
if ( factors.size() == 1 & factors.get(2L) != null && factors.get(2L) > 0 ) {
long result = 3 * n / 2;
PERIOD_MEMO.put(n, result);
return result;
}
if ( factors.size() == 1 & factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 4*n;
PERIOD_MEMO.put(n, result);
return result;
}
if ( factors.size() == 2 & factors.get(2L) != null && factors.get(2L) == 1 && factors.get(5L) != null && factors.get(5L) > 0 ) {
long result = 6*n;
PERIOD_MEMO.put(n, result);
return result;
}
List<Long> primes = new ArrayList<>(factors.keySet());
long prime = primes.get(0);
if ( factors.size() == 1 && factors.get(prime) == 1 ) {
List<Long> divisors = new ArrayList<>();
if ( n % 10 == 1 || n % 10 == 9 ) {
for ( long divisor : getDivisors(prime-1) ) {
if ( divisor % 2 == 0 ) {
divisors.add(divisor);
}
}
}
else {
List<Long> pPlus1Divisors = getDivisors(prime+1);
for ( long divisor : getDivisors(2*prime+2) ) {
if ( ! pPlus1Divisors.contains(divisor) ) {
divisors.add(divisor);
}
}
}
Collections.sort(divisors);
for ( long divisor : divisors ) {
if ( fibModIdentity(divisor, prime) ) {
PERIOD_MEMO.put(prime, divisor);
return divisor;
}
}
throw new RuntimeException("ERROR 144: Divisor not found.");
}
long period = (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime);
for ( int i = 1 ; i < primes.size() ; i++ ) {
prime = primes.get(i);
period = lcm(period, (long) Math.pow(prime, factors.get(prime)-1) * pisano(prime));
}
PERIOD_MEMO.put(n, period);
return period;
}
private static boolean fibModIdentity(long n, long mod) {
long aRes = 0;
long bRes = 1;
long cRes = 1;
long aBase = 0;
long bBase = 1;
long cBase = 1;
while ( n > 0 ) {
if ( n % 2 == 1 ) {
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aRes > SQRT || aBase > SQRT || bRes > SQRT || bBase > SQRT || cBase > SQRT || cRes > SQRT ) {
temp1 = (multiply(aRes, aBase, mod) + multiply(bRes, bBase, mod)) % mod;
temp2 = (multiply(aBase, bRes, mod) + multiply(bBase, cRes, mod)) % mod;
temp3 = (multiply(bBase, bRes, mod) + multiply(cBase, cRes, mod)) % mod;
}
else {
temp1 = ((aRes*aBase % mod) + (bRes*bBase % mod)) % mod;
temp2 = ((aBase*bRes % mod) + (bBase*cRes % mod)) % mod;
temp3 = ((bBase*bRes % mod) + (cBase*cRes % mod)) % mod;
}
aRes = temp1;
bRes = temp2;
cRes = temp3;
}
n >>= 1L;
long temp1 = 0, temp2 = 0, temp3 = 0;
if ( aBase > SQRT || bBase > SQRT || cBase > SQRT ) {
temp1 = (multiply(aBase, aBase, mod) + multiply(bBase, bBase, mod)) % mod;
temp2 = (multiply(aBase, bBase, mod) + multiply(bBase, cBase, mod)) % mod;
temp3 = (multiply(bBase, bBase, mod) + multiply(cBase, cBase, mod)) % mod;
}
else {
temp1 = ((aBase*aBase % mod) + (bBase*bBase % mod)) % mod;
temp2 = ((aBase*bBase % mod) + (bBase*cBase % mod)) % mod;
temp3 = ((bBase*bBase % mod) + (cBase*cBase % mod)) % mod;
}
aBase = temp1;
bBase = temp2;
cBase = temp3;
}
return aRes % mod == 0 && bRes % mod == 1 && cRes % mod == 1;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
private static final List<Long> getDivisors(long number) {
List<Long> divisors = new ArrayList<>();
long sqrt = (long) Math.sqrt(number);
for ( long i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
long div = number / i;
if ( div != i ) {
divisors.add(div);
}
}
}
return divisors;
}
public static long lcm(long a, long b) {
return a*b/gcd(a,b);
}
public static long gcd(long a, long b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
private static final Map<Long,Map<Long,Long>> allFactors = new TreeMap<Long,Map<Long,Long>>();
static {
Map<Long,Long> factors = new TreeMap<Long,Long>();
factors.put(2L, 1L);
allFactors.put(2L, factors);
}
public static Long MAX_ALL_FACTORS = 100000L;
public static final Map<Long,Long> getFactors(Long number) {
if ( allFactors.containsKey(number) ) {
return allFactors.get(number);
}
Map<Long,Long> factors = new TreeMap<Long,Long>();
if ( number % 2 == 0 ) {
Map<Long,Long> factorsdDivTwo = getFactors(number/2);
factors.putAll(factorsdDivTwo);
factors.merge(2L, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
boolean prime = true;
long sqrt = (long) Math.sqrt(number);
for ( long i = 3 ; i <= sqrt ; i += 2 ) {
if ( number % i == 0 ) {
prime = false;
factors.putAll(getFactors(number/i));
factors.merge(i, 1L, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
return factors;
}
}
if ( prime ) {
factors.put(number, 1L);
if ( number < MAX_ALL_FACTORS ) {
allFactors.put(number, factors);
}
}
return factors;
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | from itertools import count, islice
import numpy as np
from numpy import sin, cos, pi
ANGDIV = 12
ANG = 2*pi/ANGDIV
def draw_all(sols):
import matplotlib.pyplot as plt
def draw_track(ax, s):
turn, xend, yend = 0, [0], [0]
for d in s:
x0, y0 = xend[-1], yend[-1]
a = turn*ANG
cs, sn = cos(a), sin(a)
ang = a + d*pi/2
cx, cy = x0 + cos(ang), y0 + sin(ang)
da = np.linspace(ang, ang + d*ANG, 10)
xs = cx - cos(da)
ys = cy - sin(da)
ax.plot(xs, ys, 'green' if d == -1 else 'orange')
xend.append(xs[-1])
yend.append(ys[-1])
turn += d
ax.plot(xend, yend, 'k.', markersize=1)
ax.set_aspect(1)
ls = len(sols)
if ls == 0: return
w, h = min((abs(w*2 - h*3) + w*h - ls, w, h)
for w, h in ((w, (ls + w - 1)//w)
for w in range(1, ls + 1)))[1:]
fig, ax = plt.subplots(h, w, squeeze=False)
for a in ax.ravel(): a.set_axis_off()
for i, s in enumerate(sols):
draw_track(ax[i//w, i%w], s)
plt.show()
def match_up(this, that, equal_lr, seen):
if not this or not that: return
n = len(this[0][-1])
n2 = n*2
l_lo, l_hi, r_lo, r_hi = 0, 0, 0, 0
def record(m):
for _ in range(n2):
seen[m] = True
m = (m&1) << (n2 - 1) | (m >> 1)
if equal_lr:
m ^= (1<<n2) - 1
for _ in range(n2):
seen[m] = True
m = (m&1) << (n2 - 1) | (m >> 1)
l_n, r_n = len(this), len(that)
tol = 1e-3
while l_lo < l_n:
while l_hi < l_n and this[l_hi][0] - this[l_lo][0] <= tol:
l_hi += 1
while r_lo < r_n and that[r_lo][0] < this[l_lo][0] - tol:
r_lo += 1
r_hi = r_lo
while r_hi < r_n and that[r_hi][0] < this[l_lo][0] + tol:
r_hi += 1
for a in this[l_lo:l_hi]:
m_left = a[-2]<<n
for b in that[r_lo:r_hi]:
if (m := m_left | b[-2]) not in seen:
if np.abs(a[1] + b[2]) < tol:
record(m)
record(int(f'{m:b}'[::-1], base=2))
yield(a[-1] + b[-1])
l_lo, r_lo = l_hi, r_hi
def track_combo(left, right):
n = (left + right)//2
n1 = left + right - n
alphas = np.exp(1j*ANG*np.arange(ANGDIV))
def half_track(m, n):
turns = tuple(1 - 2*(m>>i & 1) for i in range(n))
rcnt = np.cumsum(turns)%ANGDIV
asum = np.sum(alphas[rcnt])
want = asum/alphas[rcnt[-1]]
return np.abs(asum), asum, want, m, turns
res = [[] for _ in range(right + 1)]
for i in range(1<<n):
b = i.bit_count()
if b <= right:
res[b].append(half_track(i, n))
for v in res: v.sort()
if n1 == n:
return res, res
res1 = [[] for _ in range(right + 1)]
for i in range(1<<n1):
b = i.bit_count()
if b <= right:
res1[b].append(half_track(i, n1))
for v in res: v.sort()
return res, res1
def railway(n):
seen = {}
for l in range(n//2, n + 1):
r = n - l
if not l >= r: continue
if (l - r)%ANGDIV == 0:
res_l, res_r = track_combo(l, r)
for i, this in enumerate(res_l):
if 2*i < r: continue
that = res_r[r - i]
for s in match_up(this, that, l == r, seen):
yield s
sols = []
for i, s in enumerate(railway(30)):
print(i + 1, s)
sols.append(s)
draw_all(sols[:40])
| package railwaycircuit;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.IntStream.range;
public class RailwayCircuit {
final static int RIGHT = 1, LEFT = -1, STRAIGHT = 0;
static String normalize(int[] tracks) {
char[] a = new char[tracks.length];
for (int i = 0; i < a.length; i++)
a[i] = "abc".charAt(tracks[i] + 1);
String norm = new String(a);
for (int i = 0, len = a.length; i < len; i++) {
String s = new String(a);
if (s.compareTo(norm) < 0)
norm = s;
char tmp = a[0];
for (int j = 1; j < a.length; j++)
a[j - 1] = a[j];
a[len - 1] = tmp;
}
return norm;
}
static boolean fullCircleStraight(int[] tracks, int nStraight) {
if (nStraight == 0)
return true;
if (stream(tracks).filter(i -> i == STRAIGHT).count() != nStraight)
return false;
int[] straight = new int[12];
for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {
if (tracks[i] == STRAIGHT)
straight[idx % 12]++;
idx += tracks[i];
}
return !(range(0, 6).anyMatch(i -> straight[i] != straight[i + 6])
&& range(0, 8).anyMatch(i -> straight[i] != straight[i + 4]));
}
static boolean fullCircleRight(int[] tracks) {
if (stream(tracks).map(i -> i * 30).sum() % 360 != 0)
return false;
int[] rTurns = new int[12];
for (int i = 0, idx = 0; i < tracks.length && idx >= 0; i++) {
if (tracks[i] == RIGHT)
rTurns[idx % 12]++;
idx += tracks[i];
}
return !(range(0, 6).anyMatch(i -> rTurns[i] != rTurns[i + 6])
&& range(0, 8).anyMatch(i -> rTurns[i] != rTurns[i + 4]));
}
static void circuits(int nCurved, int nStraight) {
Map<String, int[]> solutions = new HashMap<>();
PermutationsGen gen = getPermutationsGen(nCurved, nStraight);
while (gen.hasNext()) {
int[] tracks = gen.next();
if (!fullCircleStraight(tracks, nStraight))
continue;
if (!fullCircleRight(tracks))
continue;
solutions.put(normalize(tracks), tracks.clone());
}
report(solutions, nCurved, nStraight);
}
static PermutationsGen getPermutationsGen(int nCurved, int nStraight) {
assert (nCurved + nStraight - 12) % 4 == 0 : "input must be 12 + k * 4";
int[] trackTypes = new int[]{RIGHT, LEFT};
if (nStraight != 0) {
if (nCurved == 12)
trackTypes = new int[]{RIGHT, STRAIGHT};
else
trackTypes = new int[]{RIGHT, LEFT, STRAIGHT};
}
return new PermutationsGen(nCurved + nStraight, trackTypes);
}
static void report(Map<String, int[]> sol, int numC, int numS) {
int size = sol.size();
System.out.printf("%n%d solution(s) for C%d,%d %n", size, numC, numS);
if (size < 10)
sol.values().stream().forEach(tracks -> {
stream(tracks).forEach(i -> System.out.printf("%2d ", i));
System.out.println();
});
}
public static void main(String[] args) {
circuits(12, 0);
circuits(16, 0);
circuits(20, 0);
circuits(24, 0);
circuits(12, 4);
}
}
class PermutationsGen {
private int[] indices;
private int[] choices;
private int[] sequence;
private int carry;
PermutationsGen(int numPositions, int[] choices) {
indices = new int[numPositions];
sequence = new int[numPositions];
this.choices = choices;
}
int[] next() {
carry = 1;
for (int i = 1; i < indices.length && carry > 0; i++) {
indices[i] += carry;
carry = 0;
if (indices[i] == choices.length) {
carry = 1;
indices[i] = 0;
}
}
for (int i = 0; i < indices.length; i++)
sequence[i] = choices[indices[i]];
return sequence;
}
boolean hasNext() {
return carry != 1;
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. |
from math import radians, degrees, sin, cos, asin, atan2, sqrt
from pandas import read_csv
EARTH_RADIUS_KM = 6372.8
TASK_CONVERT_NM = 0.0094174
AIRPORT_DATA_FILE = 'airports.dat.txt'
QUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581
def haversine(lat1, lon1, lat2, lon2):
rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]
dlat = rlat2 - rlat1
dlon = rlon2 - rlon1
arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2
clen = 2.0 * degrees(asin(sqrt(arc)))
theta = atan2(sin(dlon) * cos(rlat2),
cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))
theta = (degrees(theta) + 360) % 360
return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta
def find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):
airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[
'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])
airports['Distance'] = 0.0
airports['Bearing'] = 0
for (idx, row) in enumerate(airports.itertuples()):
distance, bearing = haversine(
latitude, longitude, row.Latitude, row.Longitude)
airports.at[idx, 'Distance'] = round(distance, ndigits=1)
airports.at[idx, 'Bearing'] = int(round(bearing))
airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)
return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]
print(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))
|
package distanceAndBearing;
public class Airport {
private String airport;
private String country;
private String icao;
private double lat;
private double lon;
public String getAirportName() { return this.airport; }
public void setAirportName(String airport) { this.airport = airport; }
public String getCountry() { return this.country; }
public void setCountry(String country) { this.country = country; }
public String getIcao() { return this.icao; }
public void setIcao(String icao) { this.icao = icao; }
public double getLat() { return this.lat; }
public void setLat(double lat) { this.lat = lat; }
public double getLon() { return this.lon; }
public void setLon(double lon) { this.lon = lon; }
@Override
public String toString() {return "Airport: " + getAirportName() + ": ICAO: " + getIcao();}
}
package distanceAndBearing;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
public class DistanceAndBearing {
private final double earthRadius = 6371;
private File datFile;
private List<Airport> airports;
public DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }
public boolean readFile(String filename) {
this.datFile = new File(filename);
try {
Scanner fileScanner = new Scanner(datFile);
String line;
while (fileScanner.hasNextLine()) {
line = fileScanner.nextLine();
line = line.replace(", ", "; ");
line = line.replace(",\",\"", "\",\"");
String[] parts = line.split(",");
Airport airport = new Airport();
airport.setAirportName(parts[1].replace("\"", ""));
airport.setCountry(parts[3].replace("\"", ""));
airport.setIcao(parts[5].replace("\"", ""));
airport.setLat(Double.valueOf(parts[6]));
airport.setLon(Double.valueOf(parts[7]));
this.airports.add(airport);
}
fileScanner.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}}
public double[] calculate(double lat1, double lon1, double lat2, double lon2) {
double[] results = new double[2];
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double rlat1 = Math.toRadians(lat1);
double rlat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2), 2)
+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);
double c = 2 * Math.asin(Math.sqrt(a));
double distance = earthRadius * c;
DecimalFormat df = new DecimalFormat("#0.00");
distance = Double.valueOf(df.format(distance));
results[0] = distance;
double X = Math.cos(rlat2) * Math.sin(dLon);
double Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);
double heading = Math.atan2(X, Y);
heading = Math.toDegrees(heading);
results[1] = heading;
return results;
}
public Airport searchByName(final String name) {
Airport airport = new Airport();
List<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))
.collect(Collectors.toList());
airport = results.get(0);
return airport;
}
public List<Airport> findClosestAirports(double lat, double lon) {
Map<Double, Airport> airportDistances = new HashMap<>();
Map<Double, Airport> airportHeading = new HashMap<>();
List<Airport> closestAirports = new ArrayList<Airport>();
for (Airport ap : this.airports) {
double[] result = calculate(lat, lon, ap.getLat(), ap.getLon());
airportDistances.put(result[0], ap);
airportHeading.put(result[1], ap);
}
ArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());
Collections.sort(distances);
for (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}
Map<String, Double> distanceMap = new HashMap<>();
for (Double d : airportDistances.keySet()) { distanceMap.put(airportDistances.get(d).getAirportName(), d);}
Map<String, Double> headingMap = new HashMap<>();
for (Double d : airportHeading.keySet()) {
double d2 = d;
if(d2<0){d2+=360'}
headingMap.put(airportHeading.get(d).getAirportName(), d2); }
System.out.printf("%-4s %-40s %-25s %-6s %12s %15s\n", "Num", "Airport", "Country", "ICAO", "Distance", "Bearing");
System.out.println("-----------------------------------------------------------------------------------------------------------");
int i = 0;
for (Airport a : closestAirports) {
System.out.printf("%-4s %-40s %-25s %-6s %12.1f %15.0f\n", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));
}
return closestAirports;
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. |
from math import radians, degrees, sin, cos, asin, atan2, sqrt
from pandas import read_csv
EARTH_RADIUS_KM = 6372.8
TASK_CONVERT_NM = 0.0094174
AIRPORT_DATA_FILE = 'airports.dat.txt'
QUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581
def haversine(lat1, lon1, lat2, lon2):
rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]
dlat = rlat2 - rlat1
dlon = rlon2 - rlon1
arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2
clen = 2.0 * degrees(asin(sqrt(arc)))
theta = atan2(sin(dlon) * cos(rlat2),
cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))
theta = (degrees(theta) + 360) % 360
return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta
def find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):
airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[
'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])
airports['Distance'] = 0.0
airports['Bearing'] = 0
for (idx, row) in enumerate(airports.itertuples()):
distance, bearing = haversine(
latitude, longitude, row.Latitude, row.Longitude)
airports.at[idx, 'Distance'] = round(distance, ndigits=1)
airports.at[idx, 'Bearing'] = int(round(bearing))
airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)
return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]
print(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))
|
package distanceAndBearing;
public class Airport {
private String airport;
private String country;
private String icao;
private double lat;
private double lon;
public String getAirportName() { return this.airport; }
public void setAirportName(String airport) { this.airport = airport; }
public String getCountry() { return this.country; }
public void setCountry(String country) { this.country = country; }
public String getIcao() { return this.icao; }
public void setIcao(String icao) { this.icao = icao; }
public double getLat() { return this.lat; }
public void setLat(double lat) { this.lat = lat; }
public double getLon() { return this.lon; }
public void setLon(double lon) { this.lon = lon; }
@Override
public String toString() {return "Airport: " + getAirportName() + ": ICAO: " + getIcao();}
}
package distanceAndBearing;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
public class DistanceAndBearing {
private final double earthRadius = 6371;
private File datFile;
private List<Airport> airports;
public DistanceAndBearing() { this.airports = new ArrayList<Airport>(); }
public boolean readFile(String filename) {
this.datFile = new File(filename);
try {
Scanner fileScanner = new Scanner(datFile);
String line;
while (fileScanner.hasNextLine()) {
line = fileScanner.nextLine();
line = line.replace(", ", "; ");
line = line.replace(",\",\"", "\",\"");
String[] parts = line.split(",");
Airport airport = new Airport();
airport.setAirportName(parts[1].replace("\"", ""));
airport.setCountry(parts[3].replace("\"", ""));
airport.setIcao(parts[5].replace("\"", ""));
airport.setLat(Double.valueOf(parts[6]));
airport.setLon(Double.valueOf(parts[7]));
this.airports.add(airport);
}
fileScanner.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}}
public double[] calculate(double lat1, double lon1, double lat2, double lon2) {
double[] results = new double[2];
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double rlat1 = Math.toRadians(lat1);
double rlat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2), 2)
+ Math.pow(Math.sin(dLon / 2), 2) * Math.cos(rlat1) * Math.cos(rlat2);
double c = 2 * Math.asin(Math.sqrt(a));
double distance = earthRadius * c;
DecimalFormat df = new DecimalFormat("#0.00");
distance = Double.valueOf(df.format(distance));
results[0] = distance;
double X = Math.cos(rlat2) * Math.sin(dLon);
double Y = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon);
double heading = Math.atan2(X, Y);
heading = Math.toDegrees(heading);
results[1] = heading;
return results;
}
public Airport searchByName(final String name) {
Airport airport = new Airport();
List<Airport> results = this.airports.stream().filter(ap -> ap.getAirportName().contains(name))
.collect(Collectors.toList());
airport = results.get(0);
return airport;
}
public List<Airport> findClosestAirports(double lat, double lon) {
Map<Double, Airport> airportDistances = new HashMap<>();
Map<Double, Airport> airportHeading = new HashMap<>();
List<Airport> closestAirports = new ArrayList<Airport>();
for (Airport ap : this.airports) {
double[] result = calculate(lat, lon, ap.getLat(), ap.getLon());
airportDistances.put(result[0], ap);
airportHeading.put(result[1], ap);
}
ArrayList<Double> distances = new ArrayList<>(airportDistances.keySet());
Collections.sort(distances);
for (int i = 0; i < 20; i++) { closestAirports.add(searchByName((airportDistances.get(distances.get(i)).getAirportName())));}
Map<String, Double> distanceMap = new HashMap<>();
for (Double d : airportDistances.keySet()) { distanceMap.put(airportDistances.get(d).getAirportName(), d);}
Map<String, Double> headingMap = new HashMap<>();
for (Double d : airportHeading.keySet()) {
double d2 = d;
if(d2<0){d2+=360'}
headingMap.put(airportHeading.get(d).getAirportName(), d2); }
System.out.printf("%-4s %-40s %-25s %-6s %12s %15s\n", "Num", "Airport", "Country", "ICAO", "Distance", "Bearing");
System.out.println("-----------------------------------------------------------------------------------------------------------");
int i = 0;
for (Airport a : closestAirports) {
System.out.printf("%-4s %-40s %-25s %-6s %12.1f %15.0f\n", ++i, a.getAirportName(), a.getCountry(), a.getIcao(), distanceMap.get(a.getAirportName())*0.5399568, headingMap.get(a.getAirportName()));
}
return closestAirports;
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | from itertools import imap, imap, groupby, chain, imap
from operator import itemgetter
from sys import argv
from array import array
def concat_map(func, it):
return list(chain.from_iterable(imap(func, it)))
def minima(poly):
return (min(pt[0] for pt in poly), min(pt[1] for pt in poly))
def translate_to_origin(poly):
(minx, miny) = minima(poly)
return [(x - minx, y - miny) for (x, y) in poly]
rotate90 = lambda (x, y): ( y, -x)
rotate180 = lambda (x, y): (-x, -y)
rotate270 = lambda (x, y): (-y, x)
reflect = lambda (x, y): (-x, y)
def rotations_and_reflections(poly):
return (poly,
map(rotate90, poly),
map(rotate180, poly),
map(rotate270, poly),
map(reflect, poly),
[reflect(rotate90(pt)) for pt in poly],
[reflect(rotate180(pt)) for pt in poly],
[reflect(rotate270(pt)) for pt in poly])
def canonical(poly):
return min(sorted(translate_to_origin(pl)) for pl in rotations_and_reflections(poly))
def unique(lst):
lst.sort()
return map(next, imap(itemgetter(1), groupby(lst)))
contiguous = lambda (x, y): [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
def new_points(poly):
return unique([pt for pt in concat_map(contiguous, poly) if pt not in poly])
def new_polys(poly):
return unique([canonical(poly + [pt]) for pt in new_points(poly)])
monomino = [(0, 0)]
monominoes = [monomino]
def rank(n):
assert n >= 0
if n == 0: return []
if n == 1: return monominoes
return unique(concat_map(new_polys, rank(n - 1)))
def text_representation(poly):
min_pt = minima(poly)
max_pt = (max(p[0] for p in poly), max(p[1] for p in poly))
table = [array('c', ' ') * (max_pt[1] - min_pt[1] + 1)
for _ in xrange(max_pt[0] - min_pt[0] + 1)]
for pt in poly:
table[pt[0] - min_pt[0]][pt[1] - min_pt[1]] = '
return "\n".join(row.tostring() for row in table)
def main():
print [len(rank(n)) for n in xrange(1, 11)]
n = int(argv[1]) if (len(argv) == 2) else 5
print "\nAll free polyominoes of rank %d:" % n
for poly in rank(n):
print text_representation(poly), "\n"
main()
| import java.awt.Point;
import java.util.*;
import static java.util.Arrays.asList;
import java.util.function.Function;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
public class FreePolyominoesEnum {
static final List<Function<Point, Point>> transforms = new ArrayList<>();
static {
transforms.add(p -> new Point(p.y, -p.x));
transforms.add(p -> new Point(-p.x, -p.y));
transforms.add(p -> new Point(-p.y, p.x));
transforms.add(p -> new Point(-p.x, p.y));
transforms.add(p -> new Point(-p.y, -p.x));
transforms.add(p -> new Point(p.x, -p.y));
transforms.add(p -> new Point(p.y, p.x));
}
static Point findMinima(List<Point> poly) {
return new Point(
poly.stream().mapToInt(a -> a.x).min().getAsInt(),
poly.stream().mapToInt(a -> a.y).min().getAsInt());
}
static List<Point> translateToOrigin(List<Point> poly) {
final Point min = findMinima(poly);
poly.replaceAll(p -> new Point(p.x - min.x, p.y - min.y));
return poly;
}
static List<List<Point>> rotationsAndReflections(List<Point> poly) {
List<List<Point>> lst = new ArrayList<>();
lst.add(poly);
for (Function<Point, Point> t : transforms)
lst.add(poly.stream().map(t).collect(toList()));
return lst;
}
static Comparator<Point> byCoords = Comparator.<Point>comparingInt(p -> p.x)
.thenComparingInt(p -> p.y);
static List<Point> normalize(List<Point> poly) {
return rotationsAndReflections(poly).stream()
.map(lst -> translateToOrigin(lst))
.map(lst -> lst.stream().sorted(byCoords).collect(toList()))
.min(comparing(Object::toString))
.get();
}
static List<Point> neighborhoods(Point p) {
return asList(new Point(p.x - 1, p.y), new Point(p.x + 1, p.y),
new Point(p.x, p.y - 1), new Point(p.x, p.y + 1));
}
static List<Point> concat(List<Point> lst, Point pt) {
List<Point> r = new ArrayList<>();
r.addAll(lst);
r.add(pt);
return r;
}
static List<Point> newPoints(List<Point> poly) {
return poly.stream()
.flatMap(p -> neighborhoods(p).stream())
.filter(p -> !poly.contains(p))
.distinct()
.collect(toList());
}
static List<List<Point>> constructNextRank(List<Point> poly) {
return newPoints(poly).stream()
.map(p -> normalize(concat(poly, p)))
.distinct()
.collect(toList());
}
static List<List<Point>> rank(int n) {
if (n < 0)
throw new IllegalArgumentException("n cannot be negative");
if (n < 2) {
List<List<Point>> r = new ArrayList<>();
if (n == 1)
r.add(asList(new Point(0, 0)));
return r;
}
return rank(n - 1).stream()
.parallel()
.flatMap(lst -> constructNextRank(lst).stream())
.distinct()
.collect(toList());
}
public static void main(String[] args) {
for (List<Point> poly : rank(5)) {
for (Point p : poly)
System.out.printf("(%d,%d) ", p.x, p.y);
System.out.println();
}
}
}
|
Write the same algorithm in Java as shown in this Python implementation. |
import requests
import json
city = None
topic = None
def getEvent(url_path, key) :
responseString = ""
params = {'city':city, 'key':key,'topic':topic}
r = requests.get(url_path, params = params)
print(r.url)
responseString = r.text
return responseString
def getApiKey(key_path):
key = ""
f = open(key_path, 'r')
key = f.read()
return key
def submitEvent(url_path,params):
r = requests.post(url_path, data=json.dumps(params))
print(r.text+" : Event Submitted")
| package src;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URI;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class EventGetter {
String city = "";
String topic = "";
public String getEvent(String path_code,String key) throws Exception{
String responseString = "";
URI request = new URIBuilder()
.setScheme("http")
.setHost("api.meetup.com")
.setPath(path_code)
.setParameter("topic", topic)
.setParameter("city", city)
.setParameter("key", key)
.build();
HttpGet get = new HttpGet(request);
System.out.println("Get request : "+get.toString());
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(get);
responseString = EntityUtils.toString(response.getEntity());
return responseString;
}
public String getApiKey(String key_path){
String key = "";
try{
BufferedReader reader = new BufferedReader(new FileReader(key_path));
key = reader.readLine().toString();
reader.close();
}
catch(Exception e){System.out.println(e.toString());}
return key;
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | from itertools import product
constraintinfo = (
(lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')),
(lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')),
(lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')),
(lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')),
(lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')),
(lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')),
(lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')),
(lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')),
(lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')),
(lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')),
(lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')),
(lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')),
)
def printer(st, matches):
if False in matches:
print('Missed by one statement: %i, %s' % docs[matches.index(False)])
else:
print('Full match:')
print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1)))
funcs, docs = zip(*constraintinfo)
full, partial = [], []
for st in product( *([(False, True)] * 12) ):
truths = [bool(func(st)) for func in funcs]
matches = [s == t for s,t in zip(st, truths)]
mcount = sum(matches)
if mcount == 12:
full.append((st, matches))
elif mcount == 11:
partial.append((st, matches))
for stm in full + partial:
printer(*stm)
| public class LogicPuzzle
{
boolean S[] = new boolean[13];
int Count = 0;
public boolean check2 ()
{
int count = 0;
for (int k = 7; k <= 12; k++)
if (S[k]) count++;
return S[2] == (count == 3);
}
public boolean check3 ()
{
int count = 0;
for (int k = 2; k <= 12; k += 2)
if (S[k]) count++;
return S[3] == (count == 2);
}
public boolean check4 ()
{
return S[4] == ( !S[5] || S[6] && S[7]);
}
public boolean check5 ()
{
return S[5] == ( !S[2] && !S[3] && !S[4]);
}
public boolean check6 ()
{
int count = 0;
for (int k = 1; k <= 11; k += 2)
if (S[k]) count++;
return S[6] == (count == 4);
}
public boolean check7 ()
{
return S[7] == ((S[2] || S[3]) && !(S[2] && S[3]));
}
public boolean check8 ()
{
return S[8] == ( !S[7] || S[5] && S[6]);
}
public boolean check9 ()
{
int count = 0;
for (int k = 1; k <= 6; k++)
if (S[k]) count++;
return S[9] == (count == 3);
}
public boolean check10 ()
{
return S[10] == (S[11] && S[12]);
}
public boolean check11 ()
{
int count = 0;
for (int k = 7; k <= 9; k++)
if (S[k]) count++;
return S[11] == (count == 1);
}
public boolean check12 ()
{
int count = 0;
for (int k = 1; k <= 11; k++)
if (S[k]) count++;
return S[12] == (count == 4);
}
public void check ()
{
if (check2() && check3() && check4() && check5() && check6()
&& check7() && check8() && check9() && check10() && check11()
&& check12())
{
for (int k = 1; k <= 12; k++)
if (S[k]) System.out.print(k + " ");
System.out.println();
Count++;
}
}
public void recurseAll (int k)
{
if (k == 13)
check();
else
{
S[k] = false;
recurseAll(k + 1);
S[k] = true;
recurseAll(k + 1);
}
}
public static void main (String args[])
{
LogicPuzzle P = new LogicPuzzle();
P.S[1] = true;
P.recurseAll(2);
System.out.println();
System.out.println(P.Count + " Solutions found.");
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | import math
dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
-0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,
-0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201,
0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,
0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,
0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,
-0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799,
0.087]
dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,
-0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188,
-0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,
0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038,
-0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445,
-0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044,
0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901,
0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]
def funnel(dxs, rule):
x, rxs = 0, []
for dx in dxs:
rxs.append(x + dx)
x = rule(x, dx)
return rxs
def mean(xs): return sum(xs) / len(xs)
def stddev(xs):
m = mean(xs)
return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))
def experiment(label, rule):
rxs, rys = funnel(dxs, rule), funnel(dys, rule)
print label
print 'Mean x, y : %.4f, %.4f' % (mean(rxs), mean(rys))
print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))
print
experiment('Rule 1:', lambda z, dz: 0)
experiment('Rule 2:', lambda z, dz: -dz)
experiment('Rule 3:', lambda z, dz: -(z+dz))
experiment('Rule 4:', lambda z, dz: z+dz)
| import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] dxs = {
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import math
dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
-0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,
-0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201,
0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,
0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,
0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,
-0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799,
0.087]
dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,
-0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188,
-0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,
0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038,
-0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445,
-0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044,
0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901,
0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]
def funnel(dxs, rule):
x, rxs = 0, []
for dx in dxs:
rxs.append(x + dx)
x = rule(x, dx)
return rxs
def mean(xs): return sum(xs) / len(xs)
def stddev(xs):
m = mean(xs)
return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))
def experiment(label, rule):
rxs, rys = funnel(dxs, rule), funnel(dys, rule)
print label
print 'Mean x, y : %.4f, %.4f' % (mean(rxs), mean(rys))
print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))
print
experiment('Rule 1:', lambda z, dz: 0)
experiment('Rule 2:', lambda z, dz: -dz)
experiment('Rule 3:', lambda z, dz: -(z+dz))
experiment('Rule 4:', lambda z, dz: z+dz)
| import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] dxs = {
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087};
double[] dys = {
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032};
experiment("Rule 1:", dxs, dys, (z, dz) -> 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) -> -dz);
experiment("Rule 3:", dxs, dys, (z, dz) -> -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) -> z + dz);
}
static void experiment(String label, double[] dxs, double[] dys,
BiFunction<Double, Double, Double> rule) {
double[] resx = funnel(dxs, rule);
double[] resy = funnel(dys, rule);
System.out.println(label);
System.out.printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy));
System.out.printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy));
System.out.println();
}
static double[] funnel(double[] input, BiFunction<Double, Double, Double> rule) {
double x = 0;
double[] result = new double[input.length];
for (int i = 0; i < input.length; i++) {
double rx = x + input[i];
x = rule.apply(x, input[i]);
result[i] = rx;
}
return result;
}
static double mean(double[] xs) {
return Arrays.stream(xs).sum() / xs.length;
}
static double stdDev(double[] xs) {
double m = mean(xs);
return sqrt(Arrays.stream(xs).map(x -> pow((x - m), 2)).sum() / xs.length);
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. |
from re import sub
testtexts = [
,
,
]
for txt in testtexts:
text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt)
text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2)
text2 = sub(r'</lang\s*>', r'
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class FixCodeTags
{
public static void main(String[] args)
{
String sourcefile=args[0];
String convertedfile=args[1];
convert(sourcefile,convertedfile);
}
static String[] languages = {"abap", "actionscript", "actionscript3",
"ada", "apache", "applescript", "apt_sources", "asm", "asp",
"autoit", "avisynth", "bar", "bash", "basic4gl", "bf",
"blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg",
"cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css",
"d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email",
"foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml",
"gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict",
"idl", "ini", "inno", "intercal", "io", "java", "java5",
"javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
"lolcode", "lotusformulas", "lotusscript", "lscript", "lua",
"m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml",
"mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas",
"oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief",
"pic16", "pixelbender", "plsql", "povray", "powershell",
"progress", "prolog", "providex", "python", "qbasic", "rails",
"reg", "robots", "ruby", "sas", "scala", "scheme", "scilab",
"sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet",
"verilog", "vhdl", "vim", "visualfoxpro", "visualprolog",
"whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"};
static void convert(String sourcefile,String convertedfile)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(sourcefile));
StringBuffer sb=new StringBuffer("");
String line;
while((line=br.readLine())!=null)
{
for(int i=0;i<languages.length;i++)
{
String lang=languages[i];
line=line.replaceAll("<"+lang+">", "<lang "+lang+">");
line=line.replaceAll("</"+lang+">", "</"+"lang>");
line=line.replaceAll("<code "+lang+">", "<lang "+lang+">");
line=line.replaceAll("</code>", "</"+"lang>");
}
sb.append(line);
}
br.close();
FileWriter fw=new FileWriter(new File(convertedfile));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Write the same code in Java as shown below in Python. |
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
| import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. |
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
| import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. |
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ + ':\n')(repr)(showList)(
replicateM(2)
)([[1, 2, 3], 'abc'])
)
def liftA2List(f):
return lambda xs: lambda ys: [
f(*xy) for xy in product(xs, ys)
]
def fTable(s):
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
def showList(xs):
return '[' + ','.join(
showList(x) if isinstance(x, list) else repr(x) for x in xs
) + ']'
if __name__ == '__main__':
main()
| import java.util.function.Predicate;
public class PermutationsWithRepetitions {
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd'};
permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
}
static void permute(char[] a, int k, Predicate<int[]> decider) {
int n = a.length;
if (k < 1 || k > n)
throw new IllegalArgumentException("Illegal number of positions.");
int[] indexes = new int[n];
int total = (int) Math.pow(n, k);
while (total-- > 0) {
for (int i = 0; i < n - (n - k); i++)
System.out.print(a[indexes[i]]);
System.out.println();
if (decider.test(indexes))
break;
for (int i = 0; i < n; i++) {
if (indexes[i] >= n - 1) {
indexes[i] = 0;
} else {
indexes[i]++;
break;
}
}
}
}
}
|
Change the following Python code into Java without altering its purpose. |
import argparse
import itertools
import pathlib
import re
import secrets
import sys
MAGIC = "
def make_keys(n, size):
return (secrets.token_hex(size) for _ in range(n))
def make_pad(name, pad_size, key_size):
pad = [
MAGIC,
f"
f"
*make_keys(pad_size, key_size),
]
return "\n".join(pad)
def xor(message, key):
return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))
def use_key(pad):
match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE)
if not match:
error("pad is all used up")
key = match.group()
pos = match.start()
return (f"{pad[:pos]}-{pad[pos:]}", key)
def log(msg):
sys.stderr.write(msg)
sys.stderr.write("\n")
def error(msg):
sys.stderr.write(msg)
sys.stderr.write("\n")
sys.exit(1)
def write_pad(path, pad_size, key_size):
if path.exists():
error(f"pad '{path}' already exists")
with path.open("w") as fd:
fd.write(make_pad(path.name, pad_size, key_size))
log(f"New one-time pad written to {path}")
def main(pad, message, outfile):
if not pad.exists():
error(f"no such pad '{pad}'")
with pad.open("r") as fd:
if fd.readline().strip() != MAGIC:
error(f"file '{pad}' does not look like a one-time pad")
with pad.open("r+") as fd:
updated, key = use_key(fd.read())
fd.seek(0)
fd.write(updated)
outfile.write(xor(message, bytes.fromhex(key)))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="One-time pad.")
parser.add_argument(
"pad",
help=(
"Path to one-time pad. If neither --encrypt or --decrypt "
"are given, will create a new pad."
),
)
parser.add_argument(
"--length",
type=int,
default=10,
help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.",
)
parser.add_argument(
"--key-size",
type=int,
default=64,
help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.",
)
parser.add_argument(
"-o",
"--outfile",
type=argparse.FileType("wb"),
default=sys.stdout.buffer,
help=(
"Write encoded/decoded message to a file. Ignored if --encrypt or "
"--decrypt is not given. Defaults to stdout."
),
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--encrypt",
metavar="FILE",
type=argparse.FileType("rb"),
help="Encrypt FILE using the next available key from pad.",
)
group.add_argument(
"--decrypt",
metavar="FILE",
type=argparse.FileType("rb"),
help="Decrypt FILE using the next available key from pad.",
)
args = parser.parse_args()
if args.encrypt:
message = args.encrypt.read()
elif args.decrypt:
message = args.decrypt.read()
else:
message = None
if isinstance(message, str):
message = message.encode()
pad = pathlib.Path(args.pad).with_suffix(".1tp")
if message:
main(pad, message, args.outfile)
else:
write_pad(pad, args.length, args.key_size)
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OneTimePad {
public static void main(String[] args) {
String controlName = "AtomicBlonde";
generatePad(controlName, 5, 60, 65, 90);
String text = "IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES";
String encrypted = parse(true, controlName, text.replaceAll(" ", ""));
String decrypted = parse(false, controlName, encrypted);
System.out.println("Input text = " + text);
System.out.println("Encrypted text = " + encrypted);
System.out.println("Decrypted text = " + decrypted);
controlName = "AtomicBlondeCaseSensitive";
generatePad(controlName, 5, 60, 32, 126);
text = "It was the best of times, it was the worst of times.";
encrypted = parse(true, controlName, text);
decrypted = parse(false, controlName, encrypted);
System.out.println();
System.out.println("Input text = " + text);
System.out.println("Encrypted text = " + encrypted);
System.out.println("Decrypted text = " + decrypted);
}
private static String parse(boolean encryptText, String controlName, String text) {
StringBuilder sb = new StringBuilder();
int minCh = 0;
int maxCh = 0;
Pattern minChPattern = Pattern.compile("^# MIN_CH = ([\\d]+)$");
Pattern maxChPattern = Pattern.compile("^# MAX_CH = ([\\d]+)$");
boolean validated = false;
try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {
String inLine = null;
while ( (inLine = in.readLine()) != null ) {
Matcher minMatcher = minChPattern.matcher(inLine);
if ( minMatcher.matches() ) {
minCh = Integer.parseInt(minMatcher.group(1));
continue;
}
Matcher maxMatcher = maxChPattern.matcher(inLine);
if ( maxMatcher.matches() ) {
maxCh = Integer.parseInt(maxMatcher.group(1));
continue;
}
if ( ! validated && minCh > 0 && maxCh > 0 ) {
validateText(text, minCh, maxCh);
validated = true;
}
if ( inLine.startsWith("#") || inLine.startsWith("-") ) {
continue;
}
String key = inLine;
if ( encryptText ) {
for ( int i = 0 ; i < text.length(); i++) {
sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));
}
}
else {
for ( int i = 0 ; i < text.length(); i++) {
int decrypt = text.charAt(i) - key.charAt(i);
if ( decrypt < 0 ) {
decrypt += maxCh - minCh + 1;
}
decrypt += minCh;
sb.append((char) decrypt);
}
}
break;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
private static void validateText(String text, int minCh, int maxCh) {
for ( char ch : text.toCharArray() ) {
if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {
throw new IllegalArgumentException("ERROR 103: Invalid text.");
}
}
}
private static String getFileName(String controlName) {
return controlName + ".1tp";
}
private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {
Random random = new Random();
try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {
writer.write("# Lines starting with '#' are ignored.");
writer.newLine();
writer.write("# Lines starting with '-' are previously used.");
writer.newLine();
writer.write("# MIN_CH = " + minCh);
writer.newLine();
writer.write("# MAX_CH = " + maxCh);
writer.newLine();
for ( int line = 0 ; line < keys ; line++ ) {
StringBuilder sb = new StringBuilder();
for ( int ch = 0 ; ch < keyLength ; ch++ ) {
sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));
}
writer.write(sb.toString());
writer.newLine();
}
writer.write("# EOF");
writer.newLine();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. |
import argparse
import itertools
import pathlib
import re
import secrets
import sys
MAGIC = "
def make_keys(n, size):
return (secrets.token_hex(size) for _ in range(n))
def make_pad(name, pad_size, key_size):
pad = [
MAGIC,
f"
f"
*make_keys(pad_size, key_size),
]
return "\n".join(pad)
def xor(message, key):
return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))
def use_key(pad):
match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE)
if not match:
error("pad is all used up")
key = match.group()
pos = match.start()
return (f"{pad[:pos]}-{pad[pos:]}", key)
def log(msg):
sys.stderr.write(msg)
sys.stderr.write("\n")
def error(msg):
sys.stderr.write(msg)
sys.stderr.write("\n")
sys.exit(1)
def write_pad(path, pad_size, key_size):
if path.exists():
error(f"pad '{path}' already exists")
with path.open("w") as fd:
fd.write(make_pad(path.name, pad_size, key_size))
log(f"New one-time pad written to {path}")
def main(pad, message, outfile):
if not pad.exists():
error(f"no such pad '{pad}'")
with pad.open("r") as fd:
if fd.readline().strip() != MAGIC:
error(f"file '{pad}' does not look like a one-time pad")
with pad.open("r+") as fd:
updated, key = use_key(fd.read())
fd.seek(0)
fd.write(updated)
outfile.write(xor(message, bytes.fromhex(key)))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="One-time pad.")
parser.add_argument(
"pad",
help=(
"Path to one-time pad. If neither --encrypt or --decrypt "
"are given, will create a new pad."
),
)
parser.add_argument(
"--length",
type=int,
default=10,
help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.",
)
parser.add_argument(
"--key-size",
type=int,
default=64,
help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.",
)
parser.add_argument(
"-o",
"--outfile",
type=argparse.FileType("wb"),
default=sys.stdout.buffer,
help=(
"Write encoded/decoded message to a file. Ignored if --encrypt or "
"--decrypt is not given. Defaults to stdout."
),
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--encrypt",
metavar="FILE",
type=argparse.FileType("rb"),
help="Encrypt FILE using the next available key from pad.",
)
group.add_argument(
"--decrypt",
metavar="FILE",
type=argparse.FileType("rb"),
help="Decrypt FILE using the next available key from pad.",
)
args = parser.parse_args()
if args.encrypt:
message = args.encrypt.read()
elif args.decrypt:
message = args.decrypt.read()
else:
message = None
if isinstance(message, str):
message = message.encode()
pad = pathlib.Path(args.pad).with_suffix(".1tp")
if message:
main(pad, message, args.outfile)
else:
write_pad(pad, args.length, args.key_size)
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OneTimePad {
public static void main(String[] args) {
String controlName = "AtomicBlonde";
generatePad(controlName, 5, 60, 65, 90);
String text = "IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES";
String encrypted = parse(true, controlName, text.replaceAll(" ", ""));
String decrypted = parse(false, controlName, encrypted);
System.out.println("Input text = " + text);
System.out.println("Encrypted text = " + encrypted);
System.out.println("Decrypted text = " + decrypted);
controlName = "AtomicBlondeCaseSensitive";
generatePad(controlName, 5, 60, 32, 126);
text = "It was the best of times, it was the worst of times.";
encrypted = parse(true, controlName, text);
decrypted = parse(false, controlName, encrypted);
System.out.println();
System.out.println("Input text = " + text);
System.out.println("Encrypted text = " + encrypted);
System.out.println("Decrypted text = " + decrypted);
}
private static String parse(boolean encryptText, String controlName, String text) {
StringBuilder sb = new StringBuilder();
int minCh = 0;
int maxCh = 0;
Pattern minChPattern = Pattern.compile("^# MIN_CH = ([\\d]+)$");
Pattern maxChPattern = Pattern.compile("^# MAX_CH = ([\\d]+)$");
boolean validated = false;
try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {
String inLine = null;
while ( (inLine = in.readLine()) != null ) {
Matcher minMatcher = minChPattern.matcher(inLine);
if ( minMatcher.matches() ) {
minCh = Integer.parseInt(minMatcher.group(1));
continue;
}
Matcher maxMatcher = maxChPattern.matcher(inLine);
if ( maxMatcher.matches() ) {
maxCh = Integer.parseInt(maxMatcher.group(1));
continue;
}
if ( ! validated && minCh > 0 && maxCh > 0 ) {
validateText(text, minCh, maxCh);
validated = true;
}
if ( inLine.startsWith("#") || inLine.startsWith("-") ) {
continue;
}
String key = inLine;
if ( encryptText ) {
for ( int i = 0 ; i < text.length(); i++) {
sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));
}
}
else {
for ( int i = 0 ; i < text.length(); i++) {
int decrypt = text.charAt(i) - key.charAt(i);
if ( decrypt < 0 ) {
decrypt += maxCh - minCh + 1;
}
decrypt += minCh;
sb.append((char) decrypt);
}
}
break;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
private static void validateText(String text, int minCh, int maxCh) {
for ( char ch : text.toCharArray() ) {
if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {
throw new IllegalArgumentException("ERROR 103: Invalid text.");
}
}
}
private static String getFileName(String controlName) {
return controlName + ".1tp";
}
private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {
Random random = new Random();
try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {
writer.write("# Lines starting with '#' are ignored.");
writer.newLine();
writer.write("# Lines starting with '-' are previously used.");
writer.newLine();
writer.write("# MIN_CH = " + minCh);
writer.newLine();
writer.write("# MAX_CH = " + maxCh);
writer.newLine();
for ( int line = 0 ; line < keys ; line++ ) {
StringBuilder sb = new StringBuilder();
for ( int ch = 0 ; ch < keyLength ; ch++ ) {
sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));
}
writer.write(sb.toString());
writer.newLine();
}
writer.write("# EOF");
writer.newLine();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
Port the following code from Java to PHP with equivalent syntax and logic. | String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little);
System.out.println(replaced);
System.out.printf("Mary had a %s lamb.", little);
String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);
| <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
|
Generate an equivalent PHP version of this Java code. | import java.util.*;
public class PatienceSort {
public static <E extends Comparable<? super E>> void sort (E[] n) {
List<Pile<E>> piles = new ArrayList<Pile<E>>();
for (E x : n) {
Pile<E> newPile = new Pile<E>();
newPile.push(x);
int i = Collections.binarySearch(piles, newPile);
if (i < 0) i = ~i;
if (i != piles.size())
piles.get(i).push(x);
else
piles.add(newPile);
}
PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);
for (int c = 0; c < n.length; c++) {
Pile<E> smallPile = heap.poll();
n[c] = smallPile.pop();
if (!smallPile.isEmpty())
heap.offer(smallPile);
}
assert(heap.isEmpty());
}
private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {
public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }
}
public static void main(String[] args) {
Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};
sort(a);
System.out.println(Arrays.toString(a));
}
}
| <?php
class PilesHeap extends SplMinHeap {
public function compare($pile1, $pile2) {
return parent::compare($pile1->top(), $pile2->top());
}
}
function patience_sort(&$n) {
$piles = array();
foreach ($n as $x) {
$low = 0; $high = count($piles)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($piles[$mid]->top() >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
if ($i == count($piles))
$piles[] = new SplStack();
$piles[$i]->push($x);
}
$heap = new PilesHeap();
foreach ($piles as $pile)
$heap->insert($pile);
for ($c = 0; $c < count($n); $c++) {
$smallPile = $heap->extract();
$n[$c] = $smallPile->pop();
if (!$smallPile->isEmpty())
$heap->insert($smallPile);
}
assert($heap->isEmpty());
}
$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
|
Write the same code in PHP as shown below in Java. | import java.util.*;
public class PatienceSort {
public static <E extends Comparable<? super E>> void sort (E[] n) {
List<Pile<E>> piles = new ArrayList<Pile<E>>();
for (E x : n) {
Pile<E> newPile = new Pile<E>();
newPile.push(x);
int i = Collections.binarySearch(piles, newPile);
if (i < 0) i = ~i;
if (i != piles.size())
piles.get(i).push(x);
else
piles.add(newPile);
}
PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);
for (int c = 0; c < n.length; c++) {
Pile<E> smallPile = heap.poll();
n[c] = smallPile.pop();
if (!smallPile.isEmpty())
heap.offer(smallPile);
}
assert(heap.isEmpty());
}
private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {
public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }
}
public static void main(String[] args) {
Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};
sort(a);
System.out.println(Arrays.toString(a));
}
}
| <?php
class PilesHeap extends SplMinHeap {
public function compare($pile1, $pile2) {
return parent::compare($pile1->top(), $pile2->top());
}
}
function patience_sort(&$n) {
$piles = array();
foreach ($n as $x) {
$low = 0; $high = count($piles)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($piles[$mid]->top() >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
if ($i == count($piles))
$piles[] = new SplStack();
$piles[$i]->push($x);
}
$heap = new PilesHeap();
foreach ($piles as $pile)
$heap->insert($pile);
for ($c = 0; $c < count($n); $c++) {
$smallPile = $heap->extract();
$n[$c] = $smallPile->pop();
if (!$smallPile->isEmpty())
$heap->insert($smallPile);
}
assert($heap->isEmpty());
}
$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
|
Preserve the algorithm and functionality while converting the code from Java to PHP. | import static java.lang.Math.*;
public class RayCasting {
static boolean intersects(int[] A, int[] B, double[] P) {
if (A[1] > B[1])
return intersects(B, A, P);
if (P[1] == A[1] || P[1] == B[1])
P[1] += 0.0001;
if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))
return false;
if (P[0] < min(A[0], B[0]))
return true;
double red = (P[1] - A[1]) / (double) (P[0] - A[0]);
double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);
return red >= blue;
}
static boolean contains(int[][] shape, double[] pnt) {
boolean inside = false;
int len = shape.length;
for (int i = 0; i < len; i++) {
if (intersects(shape[i], shape[(i + 1) % len], pnt))
inside = !inside;
}
return inside;
}
public static void main(String[] a) {
double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},
{20, 10}, {16, 10}, {20, 20}};
for (int[][] shape : shapes) {
for (double[] pnt : testPoints)
System.out.printf("%7s ", contains(shape, pnt));
System.out.println();
}
}
final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};
final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},
{5, 5}, {15, 5}, {15, 15}, {5, 15}};
final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},
{20, 20}, {20, 0}};
final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},
{6, 20}, {0, 10}};
final static int[][][] shapes = {square, squareHole, strange, hexagon};
}
| <?php
function contains($bounds, $lat, $lng)
{
$count = 0;
$bounds_count = count($bounds);
for ($b = 0; $b < $bounds_count; $b++) {
$vertex1 = $bounds[$b];
$vertex2 = $bounds[($b + 1) % $bounds_count];
if (west($vertex1, $vertex2, $lng, $lat))
$count++;
}
return $count % 2;
}
function west($A, $B, $x, $y)
{
if ($A['y'] <= $B['y']) {
if ($y <= $A['y'] || $y > $B['y'] ||
$x >= $A['x'] && $x >= $B['x']) {
return false;
}
if ($x < $A['x'] && $x < $B['x']) {
return true;
}
if ($x == $A['x']) {
if ($y == $A['y']) {
$result1 = NAN;
} else {
$result1 = INF;
}
} else {
$result1 = ($y - $A['y']) / ($x - $A['x']);
}
if ($B['x'] == $A['x']) {
if ($B['y'] == $A['y']) {
$result2 = NAN;
} else {
$result2 = INF;
}
} else {
$result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);
}
return $result1 > $result2;
}
return west($B, $A, $x, $y);
}
$square = [
'name' => 'square',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]
];
$squareHole = [
'name' => 'squareHole',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]
];
$strange = [
'name' => 'strange',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]
];
$hexagon = [
'name' => 'hexagon',
'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]
];
$shapes = [$square, $squareHole, $strange, $hexagon];
$testPoints = [
['lng' => 10, 'lat' => 10],
['lng' => 10, 'lat' => 16],
['lng' => -20, 'lat' => 10],
['lng' => 0, 'lat' => 10],
['lng' => 20, 'lat' => 10],
['lng' => 16, 'lat' => 10],
['lng' => 20, 'lat' => 20]
];
for ($s = 0; $s < count($shapes); $s++) {
$shape = $shapes[$s];
for ($tp = 0; $tp < count($testPoints); $tp++) {
$testPoint = $testPoints[$tp];
echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;
}
}
|
Convert this Java snippet to PHP and keep its semantics consistent. | import static java.lang.Math.*;
public class RayCasting {
static boolean intersects(int[] A, int[] B, double[] P) {
if (A[1] > B[1])
return intersects(B, A, P);
if (P[1] == A[1] || P[1] == B[1])
P[1] += 0.0001;
if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0]))
return false;
if (P[0] < min(A[0], B[0]))
return true;
double red = (P[1] - A[1]) / (double) (P[0] - A[0]);
double blue = (B[1] - A[1]) / (double) (B[0] - A[0]);
return red >= blue;
}
static boolean contains(int[][] shape, double[] pnt) {
boolean inside = false;
int len = shape.length;
for (int i = 0; i < len; i++) {
if (intersects(shape[i], shape[(i + 1) % len], pnt))
inside = !inside;
}
return inside;
}
public static void main(String[] a) {
double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10},
{20, 10}, {16, 10}, {20, 20}};
for (int[][] shape : shapes) {
for (double[] pnt : testPoints)
System.out.printf("%7s ", contains(shape, pnt));
System.out.println();
}
}
final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}};
final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20},
{5, 5}, {15, 5}, {15, 15}, {5, 15}};
final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15},
{20, 20}, {20, 0}};
final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20},
{6, 20}, {0, 10}};
final static int[][][] shapes = {square, squareHole, strange, hexagon};
}
| <?php
function contains($bounds, $lat, $lng)
{
$count = 0;
$bounds_count = count($bounds);
for ($b = 0; $b < $bounds_count; $b++) {
$vertex1 = $bounds[$b];
$vertex2 = $bounds[($b + 1) % $bounds_count];
if (west($vertex1, $vertex2, $lng, $lat))
$count++;
}
return $count % 2;
}
function west($A, $B, $x, $y)
{
if ($A['y'] <= $B['y']) {
if ($y <= $A['y'] || $y > $B['y'] ||
$x >= $A['x'] && $x >= $B['x']) {
return false;
}
if ($x < $A['x'] && $x < $B['x']) {
return true;
}
if ($x == $A['x']) {
if ($y == $A['y']) {
$result1 = NAN;
} else {
$result1 = INF;
}
} else {
$result1 = ($y - $A['y']) / ($x - $A['x']);
}
if ($B['x'] == $A['x']) {
if ($B['y'] == $A['y']) {
$result2 = NAN;
} else {
$result2 = INF;
}
} else {
$result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);
}
return $result1 > $result2;
}
return west($B, $A, $x, $y);
}
$square = [
'name' => 'square',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]
];
$squareHole = [
'name' => 'squareHole',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]
];
$strange = [
'name' => 'strange',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]
];
$hexagon = [
'name' => 'hexagon',
'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]
];
$shapes = [$square, $squareHole, $strange, $hexagon];
$testPoints = [
['lng' => 10, 'lat' => 10],
['lng' => 10, 'lat' => 16],
['lng' => -20, 'lat' => 10],
['lng' => 0, 'lat' => 10],
['lng' => 20, 'lat' => 10],
['lng' => 16, 'lat' => 10],
['lng' => 20, 'lat' => 20]
];
for ($s = 0; $s < count($shapes); $s++) {
$shape = $shapes[$s];
for ($tp = 0; $tp < count($testPoints); $tp++) {
$testPoint = $testPoints[$tp];
echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;
}
}
|
Rewrite this program in PHP while keeping its functionality equivalent to the Java version. | public class CountSubstring {
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
public static void main(String[] args){
System.out.println(countSubstring("th", "the three truths"));
System.out.println(countSubstring("abab", "ababababab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}
| <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
|
Ensure the translated PHP code behaves exactly like the original Java snippet. | public class CountSubstring {
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
public static void main(String[] args){
System.out.println(countSubstring("th", "the three truths"));
System.out.println(countSubstring("abab", "ababababab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}
| <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
|
Write the same code in PHP as shown below in Java. | import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.close();
}
}
}
| #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
|
Please provide an equivalent version of this Java code in PHP. | import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.close();
}
}
}
| #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
|
Can you help me rewrite this code in PHP instead of Java, keeping it the same logically? | public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/");
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j];
boolean allMatched = true;
for(int i = 1; i < folders.length && allMatched; i++){
if(folders[i].length < j){
allMatched = false;
break;
}
allMatched &= folders[i][j].equals(thisFolder);
}
if(allMatched){
commonPath += thisFolder + "/";
}else{
break;
}
}
return commonPath;
}
public static void main(String[] args){
String[] paths = { "/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths));
String[] paths2 = { "/hame/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths2));
}
}
| <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
|
Produce a functionally identical PHP code for the snippet given in Java. | public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/");
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j];
boolean allMatched = true;
for(int i = 1; i < folders.length && allMatched; i++){
if(folders[i].length < j){
allMatched = false;
break;
}
allMatched &= folders[i][j].equals(thisFolder);
}
if(allMatched){
commonPath += thisFolder + "/";
}else{
break;
}
}
return commonPath;
}
public static void main(String[] args){
String[] paths = { "/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths));
String[] paths2 = { "/hame/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths2));
}
}
| <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
|
Change the following Java code into PHP without altering its purpose. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
| <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
Maintain the same structure and functionality when rewriting this code in PHP. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
| <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
Convert this Java snippet to PHP and keep its semantics consistent. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
| <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
Translate this program into PHP but keep the logic exactly as in Java. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
| <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
Transform the following Java implementation into PHP, maintaining the same output and logic. | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToe now=new TicTacToe();
now.startMatch();
}
private int[][] marks;
private int[][] wins;
private int[] weights;
private char[][] grid;
private final int knotcount=3;
private final int crosscount=4;
private final int totalcount=5;
private final int playerid=0;
private final int compid=1;
private final int truceid=2;
private final int playingid=3;
private String movesPlayer;
private byte override;
private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
private Hashtable<Integer,Integer> crossbank;
private Hashtable<Integer,Integer> knotbank;
public void startMatch()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Start?(y/n):");
char choice='y';
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(choice=='n'||choice=='N')
{
return;
}
System.out.println("Use a standard numpad as an entry grid, as so:\n ");
display(numpad);
System.out.println("Begin");
int playerscore=0;
int compscore=0;
do
{
int result=startGame();
if(result==playerid)
playerscore++;
else if(result==compid)
compscore++;
System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
System.out.print("Another?(y/n):");
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}while(choice!='n'||choice=='N');
System.out.println("Game over.");
}
private void put(int cell,int player)
{
int i=-1,j=-1;;
switch(cell)
{
case 1:i=2;j=0;break;
case 2:i=2;j=1;break;
case 3:i=2;j=2;break;
case 4:i=1;j=0;break;
case 5:i=1;j=1;break;
case 6:i=1;j=2;break;
case 7:i=0;j=0;break;
case 8:i=0;j=1;break;
case 9:i=0;j=2;break;
default:display(overridegrid);return;
}
char mark='x';
if(player==0)
mark='o';
grid[i][j]=mark;
display(grid);
}
private int startGame()
{
init();
display(grid);
int status=playingid;
while(status==playingid)
{
put(playerMove(),0);
if(override==1)
{
System.out.println("O wins.");
return playerid;
}
status=checkForWin();
if(status!=playingid)
break;
try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
put(compMove(),1);
status=checkForWin();
}
return status;
}
private void init()
{
movesPlayer="";
override=0;
marks=new int[8][6];
wins=new int[][]
{
{7,8,9},
{4,5,6},
{1,2,3},
{7,4,1},
{8,5,2},
{9,6,3},
{7,5,3},
{9,5,1}
};
weights=new int[]{3,2,3,2,4,2,3,2,3};
grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
crossbank=new Hashtable<Integer,Integer>();
knotbank=new Hashtable<Integer,Integer>();
}
private void mark(int m,int player)
{
for(int i=0;i<wins.length;i++)
for(int j=0;j<wins[i].length;j++)
if(wins[i][j]==m)
{
marks[i][j]=1;
if(player==playerid)
marks[i][knotcount]++;
else
marks[i][crosscount]++;
marks[i][totalcount]++;
}
}
private void fixWeights()
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(marks[i][j]==1)
if(weights[wins[i][j]-1]!=Integer.MIN_VALUE)
weights[wins[i][j]-1]=Integer.MIN_VALUE;
for(int i=0;i<8;i++)
{
if(marks[i][totalcount]!=2)
continue;
if(marks[i][crosscount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=6;
}
}
if(marks[i][knotcount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=5;
}
}
}
}
private int compMove()
{
int cell=move();
System.out.println("Computer plays: "+cell);
return cell;
}
private int move()
{
int max=Integer.MIN_VALUE;
int cell=0;
for(int i=0;i<weights.length;i++)
if(weights[i]>max)
{
max=weights[i];
cell=i+1;
}
if(movesPlayer.equals("76")||movesPlayer.equals("67"))
cell=9;
else if(movesPlayer.equals("92")||movesPlayer.equals("29"))
cell=3;
else if (movesPlayer.equals("18")||movesPlayer.equals("81"))
cell=7;
else if(movesPlayer.equals("73")||movesPlayer.equals("37"))
cell=4*((int)(Math.random()*2)+1);
else if(movesPlayer.equals("19")||movesPlayer.equals("91"))
cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));
mark(cell,1);
fixWeights();
crossbank.put(cell, 0);
return cell;
}
private int playerMove()
{
System.out.print("What's your move?: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int cell=0;
int okay=0;
while(okay==0)
{
try
{
cell=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(cell==7494)
{
override=1;
return -1;
}
if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)
System.out.print("Invalid move. Try again:");
else
okay=1;
}
playerMoved(cell);
System.out.println();
return cell;
}
private void playerMoved(int cell)
{
movesPlayer+=cell;
mark(cell,0);
fixWeights();
knotbank.put(cell, 0);
}
private int checkForWin()
{
int crossflag=0,knotflag=0;
for(int i=0;i<wins.length;i++)
{
if(crossbank.containsKey(wins[i][0]))
if(crossbank.containsKey(wins[i][1]))
if(crossbank.containsKey(wins[i][2]))
{
crossflag=1;
break;
}
if(knotbank.containsKey(wins[i][0]))
if(knotbank.containsKey(wins[i][1]))
if(knotbank.containsKey(wins[i][2]))
{
knotflag=1;
break;
}
}
if(knotflag==1)
{
display(grid);
System.out.println("O wins.");
return playerid;
}
else if(crossflag==1)
{
display(grid);
System.out.println("X wins.");
return compid;
}
for(int i=0;i<weights.length;i++)
if(weights[i]!=Integer.MIN_VALUE)
return playingid;
System.out.println("Truce");
return truceid;
}
private void display(char[][] grid)
{
for(int i=0;i<3;i++)
{
System.out.println("\n-------");
System.out.print("|");
for(int j=0;j<3;j++)
System.out.print(grid[i][j]+"|");
}
System.out.println("\n-------");
}
}
| <?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\.]{9}/i'; //Cat's game
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border="1">';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied
else { //Available
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type="hidden" name="b" value="', $boardStr, '"/>';
}
echo '</table>';
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
|
Write a version of this Java function in PHP with identical behavior. | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToe now=new TicTacToe();
now.startMatch();
}
private int[][] marks;
private int[][] wins;
private int[] weights;
private char[][] grid;
private final int knotcount=3;
private final int crosscount=4;
private final int totalcount=5;
private final int playerid=0;
private final int compid=1;
private final int truceid=2;
private final int playingid=3;
private String movesPlayer;
private byte override;
private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
private Hashtable<Integer,Integer> crossbank;
private Hashtable<Integer,Integer> knotbank;
public void startMatch()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Start?(y/n):");
char choice='y';
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(choice=='n'||choice=='N')
{
return;
}
System.out.println("Use a standard numpad as an entry grid, as so:\n ");
display(numpad);
System.out.println("Begin");
int playerscore=0;
int compscore=0;
do
{
int result=startGame();
if(result==playerid)
playerscore++;
else if(result==compid)
compscore++;
System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
System.out.print("Another?(y/n):");
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}while(choice!='n'||choice=='N');
System.out.println("Game over.");
}
private void put(int cell,int player)
{
int i=-1,j=-1;;
switch(cell)
{
case 1:i=2;j=0;break;
case 2:i=2;j=1;break;
case 3:i=2;j=2;break;
case 4:i=1;j=0;break;
case 5:i=1;j=1;break;
case 6:i=1;j=2;break;
case 7:i=0;j=0;break;
case 8:i=0;j=1;break;
case 9:i=0;j=2;break;
default:display(overridegrid);return;
}
char mark='x';
if(player==0)
mark='o';
grid[i][j]=mark;
display(grid);
}
private int startGame()
{
init();
display(grid);
int status=playingid;
while(status==playingid)
{
put(playerMove(),0);
if(override==1)
{
System.out.println("O wins.");
return playerid;
}
status=checkForWin();
if(status!=playingid)
break;
try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
put(compMove(),1);
status=checkForWin();
}
return status;
}
private void init()
{
movesPlayer="";
override=0;
marks=new int[8][6];
wins=new int[][]
{
{7,8,9},
{4,5,6},
{1,2,3},
{7,4,1},
{8,5,2},
{9,6,3},
{7,5,3},
{9,5,1}
};
weights=new int[]{3,2,3,2,4,2,3,2,3};
grid=new char[][]{{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
crossbank=new Hashtable<Integer,Integer>();
knotbank=new Hashtable<Integer,Integer>();
}
private void mark(int m,int player)
{
for(int i=0;i<wins.length;i++)
for(int j=0;j<wins[i].length;j++)
if(wins[i][j]==m)
{
marks[i][j]=1;
if(player==playerid)
marks[i][knotcount]++;
else
marks[i][crosscount]++;
marks[i][totalcount]++;
}
}
private void fixWeights()
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(marks[i][j]==1)
if(weights[wins[i][j]-1]!=Integer.MIN_VALUE)
weights[wins[i][j]-1]=Integer.MIN_VALUE;
for(int i=0;i<8;i++)
{
if(marks[i][totalcount]!=2)
continue;
if(marks[i][crosscount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=6;
}
}
if(marks[i][knotcount]==2)
{
int p=i,q=-1;
if(marks[i][0]==0)
q=0;
else if(marks[i][1]==0)
q=1;
else if(marks[i][2]==0)
q=2;
if(weights[wins[p][q]-1]!=Integer.MIN_VALUE)
{
weights[wins[p][q]-1]=5;
}
}
}
}
private int compMove()
{
int cell=move();
System.out.println("Computer plays: "+cell);
return cell;
}
private int move()
{
int max=Integer.MIN_VALUE;
int cell=0;
for(int i=0;i<weights.length;i++)
if(weights[i]>max)
{
max=weights[i];
cell=i+1;
}
if(movesPlayer.equals("76")||movesPlayer.equals("67"))
cell=9;
else if(movesPlayer.equals("92")||movesPlayer.equals("29"))
cell=3;
else if (movesPlayer.equals("18")||movesPlayer.equals("81"))
cell=7;
else if(movesPlayer.equals("73")||movesPlayer.equals("37"))
cell=4*((int)(Math.random()*2)+1);
else if(movesPlayer.equals("19")||movesPlayer.equals("91"))
cell=4+2*(int)(Math.pow(-1, (int)(Math.random()*2)));
mark(cell,1);
fixWeights();
crossbank.put(cell, 0);
return cell;
}
private int playerMove()
{
System.out.print("What's your move?: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int cell=0;
int okay=0;
while(okay==0)
{
try
{
cell=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(cell==7494)
{
override=1;
return -1;
}
if((cell<1||cell>9)||weights[cell-1]==Integer.MIN_VALUE)
System.out.print("Invalid move. Try again:");
else
okay=1;
}
playerMoved(cell);
System.out.println();
return cell;
}
private void playerMoved(int cell)
{
movesPlayer+=cell;
mark(cell,0);
fixWeights();
knotbank.put(cell, 0);
}
private int checkForWin()
{
int crossflag=0,knotflag=0;
for(int i=0;i<wins.length;i++)
{
if(crossbank.containsKey(wins[i][0]))
if(crossbank.containsKey(wins[i][1]))
if(crossbank.containsKey(wins[i][2]))
{
crossflag=1;
break;
}
if(knotbank.containsKey(wins[i][0]))
if(knotbank.containsKey(wins[i][1]))
if(knotbank.containsKey(wins[i][2]))
{
knotflag=1;
break;
}
}
if(knotflag==1)
{
display(grid);
System.out.println("O wins.");
return playerid;
}
else if(crossflag==1)
{
display(grid);
System.out.println("X wins.");
return compid;
}
for(int i=0;i<weights.length;i++)
if(weights[i]!=Integer.MIN_VALUE)
return playingid;
System.out.println("Truce");
return truceid;
}
private void display(char[][] grid)
{
for(int i=0;i<3;i++)
{
System.out.println("\n-------");
System.out.print("|");
for(int j=0;j<3;j++)
System.out.print(grid[i][j]+"|");
}
System.out.println("\n-------");
}
}
| <?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\.]{9}/i'; //Cat's game
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border="1">';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied
else { //Available
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type="hidden" name="b" value="', $boardStr, '"/>';
}
echo '</table>';
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
|
Generate an equivalent PHP version of this Java code. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
| <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
|
Rewrite this program in PHP while keeping its functionality equivalent to the Java version. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
| <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
|
Generate a PHP translation of this Java snippet without changing its computational steps. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
| <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
|
Ensure the translated PHP code behaves exactly like the original Java snippet. | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
| <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
|
Generate a PHP translation of this Java snippet without changing its computational steps. | import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
class DnsQuery {
public static void main(String[] args) {
try {
InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net");
for(int i=0; i < ipAddr.length ; i++) {
if (ipAddr[i] instanceof Inet4Address) {
System.out.println("IPv4 : " + ipAddr[i].getHostAddress());
} else if (ipAddr[i] instanceof Inet6Address) {
System.out.println("IPv6 : " + ipAddr[i].getHostAddress());
}
}
} catch (UnknownHostException uhe) {
System.err.println("unknown host");
}
}
}
| <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
|
Ensure the translated PHP code behaves exactly like the original Java snippet. | import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
class DnsQuery {
public static void main(String[] args) {
try {
InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net");
for(int i=0; i < ipAddr.length ; i++) {
if (ipAddr[i] instanceof Inet4Address) {
System.out.println("IPv4 : " + ipAddr[i].getHostAddress());
} else if (ipAddr[i] instanceof Inet6Address) {
System.out.println("IPv6 : " + ipAddr[i].getHostAddress());
}
}
} catch (UnknownHostException uhe) {
System.err.println("unknown host");
}
}
}
| <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
|
Port the following code from Java to PHP with equivalent syntax and logic. | import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Random;
public class RPS {
public enum Item{
ROCK, PAPER, SCISSORS, ;
public List<Item> losesToList;
public boolean losesTo(Item other) {
return losesToList.contains(other);
}
static {
SCISSORS.losesToList = Arrays.asList(ROCK);
ROCK.losesToList = Arrays.asList(PAPER);
PAPER.losesToList = Arrays.asList(SCISSORS);
}
}
public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{
for(Item item:Item.values())
put(item, 1);
}};
private int totalThrows = Item.values().length;
public static void main(String[] args){
RPS rps = new RPS();
rps.run();
}
public void run() {
Scanner in = new Scanner(System.in);
System.out.print("Make your choice: ");
while(in.hasNextLine()){
Item aiChoice = getAIChoice();
String input = in.nextLine();
Item choice;
try{
choice = Item.valueOf(input.toUpperCase());
}catch (IllegalArgumentException ex){
System.out.println("Invalid choice");
continue;
}
counts.put(choice, counts.get(choice) + 1);
totalThrows++;
System.out.println("Computer chose: " + aiChoice);
if(aiChoice == choice){
System.out.println("Tie!");
}else if(aiChoice.losesTo(choice)){
System.out.println("You chose...wisely. You win!");
}else{
System.out.println("You chose...poorly. You lose!");
}
System.out.print("Make your choice: ");
}
}
private static final Random rng = new Random();
private Item getAIChoice() {
int rand = rng.nextInt(totalThrows);
for(Map.Entry<Item, Integer> entry:counts.entrySet()){
Item item = entry.getKey();
int count = entry.getValue();
if(rand < count){
List<Item> losesTo = item.losesToList;
return losesTo.get(rng.nextInt(losesTo.size()));
}
rand -= count;
}
return null;
}
}
| <?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";
$player = strtoupper( $_GET["moves"] );
$wins = [
'ROCK' => 'SCISSORS',
'PAPER' => 'ROCK',
'SCISSORS' => 'PAPER'
];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>";
echo "<br>";
echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>";
$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
$results = "A.I wins";
} else {
$results = "Player wins";
}
echo "<br>" . $results;
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the Java version. | import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Random;
public class RPS {
public enum Item{
ROCK, PAPER, SCISSORS, ;
public List<Item> losesToList;
public boolean losesTo(Item other) {
return losesToList.contains(other);
}
static {
SCISSORS.losesToList = Arrays.asList(ROCK);
ROCK.losesToList = Arrays.asList(PAPER);
PAPER.losesToList = Arrays.asList(SCISSORS);
}
}
public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{
for(Item item:Item.values())
put(item, 1);
}};
private int totalThrows = Item.values().length;
public static void main(String[] args){
RPS rps = new RPS();
rps.run();
}
public void run() {
Scanner in = new Scanner(System.in);
System.out.print("Make your choice: ");
while(in.hasNextLine()){
Item aiChoice = getAIChoice();
String input = in.nextLine();
Item choice;
try{
choice = Item.valueOf(input.toUpperCase());
}catch (IllegalArgumentException ex){
System.out.println("Invalid choice");
continue;
}
counts.put(choice, counts.get(choice) + 1);
totalThrows++;
System.out.println("Computer chose: " + aiChoice);
if(aiChoice == choice){
System.out.println("Tie!");
}else if(aiChoice.losesTo(choice)){
System.out.println("You chose...wisely. You win!");
}else{
System.out.println("You chose...poorly. You lose!");
}
System.out.print("Make your choice: ");
}
}
private static final Random rng = new Random();
private Item getAIChoice() {
int rand = rng.nextInt(totalThrows);
for(Map.Entry<Item, Integer> entry:counts.entrySet()){
Item item = entry.getKey();
int count = entry.getValue();
if(rand < count){
List<Item> losesTo = item.losesToList;
return losesTo.get(rng.nextInt(losesTo.size()));
}
rand -= count;
}
return null;
}
}
| <?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";
$player = strtoupper( $_GET["moves"] );
$wins = [
'ROCK' => 'SCISSORS',
'PAPER' => 'ROCK',
'SCISSORS' => 'PAPER'
];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>";
echo "<br>";
echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>";
$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
$results = "A.I wins";
} else {
$results = "Player wins";
}
echo "<br>" . $results;
?>
|
Translate this program into PHP but keep the logic exactly as in Java. | import java.util.function.Function;
public interface YCombinator {
interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }
public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {
RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));
return r.apply(r);
}
public static void main(String... arguments) {
Function<Integer,Integer> fib = Y(f -> n ->
(n <= 2)
? 1
: (f.apply(n - 1) + f.apply(n - 2))
);
Function<Integer,Integer> fac = Y(f -> n ->
(n <= 1)
? 1
: (n * f.apply(n - 1))
);
System.out.println("fib(10) = " + fib.apply(10));
System.out.println("fac(10) = " + fac.apply(10));
}
}
| <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "\n";
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), "\n";
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the Java version. | import java.util.function.Function;
public interface YCombinator {
interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }
public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {
RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));
return r.apply(r);
}
public static void main(String... arguments) {
Function<Integer,Integer> fib = Y(f -> n ->
(n <= 2)
? 1
: (f.apply(n - 1) + f.apply(n - 2))
);
Function<Integer,Integer> fac = Y(f -> n ->
(n <= 1)
? 1
: (n * f.apply(n - 1))
);
System.out.println("fib(10) = " + fib.apply(10));
System.out.println("fac(10) = " + fac.apply(10));
}
}
| <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "\n";
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), "\n";
?>
|
Can you help me rewrite this code in PHP instead of Java, keeping it the same logically? | import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class RReturnMultipleVals {
public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
public static final Long K_1024 = 1024L;
public static final String L = "L";
public static final String R = "R";
public static void main(String[] args) throws NumberFormatException{
Long nv_;
String sv_;
switch (args.length) {
case 0:
nv_ = K_1024;
sv_ = K_lipsum;
break;
case 1:
nv_ = Long.parseLong(args[0]);
sv_ = K_lipsum;
break;
case 2:
nv_ = Long.parseLong(args[0]);
sv_ = args[1];
break;
default:
nv_ = Long.parseLong(args[0]);
sv_ = args[1];
for (int ix = 2; ix < args.length; ++ix) {
sv_ = sv_ + " " + args[ix];
}
break;
}
RReturnMultipleVals lcl = new RReturnMultipleVals();
Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_);
System.out.println("Results extracted from a composite object:");
System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal());
List<Object> rvl = lcl.getPairFromList(nv_, sv_);
System.out.println("Results extracted from a Java Colections \"List\" object:");
System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1));
Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_);
System.out.println("Results extracted from a Java Colections \"Map\" object:");
System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R));
}
public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {
return new Pair<T, U>(vl_, vr_);
}
public List<Object> getPairFromList(Object nv_, Object sv_) {
List<Object> rset = new ArrayList<Object>();
rset.add(nv_);
rset.add(sv_);
return rset;
}
public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {
Map<String, Object> rset = new HashMap<String, Object>();
rset.put(L, nv_);
rset.put(R, sv_);
return rset;
}
private static class Pair<L, R> {
private L leftVal;
private R rightVal;
public Pair(L nv_, R sv_) {
setLeftVal(nv_);
setRightVal(sv_);
}
public void setLeftVal(L nv_) {
leftVal = nv_;
}
public L getLeftVal() {
return leftVal;
}
public void setRightVal(R sv_) {
rightVal = sv_;
}
public R getRightVal() {
return rightVal;
}
}
}
| function addsub($x, $y) {
return array($x + $y, $x - $y);
}
|
Change the programming language of this snippet from Java to PHP without modifying what it does. | import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class RReturnMultipleVals {
public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
public static final Long K_1024 = 1024L;
public static final String L = "L";
public static final String R = "R";
public static void main(String[] args) throws NumberFormatException{
Long nv_;
String sv_;
switch (args.length) {
case 0:
nv_ = K_1024;
sv_ = K_lipsum;
break;
case 1:
nv_ = Long.parseLong(args[0]);
sv_ = K_lipsum;
break;
case 2:
nv_ = Long.parseLong(args[0]);
sv_ = args[1];
break;
default:
nv_ = Long.parseLong(args[0]);
sv_ = args[1];
for (int ix = 2; ix < args.length; ++ix) {
sv_ = sv_ + " " + args[ix];
}
break;
}
RReturnMultipleVals lcl = new RReturnMultipleVals();
Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_);
System.out.println("Results extracted from a composite object:");
System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal());
List<Object> rvl = lcl.getPairFromList(nv_, sv_);
System.out.println("Results extracted from a Java Colections \"List\" object:");
System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1));
Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_);
System.out.println("Results extracted from a Java Colections \"Map\" object:");
System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R));
}
public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) {
return new Pair<T, U>(vl_, vr_);
}
public List<Object> getPairFromList(Object nv_, Object sv_) {
List<Object> rset = new ArrayList<Object>();
rset.add(nv_);
rset.add(sv_);
return rset;
}
public Map<String, Object> getPairFromMap(Object nv_, Object sv_) {
Map<String, Object> rset = new HashMap<String, Object>();
rset.put(L, nv_);
rset.put(R, sv_);
return rset;
}
private static class Pair<L, R> {
private L leftVal;
private R rightVal;
public Pair(L nv_, R sv_) {
setLeftVal(nv_);
setRightVal(sv_);
}
public void setLeftVal(L nv_) {
leftVal = nv_;
}
public L getLeftVal() {
return leftVal;
}
public void setRightVal(R sv_) {
rightVal = sv_;
}
public R getRightVal() {
return rightVal;
}
}
}
| function addsub($x, $y) {
return array($x + $y, $x - $y);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.