Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite the snippet below in Java so it works the same as the original Python code. | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
| public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0);
int count = 0;
for(int j = 0; j < s.length(); j++){
int temp = Integer.parseInt(s.charAt(j) + "");
if(temp == i){
count++;
}
if (count > b) return false;
}
if(count != b) return false;
}
return true;
}
public static void main(String[] args){
for(int i = 0; i < 100000000; i++){
if(isSelfDescribing(i)){
System.out.println(i);
}
}
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | >>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
| public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0);
int count = 0;
for(int j = 0; j < s.length(); j++){
int temp = Integer.parseInt(s.charAt(j) + "");
if(temp == i){
count++;
}
if (count > b) return false;
}
if(count != b) return false;
}
return true;
}
public static void main(String[] args){
for(int i = 0; i < 100000000; i++){
if(isSelfDescribing(i)){
System.out.println(i);
}
}
}
}
|
Port the provided Python code into Java while preserving the original functionality. | def prepend(n, seq):
return [n] + seq
def check_seq(pos, seq, n, min_len):
if pos > min_len or seq[0] > n:
return min_len, 0
if seq[0] == n:
return pos, 1
if pos < min_len:
return try_perm(0, pos, seq, n, min_len)
return min_len, 0
def try_perm(i, pos, seq, n, min_len):
if i > pos:
return min_len, 0
res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)
res2 = try_perm(i + 1, pos, seq, n, res1[0])
if res2[0] < res1[0]:
return res2
if res2[0] == res1[0]:
return res2[0], res1[1] + res2[1]
raise Exception("try_perm exception")
def init_try_perm(x):
return try_perm(0, 0, [1], x, 12)
def find_brauer(num):
res = init_try_perm(num)
print
print "N = ", num
print "Minimum length of chains: L(n) = ", res[0]
print "Number of minimum length Brauer chains: ", res[1]
nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums:
find_brauer(i)
| public class AdditionChains {
private static class Pair {
int f, s;
Pair(int f, int s) {
this.f = f;
this.s = s;
}
}
private static int[] prepend(int n, int[] seq) {
int[] result = new int[seq.length + 1];
result[0] = n;
System.arraycopy(seq, 0, result, 1, seq.length);
return result;
}
private static Pair check_seq(int pos, int[] seq, int n, int min_len) {
if (pos > min_len || seq[0] > n) return new Pair(min_len, 0);
else if (seq[0] == n) return new Pair(pos, 1);
else if (pos < min_len) return try_perm(0, pos, seq, n, min_len);
else return new Pair(min_len, 0);
}
private static Pair try_perm(int i, int pos, int[] seq, int n, int min_len) {
if (i > pos) return new Pair(min_len, 0);
Pair res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len);
Pair res2 = try_perm(i + 1, pos, seq, n, res1.f);
if (res2.f < res1.f) return res2;
else if (res2.f == res1.f) return new Pair(res2.f, res1.s + res2.s);
else throw new RuntimeException("Try_perm exception");
}
private static Pair init_try_perm(int x) {
return try_perm(0, 0, new int[]{1}, x, 12);
}
private static void find_brauer(int num) {
Pair res = init_try_perm(num);
System.out.println();
System.out.println("N = " + num);
System.out.println("Minimum length of chains: L(n)= " + res.f);
System.out.println("Number of minimum length Brauer chains: " + res.s);
}
public static void main(String[] args) {
int[] nums = new int[]{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379};
for (int i : nums) {
find_brauer(i);
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. |
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3);
| import java.util.function.Consumer;
import java.util.stream.IntStream;
public class Repeat {
public static void main(String[] args) {
repeat(3, (x) -> System.out.println("Example " + x));
}
static void repeat (int n, Consumer<Integer> fun) {
IntStream.range(0, n).forEach(i -> fun.accept(i + 1));
}
}
|
Translate the given Python code snippet into Java without altering its behavior. |
bar = 'βββββ
βββ'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __name__ == '__main__':
import re
for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'):
print("\nNumbers:", line)
numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())]
mn, mx, sp = sparkline(numbers)
print(' min: %5f; max: %5f' % (mn, mx))
print(" " + sp)
| public class Sparkline
{
String bars="βββββ
βββ";
public static void main(String[] args)
{
Sparkline now=new Sparkline();
float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
now.display1D(arr);
System.out.println(now.getSparkline(arr));
float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};
now.display1D(arr1);
System.out.println(now.getSparkline(arr1));
}
public void display1D(float[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public String getSparkline(float[] arr)
{
float min=Integer.MAX_VALUE;
float max=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++)
{
if(arr[i]<min)
min=arr[i];
if(arr[i]>max)
max=arr[i];
}
float range=max-min;
int num=bars.length()-1;
String line="";
for(int i=0;i<arr.length;i++)
{
line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));
}
return line;
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| import java.util.Scanner;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Interpreter {
static Map<String, Integer> globals = new HashMap<>();
static Scanner s;
static List<Node> list = new ArrayList<>();
static Map<String, NodeType> str_to_nodes = new HashMap<>();
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static enum NodeType {
nd_None(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"),
nd_Sequence("Sequence"), nd_If("If"),
nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"),
nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"),
nd_Mod("Mod"), nd_Add("Add"),
nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"),
nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or");
private final String name;
NodeType(String name) { this.name = name; }
@Override
public String toString() { return this.name; }
}
static String str(String s) {
String result = "";
int i = 0;
s = s.replace("\"", "");
while (i < s.length()) {
if (s.charAt(i) == '\\' && i + 1 < s.length()) {
if (s.charAt(i + 1) == 'n') {
result += '\n';
i += 2;
} else if (s.charAt(i) == '\\') {
result += '\\';
i += 2;
}
} else {
result += s.charAt(i);
i++;
}
}
return result;
}
static boolean itob(int i) {
return i != 0;
}
static int btoi(boolean b) {
return b ? 1 : 0;
}
static int fetch_var(String name) {
int result;
if (globals.containsKey(name)) {
result = globals.get(name);
} else {
globals.put(name, 0);
result = 0;
}
return result;
}
static Integer interpret(Node n) throws Exception {
if (n == null) {
return 0;
}
switch (n.nt) {
case nd_Integer:
return Integer.parseInt(n.value);
case nd_Ident:
return fetch_var(n.value);
case nd_String:
return 1;
case nd_Assign:
globals.put(n.left.value, interpret(n.right));
return 0;
case nd_Add:
return interpret(n.left) + interpret(n.right);
case nd_Sub:
return interpret(n.left) - interpret(n.right);
case nd_Mul:
return interpret(n.left) * interpret(n.right);
case nd_Div:
return interpret(n.left) / interpret(n.right);
case nd_Mod:
return interpret(n.left) % interpret(n.right);
case nd_Lss:
return btoi(interpret(n.left) < interpret(n.right));
case nd_Leq:
return btoi(interpret(n.left) <= interpret(n.right));
case nd_Gtr:
return btoi(interpret(n.left) > interpret(n.right));
case nd_Geq:
return btoi(interpret(n.left) >= interpret(n.right));
case nd_Eql:
return btoi(interpret(n.left) == interpret(n.right));
case nd_Neq:
return btoi(interpret(n.left) != interpret(n.right));
case nd_And:
return btoi(itob(interpret(n.left)) && itob(interpret(n.right)));
case nd_Or:
return btoi(itob(interpret(n.left)) || itob(interpret(n.right)));
case nd_Not:
if (interpret(n.left) == 0) {
return 1;
} else {
return 0;
}
case nd_Negate:
return -interpret(n.left);
case nd_If:
if (interpret(n.left) != 0) {
interpret(n.right.left);
} else {
interpret(n.right.right);
}
return 0;
case nd_While:
while (interpret(n.left) != 0) {
interpret(n.right);
}
return 0;
case nd_Prtc:
System.out.printf("%c", interpret(n.left));
return 0;
case nd_Prti:
System.out.printf("%d", interpret(n.left));
return 0;
case nd_Prts:
System.out.print(str(n.left.value));
return 0;
case nd_Sequence:
interpret(n.left);
interpret(n.right);
return 0;
default:
throw new Exception("Error: '" + n.nt + "' found, expecting operator");
}
}
static Node load_ast() throws Exception {
String command, value;
String line;
Node left, right;
while (s.hasNext()) {
line = s.nextLine();
value = null;
if (line.length() > 16) {
command = line.substring(0, 15).trim();
value = line.substring(15).trim();
} else {
command = line.trim();
}
if (command.equals(";")) {
return null;
}
if (!str_to_nodes.containsKey(command)) {
throw new Exception("Command not found: '" + command + "'");
}
if (value != null) {
return Node.make_leaf(str_to_nodes.get(command), value);
}
left = load_ast(); right = load_ast();
return Node.make_node(str_to_nodes.get(command), left, right);
}
return null;
}
public static void main(String[] args) {
Node n;
str_to_nodes.put(";", NodeType.nd_None);
str_to_nodes.put("Sequence", NodeType.nd_Sequence);
str_to_nodes.put("Identifier", NodeType.nd_Ident);
str_to_nodes.put("String", NodeType.nd_String);
str_to_nodes.put("Integer", NodeType.nd_Integer);
str_to_nodes.put("If", NodeType.nd_If);
str_to_nodes.put("While", NodeType.nd_While);
str_to_nodes.put("Prtc", NodeType.nd_Prtc);
str_to_nodes.put("Prts", NodeType.nd_Prts);
str_to_nodes.put("Prti", NodeType.nd_Prti);
str_to_nodes.put("Assign", NodeType.nd_Assign);
str_to_nodes.put("Negate", NodeType.nd_Negate);
str_to_nodes.put("Not", NodeType.nd_Not);
str_to_nodes.put("Multiply", NodeType.nd_Mul);
str_to_nodes.put("Divide", NodeType.nd_Div);
str_to_nodes.put("Mod", NodeType.nd_Mod);
str_to_nodes.put("Add", NodeType.nd_Add);
str_to_nodes.put("Subtract", NodeType.nd_Sub);
str_to_nodes.put("Less", NodeType.nd_Lss);
str_to_nodes.put("LessEqual", NodeType.nd_Leq);
str_to_nodes.put("Greater", NodeType.nd_Gtr);
str_to_nodes.put("GreaterEqual", NodeType.nd_Geq);
str_to_nodes.put("Equal", NodeType.nd_Eql);
str_to_nodes.put("NotEqual", NodeType.nd_Neq);
str_to_nodes.put("And", NodeType.nd_And);
str_to_nodes.put("Or", NodeType.nd_Or);
if (args.length > 0) {
try {
s = new Scanner(new File(args[0]));
n = load_ast();
interpret(n);
} catch (Exception e) {
System.out.println("Ex: "+e.getMessage());
}
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = load_ast()
return make_node(node_type, left, right)
| import java.util.Scanner;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Interpreter {
static Map<String, Integer> globals = new HashMap<>();
static Scanner s;
static List<Node> list = new ArrayList<>();
static Map<String, NodeType> str_to_nodes = new HashMap<>();
static class Node {
public NodeType nt;
public Node left, right;
public String value;
Node() {
this.nt = null;
this.left = null;
this.right = null;
this.value = null;
}
Node(NodeType node_type, Node left, Node right, String value) {
this.nt = node_type;
this.left = left;
this.right = right;
this.value = value;
}
public static Node make_node(NodeType nodetype, Node left, Node right) {
return new Node(nodetype, left, right, "");
}
public static Node make_node(NodeType nodetype, Node left) {
return new Node(nodetype, left, null, "");
}
public static Node make_leaf(NodeType nodetype, String value) {
return new Node(nodetype, null, null, value);
}
}
static enum NodeType {
nd_None(";"), nd_Ident("Identifier"), nd_String("String"), nd_Integer("Integer"),
nd_Sequence("Sequence"), nd_If("If"),
nd_Prtc("Prtc"), nd_Prts("Prts"), nd_Prti("Prti"), nd_While("While"),
nd_Assign("Assign"), nd_Negate("Negate"), nd_Not("Not"), nd_Mul("Multiply"), nd_Div("Divide"),
nd_Mod("Mod"), nd_Add("Add"),
nd_Sub("Subtract"), nd_Lss("Less"), nd_Leq("LessEqual"),
nd_Gtr("Greater"), nd_Geq("GreaterEqual"), nd_Eql("Equal"), nd_Neq("NotEqual"), nd_And("And"), nd_Or("Or");
private final String name;
NodeType(String name) { this.name = name; }
@Override
public String toString() { return this.name; }
}
static String str(String s) {
String result = "";
int i = 0;
s = s.replace("\"", "");
while (i < s.length()) {
if (s.charAt(i) == '\\' && i + 1 < s.length()) {
if (s.charAt(i + 1) == 'n') {
result += '\n';
i += 2;
} else if (s.charAt(i) == '\\') {
result += '\\';
i += 2;
}
} else {
result += s.charAt(i);
i++;
}
}
return result;
}
static boolean itob(int i) {
return i != 0;
}
static int btoi(boolean b) {
return b ? 1 : 0;
}
static int fetch_var(String name) {
int result;
if (globals.containsKey(name)) {
result = globals.get(name);
} else {
globals.put(name, 0);
result = 0;
}
return result;
}
static Integer interpret(Node n) throws Exception {
if (n == null) {
return 0;
}
switch (n.nt) {
case nd_Integer:
return Integer.parseInt(n.value);
case nd_Ident:
return fetch_var(n.value);
case nd_String:
return 1;
case nd_Assign:
globals.put(n.left.value, interpret(n.right));
return 0;
case nd_Add:
return interpret(n.left) + interpret(n.right);
case nd_Sub:
return interpret(n.left) - interpret(n.right);
case nd_Mul:
return interpret(n.left) * interpret(n.right);
case nd_Div:
return interpret(n.left) / interpret(n.right);
case nd_Mod:
return interpret(n.left) % interpret(n.right);
case nd_Lss:
return btoi(interpret(n.left) < interpret(n.right));
case nd_Leq:
return btoi(interpret(n.left) <= interpret(n.right));
case nd_Gtr:
return btoi(interpret(n.left) > interpret(n.right));
case nd_Geq:
return btoi(interpret(n.left) >= interpret(n.right));
case nd_Eql:
return btoi(interpret(n.left) == interpret(n.right));
case nd_Neq:
return btoi(interpret(n.left) != interpret(n.right));
case nd_And:
return btoi(itob(interpret(n.left)) && itob(interpret(n.right)));
case nd_Or:
return btoi(itob(interpret(n.left)) || itob(interpret(n.right)));
case nd_Not:
if (interpret(n.left) == 0) {
return 1;
} else {
return 0;
}
case nd_Negate:
return -interpret(n.left);
case nd_If:
if (interpret(n.left) != 0) {
interpret(n.right.left);
} else {
interpret(n.right.right);
}
return 0;
case nd_While:
while (interpret(n.left) != 0) {
interpret(n.right);
}
return 0;
case nd_Prtc:
System.out.printf("%c", interpret(n.left));
return 0;
case nd_Prti:
System.out.printf("%d", interpret(n.left));
return 0;
case nd_Prts:
System.out.print(str(n.left.value));
return 0;
case nd_Sequence:
interpret(n.left);
interpret(n.right);
return 0;
default:
throw new Exception("Error: '" + n.nt + "' found, expecting operator");
}
}
static Node load_ast() throws Exception {
String command, value;
String line;
Node left, right;
while (s.hasNext()) {
line = s.nextLine();
value = null;
if (line.length() > 16) {
command = line.substring(0, 15).trim();
value = line.substring(15).trim();
} else {
command = line.trim();
}
if (command.equals(";")) {
return null;
}
if (!str_to_nodes.containsKey(command)) {
throw new Exception("Command not found: '" + command + "'");
}
if (value != null) {
return Node.make_leaf(str_to_nodes.get(command), value);
}
left = load_ast(); right = load_ast();
return Node.make_node(str_to_nodes.get(command), left, right);
}
return null;
}
public static void main(String[] args) {
Node n;
str_to_nodes.put(";", NodeType.nd_None);
str_to_nodes.put("Sequence", NodeType.nd_Sequence);
str_to_nodes.put("Identifier", NodeType.nd_Ident);
str_to_nodes.put("String", NodeType.nd_String);
str_to_nodes.put("Integer", NodeType.nd_Integer);
str_to_nodes.put("If", NodeType.nd_If);
str_to_nodes.put("While", NodeType.nd_While);
str_to_nodes.put("Prtc", NodeType.nd_Prtc);
str_to_nodes.put("Prts", NodeType.nd_Prts);
str_to_nodes.put("Prti", NodeType.nd_Prti);
str_to_nodes.put("Assign", NodeType.nd_Assign);
str_to_nodes.put("Negate", NodeType.nd_Negate);
str_to_nodes.put("Not", NodeType.nd_Not);
str_to_nodes.put("Multiply", NodeType.nd_Mul);
str_to_nodes.put("Divide", NodeType.nd_Div);
str_to_nodes.put("Mod", NodeType.nd_Mod);
str_to_nodes.put("Add", NodeType.nd_Add);
str_to_nodes.put("Subtract", NodeType.nd_Sub);
str_to_nodes.put("Less", NodeType.nd_Lss);
str_to_nodes.put("LessEqual", NodeType.nd_Leq);
str_to_nodes.put("Greater", NodeType.nd_Gtr);
str_to_nodes.put("GreaterEqual", NodeType.nd_Geq);
str_to_nodes.put("Equal", NodeType.nd_Eql);
str_to_nodes.put("NotEqual", NodeType.nd_Neq);
str_to_nodes.put("And", NodeType.nd_And);
str_to_nodes.put("Or", NodeType.nd_Or);
if (args.length > 0) {
try {
s = new Scanner(new File(args[0]));
n = load_ast();
interpret(n);
} catch (Exception e) {
System.out.println("Ex: "+e.getMessage());
}
}
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
>>> modinv(42, 2017)
1969
>>>
| System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
|
Port the provided Python code into Java while preserving the original functionality. | >>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x % m
>>> modinv(42, 2017)
1969
>>>
| System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
|
Port the provided Python code into Java while preserving the original functionality. | import ctypes
def click():
ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)
ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)
click()
| Point p = component.getLocation();
Robot robot = new Robot();
robot.mouseMove(p.getX(), p.getY());
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
|
Ensure the translated Java code behaves exactly like the original Python snippet. | from wsgiref.simple_server import make_server
def app(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
yield b"<h1>Goodbye, World!</h1>"
server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
| import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloWorld{
public static void main(String[] args) throws IOException{
ServerSocket listener = new ServerSocket(8080);
while(true){
Socket sock = listener.accept();
new PrintWriter(sock.getOutputStream(), true).
println("Goodbye, World!");
sock.close();
}
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | import os
os.system("clear")
| public class Clear
{
public static void main (String[] args)
{
System.out.print("\033[2J");
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | from turtle import *
from math import *
iter = 3000
diskRatio = .5
factor = .5 + sqrt(1.25)
screen = getscreen()
(winWidth, winHeight) = screen.screensize()
x = 0.0
y = 0.0
maxRad = pow(iter,factor)/iter;
bgcolor("light blue")
hideturtle()
tracer(0, 0)
for i in range(iter+1):
r = pow(i,factor)/iter;
if r/maxRad < diskRatio:
pencolor("black")
else:
pencolor("yellow")
theta = 2*pi*factor*i;
up()
setposition(x + r*sin(theta), y + r*cos(theta))
down()
circle(10.0 * i/(1.0*iter))
update()
done()
|
size(1000,1000);
surface.setTitle("Sunflower...");
int iter = 3000;
float factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5;
float x = width/2.0, y = height/2.0;
double maxRad = pow(iter,factor)/iter;
int i;
background(#add8e6);
for(i=0;i<=iter;i++){
r = pow(i,factor)/iter;
if(r/maxRad < diskRatio){
stroke(#000000);
}
else
stroke(#ffff00);
theta = 2*PI*factor*i;
ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter));
}
|
Write a version of this Python function in Java with identical behavior. | from collections import defaultdict
costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}
cols = sorted(demand.iterkeys())
supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}
res = dict((k, defaultdict(int)) for k in costs)
g = {}
for x in supply:
g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])
for x in demand:
g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])
while g:
d = {}
for x in demand:
d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]
s = {}
for x in supply:
s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]
f = max(d, key=lambda n: d[n])
t = max(s, key=lambda n: s[n])
t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)
v = min(supply[f], demand[t])
res[f][t] += v
demand[t] -= v
if demand[t] == 0:
for k, n in supply.iteritems():
if n != 0:
g[k].remove(t)
del g[t]
del demand[t]
supply[f] -= v
if supply[f] == 0:
for k, n in demand.iteritems():
if n != 0:
g[k].remove(f)
del g[f]
del supply[f]
for n in cols:
print "\t", n,
print
cost = 0
for g in sorted(costs):
print g, "\t",
for n in cols:
y = res[g][n]
if y != 0:
print y,
cost += y * costs[g][n]
print "\t",
print
print "\n\nTotal Cost = ", cost
| import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;
public class VogelsApproximationMethod {
final static int[] demand = {30, 20, 70, 30, 60};
final static int[] supply = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
{19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};
final static int nRows = supply.length;
final static int nCols = demand.length;
static boolean[] rowDone = new boolean[nRows];
static boolean[] colDone = new boolean[nCols];
static int[][] result = new int[nRows][nCols];
static ExecutorService es = Executors.newFixedThreadPool(2);
public static void main(String[] args) throws Exception {
int supplyLeft = stream(supply).sum();
int totalCost = 0;
while (supplyLeft > 0) {
int[] cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = Math.min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0)
colDone[c] = true;
supply[r] -= quantity;
if (supply[r] == 0)
rowDone[r] = true;
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
System.out.println("Total cost: " + totalCost);
es.shutdown();
}
static int[] nextCell() throws Exception {
Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));
Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));
int[] res1 = f1.get();
int[] res2 = f2.get();
if (res1[3] == res2[3])
return res1[2] < res2[2] ? res1 : res2;
return (res1[3] > res2[3]) ? res2 : res1;
}
static int[] diff(int j, int len, boolean isRow) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
int minP = -1;
for (int i = 0; i < len; i++) {
if (isRow ? colDone[i] : rowDone[i])
continue;
int c = isRow ? costs[j][i] : costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
minP = i;
} else if (c < min2)
min2 = c;
}
return new int[]{min2 - min1, min1, minP};
}
static int[] maxPenalty(int len1, int len2, boolean isRow) {
int md = Integer.MIN_VALUE;
int pc = -1, pm = -1, mc = -1;
for (int i = 0; i < len1; i++) {
if (isRow ? rowDone[i] : colDone[i])
continue;
int[] res = diff(i, len2, isRow);
if (res[0] > md) {
md = res[0];
pm = i;
mc = res[1];
pc = res[2];
}
}
return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. |
from math import sqrt, cos, exp
DEG = 0.017453292519943295769236907684886127134
RE = 6371000
dd = 0.001
FIN = 10000000
def rho(a):
return exp(-a / 8500.0)
def height(a, z, d):
return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE
def column_density(a, z):
dsum, d = 0.0, 0.0
while d < FIN:
delta = max(dd, (dd)*d)
dsum += rho(height(a, z, d + 0.5 * delta)) * delta
d += delta
return dsum
def airmass(a, z):
return column_density(a, z) / column_density(a, 0)
print('Angle 0 m 13700 m\n', '-' * 36)
for z in range(0, 91, 5):
print(f"{z: 3d} {airmass(0, z): 12.7f} {airmass(13700, z): 12.7f}")
| public class AirMass {
public static void main(String[] args) {
System.out.println("Angle 0 m 13700 m");
System.out.println("------------------------------------");
for (double z = 0; z <= 90; z+= 5) {
System.out.printf("%2.0f %11.8f %11.8f\n",
z, airmass(0.0, z), airmass(13700.0, z));
}
}
private static double rho(double a) {
return Math.exp(-a / 8500.0);
}
private static double height(double a, double z, double d) {
double aa = RE + a;
double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));
return hh - RE;
}
private static double columnDensity(double a, double z) {
double sum = 0.0, d = 0.0;
while (d < FIN) {
double delta = Math.max(DD * d, DD);
sum += rho(height(a, z, d + 0.5 * delta)) * delta;
d += delta;
}
return sum;
}
private static double airmass(double a, double z) {
return columnDensity(a, z) / columnDensity(a, 0.0);
}
private static final double RE = 6371000.0;
private static final double DD = 0.001;
private static final double FIN = 10000000.0;
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | tutor = False
def pancakesort(data):
if len(data) <= 1:
return data
if tutor: print()
for size in range(len(data), 1, -1):
maxindex = max(range(size), key=data.__getitem__)
if maxindex+1 != size:
if maxindex != 0:
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), maxindex+1 ))
data[:maxindex+1] = reversed(data[:maxindex+1])
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), size ))
data[:size] = reversed(data[:size])
if tutor: print()
| public class PancakeSort
{
int[] heap;
public String toString() {
String info = "";
for (int x: heap)
info += x + " ";
return info;
}
public void flip(int n) {
for (int i = 0; i < (n+1) / 2; ++i) {
int tmp = heap[i];
heap[i] = heap[n-i];
heap[n-i] = tmp;
}
System.out.println("flip(0.." + n + "): " + toString());
}
public int[] minmax(int n) {
int xm, xM;
xm = xM = heap[0];
int posm = 0, posM = 0;
for (int i = 1; i < n; ++i) {
if (heap[i] < xm) {
xm = heap[i];
posm = i;
}
else if (heap[i] > xM) {
xM = heap[i];
posM = i;
}
}
return new int[] {posm, posM};
}
public void sort(int n, int dir) {
if (n == 0) return;
int[] mM = minmax(n);
int bestXPos = mM[dir];
int altXPos = mM[1-dir];
boolean flipped = false;
if (bestXPos == n-1) {
--n;
}
else if (bestXPos == 0) {
flip(n-1);
--n;
}
else if (altXPos == n-1) {
dir = 1-dir;
--n;
flipped = true;
}
else {
flip(bestXPos);
}
sort(n, dir);
if (flipped) {
flip(n);
}
}
PancakeSort(int[] numbers) {
heap = numbers;
sort(numbers.length, 1);
}
public static void main(String[] args) {
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; ++i)
numbers[i] = Integer.valueOf(args[i]);
PancakeSort pancakes = new PancakeSort(numbers);
System.out.println(pancakes);
}
}
|
Write the same code in Java as shown below in Python. | tutor = False
def pancakesort(data):
if len(data) <= 1:
return data
if tutor: print()
for size in range(len(data), 1, -1):
maxindex = max(range(size), key=data.__getitem__)
if maxindex+1 != size:
if maxindex != 0:
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), maxindex+1 ))
data[:maxindex+1] = reversed(data[:maxindex+1])
if tutor: print('With: %r doflip %i'
% ( ' '.join(str(x) for x in data), size ))
data[:size] = reversed(data[:size])
if tutor: print()
| public class PancakeSort
{
int[] heap;
public String toString() {
String info = "";
for (int x: heap)
info += x + " ";
return info;
}
public void flip(int n) {
for (int i = 0; i < (n+1) / 2; ++i) {
int tmp = heap[i];
heap[i] = heap[n-i];
heap[n-i] = tmp;
}
System.out.println("flip(0.." + n + "): " + toString());
}
public int[] minmax(int n) {
int xm, xM;
xm = xM = heap[0];
int posm = 0, posM = 0;
for (int i = 1; i < n; ++i) {
if (heap[i] < xm) {
xm = heap[i];
posm = i;
}
else if (heap[i] > xM) {
xM = heap[i];
posM = i;
}
}
return new int[] {posm, posM};
}
public void sort(int n, int dir) {
if (n == 0) return;
int[] mM = minmax(n);
int bestXPos = mM[dir];
int altXPos = mM[1-dir];
boolean flipped = false;
if (bestXPos == n-1) {
--n;
}
else if (bestXPos == 0) {
flip(n-1);
--n;
}
else if (altXPos == n-1) {
dir = 1-dir;
--n;
flipped = true;
}
else {
flip(bestXPos);
}
sort(n, dir);
if (flipped) {
flip(n);
}
}
PancakeSort(int[] numbers) {
heap = numbers;
sort(numbers.length, 1);
}
public static void main(String[] args) {
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; ++i)
numbers[i] = Integer.valueOf(args[i]);
PancakeSort pancakes = new PancakeSort(numbers);
System.out.println(pancakes);
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | assert 1.008 == molar_mass('H')
assert 2.016 == molar_mass('H2')
assert 18.015 == molar_mass('H2O')
assert 34.014 == molar_mass('H2O2')
assert 34.014 == molar_mass('(HO)2')
assert 142.036 == molar_mass('Na2SO4')
assert 84.162 == molar_mass('C6H12')
assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')
assert 176.124 == molar_mass('C6H4O2(OH)4')
assert 386.664 == molar_mass('C27H46O')
assert 315 == molar_mass('Uue')
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class ChemicalCalculator {
private static final Map<String, Double> atomicMass = new HashMap<>();
static {
atomicMass.put("H", 1.008);
atomicMass.put("He", 4.002602);
atomicMass.put("Li", 6.94);
atomicMass.put("Be", 9.0121831);
atomicMass.put("B", 10.81);
atomicMass.put("C", 12.011);
atomicMass.put("N", 14.007);
atomicMass.put("O", 15.999);
atomicMass.put("F", 18.998403163);
atomicMass.put("Ne", 20.1797);
atomicMass.put("Na", 22.98976928);
atomicMass.put("Mg", 24.305);
atomicMass.put("Al", 26.9815385);
atomicMass.put("Si", 28.085);
atomicMass.put("P", 30.973761998);
atomicMass.put("S", 32.06);
atomicMass.put("Cl", 35.45);
atomicMass.put("Ar", 39.948);
atomicMass.put("K", 39.0983);
atomicMass.put("Ca", 40.078);
atomicMass.put("Sc", 44.955908);
atomicMass.put("Ti", 47.867);
atomicMass.put("V", 50.9415);
atomicMass.put("Cr", 51.9961);
atomicMass.put("Mn", 54.938044);
atomicMass.put("Fe", 55.845);
atomicMass.put("Co", 58.933194);
atomicMass.put("Ni", 58.6934);
atomicMass.put("Cu", 63.546);
atomicMass.put("Zn", 65.38);
atomicMass.put("Ga", 69.723);
atomicMass.put("Ge", 72.630);
atomicMass.put("As", 74.921595);
atomicMass.put("Se", 78.971);
atomicMass.put("Br", 79.904);
atomicMass.put("Kr", 83.798);
atomicMass.put("Rb", 85.4678);
atomicMass.put("Sr", 87.62);
atomicMass.put("Y", 88.90584);
atomicMass.put("Zr", 91.224);
atomicMass.put("Nb", 92.90637);
atomicMass.put("Mo", 95.95);
atomicMass.put("Ru", 101.07);
atomicMass.put("Rh", 102.90550);
atomicMass.put("Pd", 106.42);
atomicMass.put("Ag", 107.8682);
atomicMass.put("Cd", 112.414);
atomicMass.put("In", 114.818);
atomicMass.put("Sn", 118.710);
atomicMass.put("Sb", 121.760);
atomicMass.put("Te", 127.60);
atomicMass.put("I", 126.90447);
atomicMass.put("Xe", 131.293);
atomicMass.put("Cs", 132.90545196);
atomicMass.put("Ba", 137.327);
atomicMass.put("La", 138.90547);
atomicMass.put("Ce", 140.116);
atomicMass.put("Pr", 140.90766);
atomicMass.put("Nd", 144.242);
atomicMass.put("Pm", 145.0);
atomicMass.put("Sm", 150.36);
atomicMass.put("Eu", 151.964);
atomicMass.put("Gd", 157.25);
atomicMass.put("Tb", 158.92535);
atomicMass.put("Dy", 162.500);
atomicMass.put("Ho", 164.93033);
atomicMass.put("Er", 167.259);
atomicMass.put("Tm", 168.93422);
atomicMass.put("Yb", 173.054);
atomicMass.put("Lu", 174.9668);
atomicMass.put("Hf", 178.49);
atomicMass.put("Ta", 180.94788);
atomicMass.put("W", 183.84);
atomicMass.put("Re", 186.207);
atomicMass.put("Os", 190.23);
atomicMass.put("Ir", 192.217);
atomicMass.put("Pt", 195.084);
atomicMass.put("Au", 196.966569);
atomicMass.put("Hg", 200.592);
atomicMass.put("Tl", 204.38);
atomicMass.put("Pb", 207.2);
atomicMass.put("Bi", 208.98040);
atomicMass.put("Po", 209.0);
atomicMass.put("At", 210.0);
atomicMass.put("Rn", 222.0);
atomicMass.put("Fr", 223.0);
atomicMass.put("Ra", 226.0);
atomicMass.put("Ac", 227.0);
atomicMass.put("Th", 232.0377);
atomicMass.put("Pa", 231.03588);
atomicMass.put("U", 238.02891);
atomicMass.put("Np", 237.0);
atomicMass.put("Pu", 244.0);
atomicMass.put("Am", 243.0);
atomicMass.put("Cm", 247.0);
atomicMass.put("Bk", 247.0);
atomicMass.put("Cf", 251.0);
atomicMass.put("Es", 252.0);
atomicMass.put("Fm", 257.0);
atomicMass.put("Uue", 315.0);
atomicMass.put("Ubn", 299.0);
}
private static double evaluate(String s) {
String sym = s + "[";
double sum = 0.0;
StringBuilder symbol = new StringBuilder();
String number = "";
for (int i = 0; i < sym.length(); ++i) {
char c = sym.charAt(i);
if ('@' <= c && c <= '[') {
int n = 1;
if (!number.isEmpty()) {
n = Integer.parseInt(number);
}
if (symbol.length() > 0) {
sum += atomicMass.getOrDefault(symbol.toString(), 0.0) * n;
}
if (c == '[') {
break;
}
symbol = new StringBuilder(String.valueOf(c));
number = "";
} else if ('a' <= c && c <= 'z') {
symbol.append(c);
} else if ('0' <= c && c <= '9') {
number += c;
} else {
throw new RuntimeException("Unexpected symbol " + c + " in molecule");
}
}
return sum;
}
private static String replaceParens(String s) {
char letter = 'a';
String si = s;
while (true) {
int start = si.indexOf('(');
if (start == -1) {
break;
}
for (int i = start + 1; i < si.length(); ++i) {
if (si.charAt(i) == ')') {
String expr = si.substring(start + 1, i);
String symbol = "@" + letter;
String pattern = Pattern.quote(si.substring(start, i + 1));
si = si.replaceFirst(pattern, symbol);
atomicMass.put(symbol, evaluate(expr));
letter++;
break;
}
if (si.charAt(i) == '(') {
start = i;
}
}
}
return si;
}
public static void main(String[] args) {
List<String> molecules = List.of(
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
);
for (String molecule : molecules) {
double mass = evaluate(replaceParens(molecule));
System.out.printf("%17s -> %7.3f\n", molecule, mass);
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
| import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
public class LdapConnectionDemo {
public static void main(String[] args) throws LdapException, IOException {
try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
connection.bind();
connection.unBind();
}
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | from operator import itemgetter
DEBUG = False
def spermutations(n):
sign = 1
p = [[i, 0 if i == 0 else -1]
for i in range(n)]
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p):
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),
key=itemgetter(1))
sign *= -1
if d1 == -1:
i2 = i1 - 1
p[i1], p[i2] = p[i2], p[i1]
if i2 == 0 or p[i2 - 1][0] > n1:
p[i2][1] = 0
elif d1 == 1:
i2 = i1 + 1
p[i1], p[i2] = p[i2], p[i1]
if i2 == n - 1 or p[i2 + 1][0] > n1:
p[i2][1] = 0
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
for i3, pp in enumerate(p):
n3, d3 = pp
if n3 > n1:
pp[1] = 1 if i3 < i2 else -1
if DEBUG: print '
if __name__ == '__main__':
from itertools import permutations
for n in (3, 4):
print '\nPermutations and sign of %i items' % n
sp = set()
for i in spermutations(n):
sp.add(i[0])
print('Perm: %r Sign: %2i' % i)
p = set(permutations(range(n)))
assert sp == p, 'Two methods of generating permutations do not agree'
| package org.rosettacode.java;
import java.util.Arrays;
import java.util.stream.IntStream;
public class HeapsAlgorithm {
public static void main(String[] args) {
Object[] array = IntStream.range(0, 4)
.boxed()
.toArray();
HeapsAlgorithm algorithm = new HeapsAlgorithm();
algorithm.recursive(array);
System.out.println();
algorithm.loop(array);
}
void recursive(Object[] array) {
recursive(array, array.length, true);
}
void recursive(Object[] array, int n, boolean plus) {
if (n == 1) {
output(array, plus);
} else {
for (int i = 0; i < n; i++) {
recursive(array, n - 1, i == 0);
swap(array, n % 2 == 0 ? i : 0, n - 1);
}
}
}
void output(Object[] array, boolean plus) {
System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1"));
}
void swap(Object[] array, int a, int b) {
Object o = array[a];
array[a] = array[b];
array[b] = o;
}
void loop(Object[] array) {
loop(array, array.length);
}
void loop(Object[] array, int n) {
int[] c = new int[n];
output(array, true);
boolean plus = false;
for (int i = 0; i < n; ) {
if (c[i] < i) {
if (i % 2 == 0) {
swap(array, 0, i);
} else {
swap(array, c[i], i);
}
output(array, plus);
plus = !plus;
c[i]++;
i = 0;
} else {
c[i] = 0;
i++;
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
r[d] = True
s1 += s2
s2 += 2
return [i for i, val in enumerate(r) if not val and i]
if __name__ == '__main__':
n = 2200
print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
| import java.util.ArrayList;
import java.util.List;
public class PythagoreanQuadruples {
public static void main(String[] args) {
long d = 2200;
System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d));
}
private static List<Long> getPythagoreanQuadruples(long max) {
List<Long> list = new ArrayList<>();
long n = -1;
long m = -1;
while ( true ) {
long nTest = (long) Math.pow(2, n+1);
long mTest = (long) (5L * Math.pow(2, m+1));
long test = 0;
if ( nTest > mTest ) {
test = mTest;
m++;
}
else {
test = nTest;
n++;
}
if ( test < max ) {
list.add(test);
}
else {
break;
}
}
return list;
}
}
|
Write the same algorithm in Java as shown in this Python implementation. |
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.disabled_prefix = disabled_prefix
def __str__(self):
disabled = ('', '%s ' % self.disabled_prefix)[self.disabled]
value = (' %s' % self.value, '')[self.value is None]
return ''.join((disabled, self.name, value))
def get(self):
enabled = not bool(self.disabled)
if self.value is None:
value = enabled
else:
value = enabled and self.value
return value
class Config(object):
reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'
def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):
self.disabled_prefix = disabled_prefix
self.contents = []
self.options = {}
self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix)
if fname:
self.parse_file(fname)
def __str__(self):
return '\n'.join(map(str, self.contents))
def parse_file(self, fname):
with open(fname) as f:
self.parse_lines(f)
return self
def parse_lines(self, lines):
for line in lines:
self.parse_line(line)
return self
def parse_line(self, line):
s = ''.join(c for c in line.strip() if c in string.printable)
moOPTION = self.creOPTION.match(s)
if moOPTION:
name = moOPTION.group('name').upper()
if not name in self.options:
self.add_option(name, moOPTION.group('value'),
moOPTION.group('disabled'))
else:
if not s.startswith(self.disabled_prefix):
self.contents.append(line.rstrip())
return self
def add_option(self, name, value=None, disabled=False):
name = name.upper()
opt = Option(name, value, disabled)
self.options[name] = opt
self.contents.append(opt)
return opt
def set_option(self, name, value=None, disabled=False):
name = name.upper()
opt = self.options.get(name)
if opt:
opt.value = value
opt.disabled = disabled
else:
opt = self.add_option(name, value, disabled)
return opt
def enable_option(self, name, value=None):
return self.set_option(name, value, False)
def disable_option(self, name, value=None):
return self.set_option(name, value, True)
def get_option(self, name):
opt = self.options.get(name.upper())
value = opt.get() if opt else None
return value
if __name__ == '__main__':
import sys
cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)
cfg.disable_option('needspeeling')
cfg.enable_option('seedsremoved')
cfg.enable_option('numberofbananas', 1024)
cfg.enable_option('numberofstrawberries', 62000)
print cfg
| import java.io.*;
import java.util.*;
import java.util.regex.*;
public class UpdateConfig {
public static void main(String[] args) {
if (args[0] == null) {
System.out.println("filename required");
} else if (readConfig(args[0])) {
enableOption("seedsremoved");
disableOption("needspeeling");
setOption("numberofbananas", "1024");
addOption("numberofstrawberries", "62000");
store();
}
}
private enum EntryType {
EMPTY, ENABLED, DISABLED, COMMENT
}
private static class Entry {
EntryType type;
String name, value;
Entry(EntryType t, String n, String v) {
type = t;
name = n;
value = v;
}
}
private static Map<String, Entry> entries = new LinkedHashMap<>();
private static String path;
private static boolean readConfig(String p) {
path = p;
File f = new File(path);
if (!f.exists() || f.isDirectory())
return false;
String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)";
Pattern regex = Pattern.compile(regexString);
try (Scanner sc = new Scanner(new FileReader(f))){
int emptyLines = 0;
String line;
while (sc.hasNext()) {
line = sc.nextLine().trim();
if (line.isEmpty()) {
addOption("" + emptyLines++, null, EntryType.EMPTY);
} else if (line.charAt(0) == '#') {
entries.put(line, new Entry(EntryType.COMMENT, line, null));
} else {
line = line.replaceAll("[^a-zA-Z0-9\\x20;]", "");
Matcher m = regex.matcher(line);
if (m.find() && !m.group(2).isEmpty()) {
EntryType t = EntryType.ENABLED;
if (!m.group(1).isEmpty())
t = EntryType.DISABLED;
addOption(m.group(2), m.group(3), t);
}
}
}
} catch (IOException e) {
System.out.println(e);
}
return true;
}
private static void addOption(String name, String value) {
addOption(name, value, EntryType.ENABLED);
}
private static void addOption(String name, String value, EntryType t) {
name = name.toUpperCase();
entries.put(name, new Entry(t, name, value));
}
private static void enableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.ENABLED;
}
private static void disableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.DISABLED;
}
private static void setOption(String name, String value) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.value = value;
}
private static void store() {
try (PrintWriter pw = new PrintWriter(path)) {
for (Entry e : entries.values()) {
switch (e.type) {
case EMPTY:
pw.println();
break;
case ENABLED:
pw.format("%s %s%n", e.name, e.value);
break;
case DISABLED:
pw.format("; %s %s%n", e.name, e.value);
break;
case COMMENT:
pw.println(e.name);
break;
default:
break;
}
}
if (pw.checkError()) {
throw new IOException("writing to file failed");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. |
from PIL import Image, ImageFilter
if __name__=="__main__":
im = Image.open("test.jpg")
kernelValues = [-2,-1,0,-1,1,1,0,1,2]
kernel = ImageFilter.Kernel((3,3), kernelValues)
im2 = im.filter(kernel)
im2.show()
| import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.*;
public class ImageConvolution
{
public static class ArrayData
{
public final int[] dataArray;
public final int width;
public final int height;
public ArrayData(int width, int height)
{
this(new int[width * height], width, height);
}
public ArrayData(int[] dataArray, int width, int height)
{
this.dataArray = dataArray;
this.width = width;
this.height = height;
}
public int get(int x, int y)
{ return dataArray[y * width + x]; }
public void set(int x, int y, int value)
{ dataArray[y * width + x] = value; }
}
private static int bound(int value, int endIndex)
{
if (value < 0)
return 0;
if (value < endIndex)
return value;
return endIndex - 1;
}
public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor)
{
int inputWidth = inputData.width;
int inputHeight = inputData.height;
int kernelWidth = kernel.width;
int kernelHeight = kernel.height;
if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1))
throw new IllegalArgumentException("Kernel must have odd width");
if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1))
throw new IllegalArgumentException("Kernel must have odd height");
int kernelWidthRadius = kernelWidth >>> 1;
int kernelHeightRadius = kernelHeight >>> 1;
ArrayData outputData = new ArrayData(inputWidth, inputHeight);
for (int i = inputWidth - 1; i >= 0; i--)
{
for (int j = inputHeight - 1; j >= 0; j--)
{
double newValue = 0.0;
for (int kw = kernelWidth - 1; kw >= 0; kw--)
for (int kh = kernelHeight - 1; kh >= 0; kh--)
newValue += kernel.get(kw, kh) * inputData.get(
bound(i + kw - kernelWidthRadius, inputWidth),
bound(j + kh - kernelHeightRadius, inputHeight));
outputData.set(i, j, (int)Math.round(newValue / kernelDivisor));
}
}
return outputData;
}
public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException
{
BufferedImage inputImage = ImageIO.read(new File(filename));
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
ArrayData reds = new ArrayData(width, height);
ArrayData greens = new ArrayData(width, height);
ArrayData blues = new ArrayData(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgbValue = rgbData[y * width + x];
reds.set(x, y, (rgbValue >>> 16) & 0xFF);
greens.set(x, y, (rgbValue >>> 8) & 0xFF);
blues.set(x, y, rgbValue & 0xFF);
}
}
return new ArrayData[] { reds, greens, blues };
}
public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException
{
ArrayData reds = redGreenBlue[0];
ArrayData greens = redGreenBlue[1];
ArrayData blues = redGreenBlue[2];
BufferedImage outputImage = new BufferedImage(reds.width, reds.height,
BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < reds.height; y++)
{
for (int x = 0; x < reds.width; x++)
{
int red = bound(reds.get(x, y), 256);
int green = bound(greens.get(x, y), 256);
int blue = bound(blues.get(x, y), 256);
outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000);
}
}
ImageIO.write(outputImage, "PNG", new File(filename));
return;
}
public static void main(String[] args) throws IOException
{
int kernelWidth = Integer.parseInt(args[2]);
int kernelHeight = Integer.parseInt(args[3]);
int kernelDivisor = Integer.parseInt(args[4]);
System.out.println("Kernel size: " + kernelWidth + "x" + kernelHeight +
", divisor=" + kernelDivisor);
int y = 5;
ArrayData kernel = new ArrayData(kernelWidth, kernelHeight);
for (int i = 0; i < kernelHeight; i++)
{
System.out.print("[");
for (int j = 0; j < kernelWidth; j++)
{
kernel.set(j, i, Integer.parseInt(args[y++]));
System.out.print(" " + kernel.get(j, i) + " ");
}
System.out.println("]");
}
ArrayData[] dataArrays = getArrayDatasFromImage(args[0]);
for (int i = 0; i < dataArrays.length; i++)
dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor);
writeOutputImage(args[1], dataArrays);
return;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | from itertools import product
def gen_dict(n_faces, n_dice):
counts = [0] * ((n_faces + 1) * n_dice)
for t in product(range(1, n_faces + 1), repeat=n_dice):
counts[sum(t)] += 1
return counts, n_faces ** n_dice
def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
c1, p1 = gen_dict(n_sides1, n_dice1)
c2, p2 = gen_dict(n_sides2, n_dice2)
p12 = float(p1 * p2)
return sum(p[1] * q[1] / p12
for p, q in product(enumerate(c1), enumerate(c2))
if p[0] > q[0])
print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6)
| import java.util.Random;
public class Dice{
private static int roll(int nDice, int nSides){
int sum = 0;
Random rand = new Random();
for(int i = 0; i < nDice; i++){
sum += rand.nextInt(nSides) + 1;
}
return sum;
}
private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){
int p1Wins = 0;
for(int i = 0; i < rolls; i++){
int p1Roll = roll(p1Dice, p1Sides);
int p2Roll = roll(p2Dice, p2Sides);
if(p1Roll > p2Roll) p1Wins++;
}
return p1Wins;
}
public static void main(String[] args){
int p1Dice = 9; int p1Sides = 4;
int p2Dice = 6; int p2Sides = 6;
int rolls = 10000;
int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 10000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 9; p1Sides = 4;
p2Dice = 6; p2Sides = 6;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | from array import array
from collections import deque
import psyco
data = []
nrows = 0
px = py = 0
sdata = ""
ddata = ""
def init(board):
global data, nrows, sdata, ddata, px, py
data = filter(None, board.splitlines())
nrows = max(len(r) for r in data)
maps = {' ':' ', '.': '.', '@':' ', '
mapd = {' ':' ', '.': ' ', '@':'@', '
for r, row in enumerate(data):
for c, ch in enumerate(row):
sdata += maps[ch]
ddata += mapd[ch]
if ch == '@':
px = c
py = r
def push(x, y, dx, dy, data):
if sdata[(y+2*dy) * nrows + x+2*dx] == '
data[(y+2*dy) * nrows + x+2*dx] != ' ':
return None
data2 = array("c", data)
data2[y * nrows + x] = ' '
data2[(y+dy) * nrows + x+dx] = '@'
data2[(y+2*dy) * nrows + x+2*dx] = '*'
return data2.tostring()
def is_solved(data):
for i in xrange(len(data)):
if (sdata[i] == '.') != (data[i] == '*'):
return False
return True
def solve():
open = deque([(ddata, "", px, py)])
visited = set([ddata])
dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),
(0, 1, 'd', 'D'), (-1, 0, 'l', 'L'))
lnrows = nrows
while open:
cur, csol, x, y = open.popleft()
for di in dirs:
temp = cur
dx, dy = di[0], di[1]
if temp[(y+dy) * lnrows + x+dx] == '*':
temp = push(x, y, dx, dy, temp)
if temp and temp not in visited:
if is_solved(temp):
return csol + di[3]
open.append((temp, csol + di[3], x+dx, y+dy))
visited.add(temp)
else:
if sdata[(y+dy) * lnrows + x+dx] == '
temp[(y+dy) * lnrows + x+dx] != ' ':
continue
data2 = array("c", temp)
data2[y * lnrows + x] = ' '
data2[(y+dy) * lnrows + x+dx] = '@'
temp = data2.tostring()
if temp not in visited:
if is_solved(temp):
return csol + di[2]
open.append((temp, csol + di[2], x+dx, y+dy))
visited.add(temp)
return "No solution"
level = """\
psyco.full()
init(level)
print level, "\n\n", solve()
| import java.util.*;
public class Sokoban {
String destBoard, currBoard;
int playerX, playerY, nCols;
Sokoban(String[] board) {
nCols = board[0].length();
StringBuilder destBuf = new StringBuilder();
StringBuilder currBuf = new StringBuilder();
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < nCols; c++) {
char ch = board[r].charAt(c);
destBuf.append(ch != '$' && ch != '@' ? ch : ' ');
currBuf.append(ch != '.' ? ch : ' ');
if (ch == '@') {
this.playerX = c;
this.playerY = r;
}
}
}
destBoard = destBuf.toString();
currBoard = currBuf.toString();
}
String move(int x, int y, int dx, int dy, String trialBoard) {
int newPlayerPos = (y + dy) * nCols + x + dx;
if (trialBoard.charAt(newPlayerPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[newPlayerPos] = '@';
return new String(trial);
}
String push(int x, int y, int dx, int dy, String trialBoard) {
int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;
if (trialBoard.charAt(newBoxPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[(y + dy) * nCols + x + dx] = '@';
trial[newBoxPos] = '$';
return new String(trial);
}
boolean isSolved(String trialBoard) {
for (int i = 0; i < trialBoard.length(); i++)
if ((destBoard.charAt(i) == '.')
!= (trialBoard.charAt(i) == '$'))
return false;
return true;
}
String solve() {
class Board {
String cur, sol;
int x, y;
Board(String s1, String s2, int px, int py) {
cur = s1;
sol = s2;
x = px;
y = py;
}
}
char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};
int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
Set<String> history = new HashSet<>();
LinkedList<Board> open = new LinkedList<>();
history.add(currBoard);
open.add(new Board(currBoard, "", playerX, playerY));
while (!open.isEmpty()) {
Board item = open.poll();
String cur = item.cur;
String sol = item.sol;
int x = item.x;
int y = item.y;
for (int i = 0; i < dirs.length; i++) {
String trial = cur;
int dx = dirs[i][0];
int dy = dirs[i][1];
if (trial.charAt((y + dy) * nCols + x + dx) == '$') {
if ((trial = push(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][1];
if (isSolved(trial))
return newSol;
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
} else if ((trial = move(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][0];
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
}
}
return "No solution";
}
public static void main(String[] a) {
String level = "#######,# #,# #,#. # #,#. $$ #,"
+ "#.$$ #,#.# @#,#######";
System.out.println(new Sokoban(level.split(",")).solve());
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from itertools import chain, cycle, accumulate, combinations
from typing import List, Tuple
def factors5(n: int) -> List[int]:
def prime_powers(n):
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d + (p,)
yield(d)
if n > 1: yield((n,))
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r[:-1]
def powerset(s: List[int]) -> List[Tuple[int, ...]]:
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1))
def is_practical(x: int) -> bool:
if x == 1:
return True
if x %2:
return False
f = factors5(x)
ps = powerset(f)
found = {y for y in {sum(i) for i in ps}
if 1 <= y < x}
return len(found) == x - 1
if __name__ == '__main__':
n = 333
p = [x for x in range(1, n + 1) if is_practical(x)]
print(f"There are {len(p)} Practical numbers from 1 to {n}:")
print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1])
x = 666
print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
| import java.util.*;
public class PracticalNumbers {
public static void main(String[] args) {
final int from = 1;
final int to = 333;
List<Integer> practical = new ArrayList<>();
for (int i = from; i <= to; ++i) {
if (isPractical(i))
practical.add(i);
}
System.out.printf("Found %d practical numbers between %d and %d:\n%s\n",
practical.size(), from, to, shorten(practical, 10));
printPractical(666);
printPractical(6666);
printPractical(66666);
printPractical(672);
printPractical(720);
printPractical(222222);
}
private static void printPractical(int n) {
if (isPractical(n))
System.out.printf("%d is a practical number.\n", n);
else
System.out.printf("%d is not a practical number.\n", n);
}
private static boolean isPractical(int n) {
int[] divisors = properDivisors(n);
for (int i = 1; i < n; ++i) {
if (!sumOfAnySubset(i, divisors, divisors.length))
return false;
}
return true;
}
private static boolean sumOfAnySubset(int n, int[] f, int len) {
if (len == 0)
return false;
int total = 0;
for (int i = 0; i < len; ++i) {
if (n == f[i])
return true;
total += f[i];
}
if (n == total)
return true;
if (n > total)
return false;
--len;
int d = n - f[len];
return (d > 0 && sumOfAnySubset(d, f, len)) || sumOfAnySubset(n, f, len);
}
private static int[] properDivisors(int n) {
List<Integer> divisors = new ArrayList<>();
divisors.add(1);
for (int i = 2;; ++i) {
int i2 = i * i;
if (i2 > n)
break;
if (n % i == 0) {
divisors.add(i);
if (i2 != n)
divisors.add(n / i);
}
}
int[] result = new int[divisors.size()];
for (int i = 0; i < result.length; ++i)
result[i] = divisors.get(i);
Arrays.sort(result);
return result;
}
private static String shorten(List<Integer> list, int n) {
StringBuilder str = new StringBuilder();
int len = list.size(), i = 0;
if (n > 0 && len > 0)
str.append(list.get(i++));
for (; i < n && i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
if (len > i + n) {
if (n > 0)
str.append(", ...");
i = len - n;
}
for (; i < len; ++i) {
str.append(", ");
str.append(list.get(i));
}
return str.toString();
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | 2.3
.3
.3e4
.3e+34
.3e-34
2.e34
| 1.
1.0
2432311.7567374
1.234E-10
1.234e-10
758832d
728832f
1.0f
758832D
728832F
1.0F
1 / 2.
1 / 2
|
Keep all operations the same but rewrite the snippet in Java. | 2.3
.3
.3e4
.3e+34
.3e-34
2.e34
| 1.
1.0
2432311.7567374
1.234E-10
1.234e-10
758832d
728832f
1.0f
758832D
728832F
1.0F
1 / 2.
1 / 2
|
Ensure the translated Java code behaves exactly like the original Python snippet. | from sys import stdout
neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]
exists = []
lastNumber = 0
wid = 0
hei = 0
def find_next(pa, x, y, z):
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == z:
return a, b
return -1, -1
def find_solution(pa, x, y, z):
if z > lastNumber:
return 1
if exists[z] == 1:
s = find_next(pa, x, y, z)
if s[0] < 0:
return 0
return find_solution(pa, s[0], s[1], z + 1)
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == 0:
pa[a][b] = z
r = find_solution(pa, a, b, z + 1)
if r == 1:
return 1
pa[a][b] = 0
return 0
def solve(pz, w, h):
global lastNumber, wid, hei, exists
lastNumber = w * h
wid = w
hei = h
exists = [0 for j in range(lastNumber + 1)]
pa = [[0 for j in range(h)] for i in range(w)]
st = pz.split()
idx = 0
for j in range(h):
for i in range(w):
if st[idx] == ".":
idx += 1
else:
pa[i][j] = int(st[idx])
exists[pa[i][j]] = 1
idx += 1
x = 0
y = 0
t = w * h + 1
for j in range(h):
for i in range(w):
if pa[i][j] != 0 and pa[i][j] < t:
t = pa[i][j]
x = i
y = j
return find_solution(pa, x, y, t + 1), pa
def show_result(r):
if r[0] == 1:
for j in range(hei):
for i in range(wid):
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No Solution!\n")
print()
r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17"
" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9)
show_result(r)
r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37"
" . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9)
show_result(r)
r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55"
" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9)
show_result(r)
| import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | from sys import stdout
neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]
exists = []
lastNumber = 0
wid = 0
hei = 0
def find_next(pa, x, y, z):
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == z:
return a, b
return -1, -1
def find_solution(pa, x, y, z):
if z > lastNumber:
return 1
if exists[z] == 1:
s = find_next(pa, x, y, z)
if s[0] < 0:
return 0
return find_solution(pa, s[0], s[1], z + 1)
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == 0:
pa[a][b] = z
r = find_solution(pa, a, b, z + 1)
if r == 1:
return 1
pa[a][b] = 0
return 0
def solve(pz, w, h):
global lastNumber, wid, hei, exists
lastNumber = w * h
wid = w
hei = h
exists = [0 for j in range(lastNumber + 1)]
pa = [[0 for j in range(h)] for i in range(w)]
st = pz.split()
idx = 0
for j in range(h):
for i in range(w):
if st[idx] == ".":
idx += 1
else:
pa[i][j] = int(st[idx])
exists[pa[i][j]] = 1
idx += 1
x = 0
y = 0
t = w * h + 1
for j in range(h):
for i in range(w):
if pa[i][j] != 0 and pa[i][j] < t:
t = pa[i][j]
x = i
y = j
return find_solution(pa, x, y, t + 1), pa
def show_result(r):
if r[0] == 1:
for j in range(hei):
for i in range(wid):
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No Solution!\n")
print()
r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17"
" . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9)
show_result(r)
r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37"
" . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9)
show_result(r)
r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55"
" . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9)
show_result(r)
| import java.util.*;
public class Numbrix {
final static String[] board = {
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"};
final static int[][] moves = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static int[][] grid;
static int[] clues;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 2;
int nCols = board[0].split(",").length + 2;
int startRow = 0, startCol = 0;
grid = new int[nRows][nCols];
totalToFill = (nRows - 2) * (nCols - 2);
List<Integer> lst = new ArrayList<>();
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
if (r >= 1 && r < nRows - 1) {
String[] row = board[r - 1].split(",");
for (int c = 1; c < nCols - 1; c++) {
int val = Integer.parseInt(row[c - 1]);
if (val > 0)
lst.add(val);
if (val == 1) {
startRow = r;
startCol = c;
}
grid[r][c] = val;
}
}
}
clues = lst.stream().sorted().mapToInt(i -> i).toArray();
if (solve(startRow, startCol, 1, 0))
printResult();
}
static boolean solve(int r, int c, int count, int nextClue) {
if (count > totalToFill)
return true;
if (grid[r][c] != 0 && grid[r][c] != count)
return false;
if (grid[r][c] == 0 && nextClue < clues.length)
if (clues[nextClue] == count)
return false;
int back = grid[r][c];
if (back == count)
nextClue++;
grid[r][c] = count;
for (int[] move : moves)
if (solve(r + move[1], c + move[0], count + 1, nextClue))
return true;
grid[r][c] = back;
return false;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
continue;
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
| package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four)));
System.out.println("4+3=" + toInt(plus(four).apply(three)));
System.out.println("3*4=" + toInt(mult(three).apply(four)));
System.out.println("4*3=" + toInt(mult(four).apply(three)));
System.out.println("3^4=" + toInt(pow(four).apply(three)));
System.out.println("4^3=" + toInt(pow(three).apply(four)));
System.out.println(" 8=" + toInt(toChurchNum(8)));
}
}
|
Produce a functionally identical Java code for the snippet given in Python. |
from itertools import repeat
from functools import reduce
def churchZero():
return lambda f: identity
def churchSucc(cn):
return lambda f: compose(f)(cn(f))
def churchAdd(m):
return lambda n: lambda f: compose(m(f))(n(f))
def churchMult(m):
return lambda n: compose(m)(n)
def churchExp(m):
return lambda n: n(m)
def churchFromInt(n):
return lambda f: (
foldl
(compose)
(identity)
(replicate(n)(f))
)
def churchFromInt_(n):
if 0 == n:
return churchZero()
else:
return churchSucc(churchFromInt(n - 1))
def intFromChurch(cn):
return cn(succ)(0)
def main():
'Tests'
cThree = churchFromInt(3)
cFour = churchFromInt(4)
print(list(map(intFromChurch, [
churchAdd(cThree)(cFour),
churchMult(cThree)(cFour),
churchExp(cFour)(cThree),
churchExp(cThree)(cFour),
])))
def compose(f):
return lambda g: lambda x: g(f(x))
def foldl(f):
def go(acc, xs):
return reduce(lambda a, x: f(a)(x), xs, acc)
return lambda acc: lambda xs: go(acc, xs)
def identity(x):
return x
def replicate(n):
return lambda x: repeat(x, n)
def succ(x):
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
if __name__ == '__main__':
main()
| package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four)));
System.out.println("4+3=" + toInt(plus(four).apply(three)));
System.out.println("3*4=" + toInt(mult(three).apply(four)));
System.out.println("4*3=" + toInt(mult(four).apply(three)));
System.out.println("3^4=" + toInt(pow(four).apply(three)));
System.out.println("4^3=" + toInt(pow(three).apply(four)));
System.out.println(" 8=" + toInt(toChurchNum(8)));
}
}
|
Write the same code in Java as shown below in Python. | from sys import stdout
neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0
def is_valid(a, b):
return -1 < a < pWid and -1 < b < pHei
def iterate(pa, x, y, v):
if v > cnt:
return 1
for i in range(len(neighbours)):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if is_valid(a, b) and pa[a][b] == 0:
pa[a][b] = v
r = iterate(pa, a, b, v + 1)
if r == 1:
return r
pa[a][b] = 0
return 0
def solve(pz, w, h):
global cnt, pWid, pHei
pa = [[-1 for j in range(h)] for i in range(w)]
f = 0
pWid = w
pHei = h
for j in range(h):
for i in range(w):
if pz[f] == "1":
pa[i][j] = 0
cnt += 1
f += 1
for y in range(h):
for x in range(w):
if pa[x][y] == 0:
pa[x][y] = 1
if 1 == iterate(pa, x, y, 2):
return 1, pa
pa[x][y] = 0
return 0, pa
r = solve("011011011111111111111011111000111000001000", 7, 6)
if r[0] == 1:
for j in range(6):
for i in range(7):
if r[1][i][j] == -1:
stdout.write(" ")
else:
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No solution!")
| import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | from sys import stdout
neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0
def is_valid(a, b):
return -1 < a < pWid and -1 < b < pHei
def iterate(pa, x, y, v):
if v > cnt:
return 1
for i in range(len(neighbours)):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if is_valid(a, b) and pa[a][b] == 0:
pa[a][b] = v
r = iterate(pa, a, b, v + 1)
if r == 1:
return r
pa[a][b] = 0
return 0
def solve(pz, w, h):
global cnt, pWid, pHei
pa = [[-1 for j in range(h)] for i in range(w)]
f = 0
pWid = w
pHei = h
for j in range(h):
for i in range(w):
if pz[f] == "1":
pa[i][j] = 0
cnt += 1
f += 1
for y in range(h):
for x in range(w):
if pa[x][y] == 0:
pa[x][y] = 1
if 1 == iterate(pa, x, y, 2):
return 1, pa
pa[x][y] = 0
return 0, pa
r = solve("011011011111111111111011111000111000001000", 7, 6)
if r[0] == 1:
for j in range(6):
for i in range(7):
if r[1][i][j] == -1:
stdout.write(" ")
else:
stdout.write(" {:0{}d}".format(r[1][i][j], 2))
print()
else:
stdout.write("No solution!")
| import java.util.*;
public class Hopido {
final static String[] board = {
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."};
final static int[][] moves = {{-3, 0}, {0, 3}, {3, 0}, {0, -3},
{2, 2}, {2, -2}, {-2, 2}, {-2, -2}};
static int[][] grid;
static int totalToFill;
public static void main(String[] args) {
int nRows = board.length + 6;
int nCols = board[0].length() + 6;
grid = new int[nRows][nCols];
for (int r = 0; r < nRows; r++) {
Arrays.fill(grid[r], -1);
for (int c = 3; c < nCols - 3; c++)
if (r >= 3 && r < nRows - 3) {
if (board[r - 3].charAt(c - 3) == '0') {
grid[r][c] = 0;
totalToFill++;
}
}
}
int pos = -1, r, c;
do {
do {
pos++;
r = pos / nCols;
c = pos % nCols;
} while (grid[r][c] == -1);
grid[r][c] = 1;
if (solve(r, c, 2))
break;
grid[r][c] = 0;
} while (pos < nRows * nCols);
printResult();
}
static boolean solve(int r, int c, int count) {
if (count > totalToFill)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != totalToFill)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Please provide an equivalent version of this Python code in Java. | from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
for x in m:
print " ".join("x
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique"
else:
print "Solution may not be unique, doing exhaustive search:"
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main()
| import java.util.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.toList;
public class NonogramSolver {
static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"};
static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE "
+ "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"};
static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH "
+ "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF "
+ "AAAAD BDG CEF CBDB BBB FC"};
static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q "
+ "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ "
+ "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"};
public static void main(String[] args) {
for (String[] puzzleData : new String[][]{p1, p2, p3, p4})
newPuzzle(puzzleData);
}
static void newPuzzle(String[] data) {
String[] rowData = data[0].split("\\s");
String[] colData = data[1].split("\\s");
List<List<BitSet>> cols, rows;
rows = getCandidates(rowData, colData.length);
cols = getCandidates(colData, rowData.length);
int numChanged;
do {
numChanged = reduceMutual(cols, rows);
if (numChanged == -1) {
System.out.println("No solution");
return;
}
} while (numChanged > 0);
for (List<BitSet> row : rows) {
for (int i = 0; i < cols.size(); i++)
System.out.print(row.get(0).get(i) ? "# " : ". ");
System.out.println();
}
System.out.println();
}
static List<List<BitSet>> getCandidates(String[] data, int len) {
List<List<BitSet>> result = new ArrayList<>();
for (String s : data) {
List<BitSet> lst = new LinkedList<>();
int sumChars = s.chars().map(c -> c - 'A' + 1).sum();
List<String> prep = stream(s.split(""))
.map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList());
for (String r : genSequence(prep, len - sumChars + 1)) {
char[] bits = r.substring(1).toCharArray();
BitSet bitset = new BitSet(bits.length);
for (int i = 0; i < bits.length; i++)
bitset.set(i, bits[i] == '1');
lst.add(bitset);
}
result.add(lst);
}
return result;
}
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {
int countRemoved1 = reduce(cols, rows);
if (countRemoved1 == -1)
return -1;
int countRemoved2 = reduce(rows, cols);
if (countRemoved2 == -1)
return -1;
return countRemoved1 + countRemoved2;
}
static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {
int countRemoved = 0;
for (int i = 0; i < a.size(); i++) {
BitSet commonOn = new BitSet();
commonOn.set(0, b.size());
BitSet commonOff = new BitSet();
for (BitSet candidate : a.get(i)) {
commonOn.and(candidate);
commonOff.or(candidate);
}
for (int j = 0; j < b.size(); j++) {
final int fi = i, fj = j;
if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))
|| (!commonOff.get(fj) && cnd.get(fi))))
countRemoved++;
if (b.get(j).isEmpty())
return -1;
}
}
return countRemoved;
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
for x in m:
print " ".join("x
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique"
else:
print "Solution may not be unique, doing exhaustive search:"
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main()
| import java.util.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.toList;
public class NonogramSolver {
static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"};
static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE "
+ "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"};
static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH "
+ "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF "
+ "AAAAD BDG CEF CBDB BBB FC"};
static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q "
+ "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ "
+ "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"};
public static void main(String[] args) {
for (String[] puzzleData : new String[][]{p1, p2, p3, p4})
newPuzzle(puzzleData);
}
static void newPuzzle(String[] data) {
String[] rowData = data[0].split("\\s");
String[] colData = data[1].split("\\s");
List<List<BitSet>> cols, rows;
rows = getCandidates(rowData, colData.length);
cols = getCandidates(colData, rowData.length);
int numChanged;
do {
numChanged = reduceMutual(cols, rows);
if (numChanged == -1) {
System.out.println("No solution");
return;
}
} while (numChanged > 0);
for (List<BitSet> row : rows) {
for (int i = 0; i < cols.size(); i++)
System.out.print(row.get(0).get(i) ? "# " : ". ");
System.out.println();
}
System.out.println();
}
static List<List<BitSet>> getCandidates(String[] data, int len) {
List<List<BitSet>> result = new ArrayList<>();
for (String s : data) {
List<BitSet> lst = new LinkedList<>();
int sumChars = s.chars().map(c -> c - 'A' + 1).sum();
List<String> prep = stream(s.split(""))
.map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList());
for (String r : genSequence(prep, len - sumChars + 1)) {
char[] bits = r.substring(1).toCharArray();
BitSet bitset = new BitSet(bits.length);
for (int i = 0; i < bits.length; i++)
bitset.set(i, bits[i] == '1');
lst.add(bitset);
}
result.add(lst);
}
return result;
}
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {
int countRemoved1 = reduce(cols, rows);
if (countRemoved1 == -1)
return -1;
int countRemoved2 = reduce(rows, cols);
if (countRemoved2 == -1)
return -1;
return countRemoved1 + countRemoved2;
}
static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {
int countRemoved = 0;
for (int i = 0; i < a.size(); i++) {
BitSet commonOn = new BitSet();
commonOn.set(0, b.size());
BitSet commonOff = new BitSet();
for (BitSet candidate : a.get(i)) {
commonOn.and(candidate);
commonOff.or(candidate);
}
for (int j = 0; j < b.size(); j++) {
final int fi = i, fj = j;
if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))
|| (!commonOff.get(fj) && cnd.get(fi))))
countRemoved++;
if (b.get(j).isEmpty())
return -1;
}
}
return countRemoved;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))]
def deduce(hr, vr):
def allowable(row):
return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row)
def fits(a, b):
return all(x & y for x, y in izip(a, b))
def fix_col(n):
c = [x[n] for x in can_do]
cols[n] = [x for x in cols[n] if fits(x, c)]
for i, x in enumerate(allowable(cols[n])):
if x != can_do[i][n]:
mod_rows.add(i)
can_do[i][n] &= x
def fix_row(n):
c = can_do[n]
rows[n] = [x for x in rows[n] if fits(x, c)]
for i, x in enumerate(allowable(rows[n])):
if x != can_do[n][i]:
mod_cols.add(i)
can_do[n][i] &= x
def show_gram(m):
for x in m:
print " ".join("x
print
w, h = len(vr), len(hr)
rows = [gen_row(w, x) for x in hr]
cols = [gen_row(h, x) for x in vr]
can_do = map(allowable, rows)
mod_rows, mod_cols = set(), set(xrange(w))
while mod_cols:
for i in mod_cols:
fix_col(i)
mod_cols = set()
for i in mod_rows:
fix_row(i)
mod_rows = set()
if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)):
print "Solution would be unique"
else:
print "Solution may not be unique, doing exhaustive search:"
out = [0] * h
def try_all(n = 0):
if n >= h:
for j in xrange(w):
if [x[j] for x in out] not in cols[j]:
return 0
show_gram(out)
return 1
sol = 0
for x in rows[n]:
out[n] = x
sol += try_all(n + 1)
return sol
n = try_all()
if not n:
print "No solution."
elif n == 1:
print "Unique solution."
else:
print n, "solutions."
print
def solve(p, show_runs=True):
s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()]
for l in p.splitlines()]
if show_runs:
print "Horizontal runs:", s[0]
print "Vertical runs:", s[1]
deduce(s[0], s[1])
def main():
fn = "nonogram_problems.txt"
for p in (x for x in open(fn).read().split("\n\n") if x):
solve(p)
print "Extra example not solvable by deduction alone:"
solve("B B A A\nB B A A")
print "Extra example where there is no solution:"
solve("B A A\nA A A")
main()
| import java.util.*;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.toList;
public class NonogramSolver {
static String[] p1 = {"C BA CB BB F AE F A B", "AB CA AE GA E C D C"};
static String[] p2 = {"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE "
+ "CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"};
static String[] p3 = {"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH "
+ "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF "
+ "AAAAD BDG CEF CBDB BBB FC"};
static String[] p4 = {"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q "
+ "R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ "
+ "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"};
public static void main(String[] args) {
for (String[] puzzleData : new String[][]{p1, p2, p3, p4})
newPuzzle(puzzleData);
}
static void newPuzzle(String[] data) {
String[] rowData = data[0].split("\\s");
String[] colData = data[1].split("\\s");
List<List<BitSet>> cols, rows;
rows = getCandidates(rowData, colData.length);
cols = getCandidates(colData, rowData.length);
int numChanged;
do {
numChanged = reduceMutual(cols, rows);
if (numChanged == -1) {
System.out.println("No solution");
return;
}
} while (numChanged > 0);
for (List<BitSet> row : rows) {
for (int i = 0; i < cols.size(); i++)
System.out.print(row.get(0).get(i) ? "# " : ". ");
System.out.println();
}
System.out.println();
}
static List<List<BitSet>> getCandidates(String[] data, int len) {
List<List<BitSet>> result = new ArrayList<>();
for (String s : data) {
List<BitSet> lst = new LinkedList<>();
int sumChars = s.chars().map(c -> c - 'A' + 1).sum();
List<String> prep = stream(s.split(""))
.map(x -> repeat(x.charAt(0) - 'A' + 1, "1")).collect(toList());
for (String r : genSequence(prep, len - sumChars + 1)) {
char[] bits = r.substring(1).toCharArray();
BitSet bitset = new BitSet(bits.length);
for (int i = 0; i < bits.length; i++)
bitset.set(i, bits[i] == '1');
lst.add(bitset);
}
result.add(lst);
}
return result;
}
static List<String> genSequence(List<String> ones, int numZeros) {
if (ones.isEmpty())
return asList(repeat(numZeros, "0"));
List<String> result = new ArrayList<>();
for (int x = 1; x < numZeros - ones.size() + 2; x++) {
List<String> skipOne = ones.stream().skip(1).collect(toList());
for (String tail : genSequence(skipOne, numZeros - x))
result.add(repeat(x, "0") + ones.get(0) + tail);
}
return result;
}
static String repeat(int n, String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(s);
return sb.toString();
}
static int reduceMutual(List<List<BitSet>> cols, List<List<BitSet>> rows) {
int countRemoved1 = reduce(cols, rows);
if (countRemoved1 == -1)
return -1;
int countRemoved2 = reduce(rows, cols);
if (countRemoved2 == -1)
return -1;
return countRemoved1 + countRemoved2;
}
static int reduce(List<List<BitSet>> a, List<List<BitSet>> b) {
int countRemoved = 0;
for (int i = 0; i < a.size(); i++) {
BitSet commonOn = new BitSet();
commonOn.set(0, b.size());
BitSet commonOff = new BitSet();
for (BitSet candidate : a.get(i)) {
commonOn.and(candidate);
commonOff.or(candidate);
}
for (int j = 0; j < b.size(); j++) {
final int fi = i, fj = j;
if (b.get(j).removeIf(cnd -> (commonOn.get(fj) && !cnd.get(fi))
|| (!commonOff.get(fj) && cnd.get(fi))))
countRemoved++;
if (b.get(j).isEmpty())
return -1;
}
}
return countRemoved;
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | import re
from random import shuffle, randint
dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
class Grid:
def __init__(self):
self.num_attempts = 0
self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]
self.solutions = []
def read_words(filename):
max_len = max(n_rows, n_cols)
words = []
with open(filename, "r") as file:
for line in file:
s = line.strip().lower()
if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:
words.append(s)
return words
def place_message(grid, msg):
msg = re.sub(r'[^A-Z]', "", msg.upper())
message_len = len(msg)
if 0 < message_len < grid_size:
gap_size = grid_size // message_len
for i in range(0, message_len):
pos = i * gap_size + randint(0, gap_size)
grid.cells[pos // n_cols][pos % n_cols] = msg[i]
return message_len
return 0
def try_location(grid, word, direction, pos):
r = pos // n_cols
c = pos % n_cols
length = len(word)
if (dirs[direction][0] == 1 and (length + c) > n_cols) or \
(dirs[direction][0] == -1 and (length - 1) > c) or \
(dirs[direction][1] == 1 and (length + r) > n_rows) or \
(dirs[direction][1] == -1 and (length - 1) > r):
return 0
rr = r
cc = c
i = 0
overlaps = 0
while i < length:
if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:
return 0
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
rr = r
cc = c
i = 0
while i < length:
if grid.cells[rr][cc] == word[i]:
overlaps += 1
else:
grid.cells[rr][cc] = word[i]
if i < length - 1:
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
letters_placed = length - overlaps
if letters_placed > 0:
grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr))
return letters_placed
def try_place_word(grid, word):
rand_dir = randint(0, len(dirs))
rand_pos = randint(0, grid_size)
for direction in range(0, len(dirs)):
direction = (direction + rand_dir) % len(dirs)
for pos in range(0, grid_size):
pos = (pos + rand_pos) % grid_size
letters_placed = try_location(grid, word, direction, pos)
if letters_placed > 0:
return letters_placed
return 0
def create_word_search(words):
grid = None
num_attempts = 0
while num_attempts < 100:
num_attempts += 1
shuffle(words)
grid = Grid()
message_len = place_message(grid, "Rosetta Code")
target = grid_size - message_len
cells_filled = 0
for word in words:
cells_filled += try_place_word(grid, word)
if cells_filled == target:
if len(grid.solutions) >= min_words:
grid.num_attempts = num_attempts
return grid
else:
break
return grid
def print_result(grid):
if grid is None or grid.num_attempts == 0:
print("No grid to display")
return
size = len(grid.solutions)
print("Attempts: {0}".format(grid.num_attempts))
print("Number of words: {0}".format(size))
print("\n 0 1 2 3 4 5 6 7 8 9\n")
for r in range(0, n_rows):
print("{0} ".format(r), end='')
for c in range(0, n_cols):
print(" %c " % grid.cells[r][c], end='')
print()
print()
for i in range(0, size - 1, 2):
print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1]))
if size % 2 == 1:
print(grid.solutions[size - 1])
if __name__ == "__main__":
print_result(create_word_search(read_words("unixdict.txt")))
| import java.io.*;
import static java.lang.String.format;
import java.util.*;
public class WordSearch {
static class Grid {
int numAttempts;
char[][] cells = new char[nRows][nCols];
List<String> solutions = new ArrayList<>();
}
final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
final static int nRows = 10;
final static int nCols = 10;
final static int gridSize = nRows * nCols;
final static int minWords = 25;
final static Random rand = new Random();
public static void main(String[] args) {
printResult(createWordSearch(readWords("unixdict.txt")));
}
static List<String> readWords(String filename) {
int maxLen = Math.max(nRows, nCols);
List<String> words = new ArrayList<>();
try (Scanner sc = new Scanner(new FileReader(filename))) {
while (sc.hasNext()) {
String s = sc.next().trim().toLowerCase();
if (s.matches("^[a-z]{3," + maxLen + "}$"))
words.add(s);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
return words;
}
static Grid createWordSearch(List<String> words) {
Grid grid = null;
int numAttempts = 0;
outer:
while (++numAttempts < 100) {
Collections.shuffle(words);
grid = new Grid();
int messageLen = placeMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled = 0;
for (String word : words) {
cellsFilled += tryPlaceWord(grid, word);
if (cellsFilled == target) {
if (grid.solutions.size() >= minWords) {
grid.numAttempts = numAttempts;
break outer;
} else break;
}
}
}
return grid;
}
static int placeMessage(Grid grid, String msg) {
msg = msg.toUpperCase().replaceAll("[^A-Z]", "");
int messageLen = msg.length();
if (messageLen > 0 && messageLen < gridSize) {
int gapSize = gridSize / messageLen;
for (int i = 0; i < messageLen; i++) {
int pos = i * gapSize + rand.nextInt(gapSize);
grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);
}
return messageLen;
}
return 0;
}
static int tryPlaceWord(Grid grid, String word) {
int randDir = rand.nextInt(dirs.length);
int randPos = rand.nextInt(gridSize);
for (int dir = 0; dir < dirs.length; dir++) {
dir = (dir + randDir) % dirs.length;
for (int pos = 0; pos < gridSize; pos++) {
pos = (pos + randPos) % gridSize;
int lettersPlaced = tryLocation(grid, word, dir, pos);
if (lettersPlaced > 0)
return lettersPlaced;
}
}
return 0;
}
static int tryLocation(Grid grid, String word, int dir, int pos) {
int r = pos / nCols;
int c = pos % nCols;
int len = word.length();
if ((dirs[dir][0] == 1 && (len + c) > nCols)
|| (dirs[dir][0] == -1 && (len - 1) > c)
|| (dirs[dir][1] == 1 && (len + r) > nRows)
|| (dirs[dir][1] == -1 && (len - 1) > r))
return 0;
int rr, cc, i, overlaps = 0;
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))
return 0;
cc += dirs[dir][0];
rr += dirs[dir][1];
}
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] == word.charAt(i))
overlaps++;
else
grid.cells[rr][cc] = word.charAt(i);
if (i < len - 1) {
cc += dirs[dir][0];
rr += dirs[dir][1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0) {
grid.solutions.add(format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr));
}
return lettersPlaced;
}
static void printResult(Grid grid) {
if (grid == null || grid.numAttempts == 0) {
System.out.println("No grid to display");
return;
}
int size = grid.solutions.size();
System.out.println("Attempts: " + grid.numAttempts);
System.out.println("Number of words: " + size);
System.out.println("\n 0 1 2 3 4 5 6 7 8 9");
for (int r = 0; r < nRows; r++) {
System.out.printf("%n%d ", r);
for (int c = 0; c < nCols; c++)
System.out.printf(" %c ", grid.cells[r][c]);
}
System.out.println("\n");
for (int i = 0; i < size - 1; i += 2) {
System.out.printf("%s %s%n", grid.solutions.get(i),
grid.solutions.get(i + 1));
}
if (size % 2 == 1)
System.out.println(grid.solutions.get(size - 1));
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | import re
from random import shuffle, randint
dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
class Grid:
def __init__(self):
self.num_attempts = 0
self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]
self.solutions = []
def read_words(filename):
max_len = max(n_rows, n_cols)
words = []
with open(filename, "r") as file:
for line in file:
s = line.strip().lower()
if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:
words.append(s)
return words
def place_message(grid, msg):
msg = re.sub(r'[^A-Z]', "", msg.upper())
message_len = len(msg)
if 0 < message_len < grid_size:
gap_size = grid_size // message_len
for i in range(0, message_len):
pos = i * gap_size + randint(0, gap_size)
grid.cells[pos // n_cols][pos % n_cols] = msg[i]
return message_len
return 0
def try_location(grid, word, direction, pos):
r = pos // n_cols
c = pos % n_cols
length = len(word)
if (dirs[direction][0] == 1 and (length + c) > n_cols) or \
(dirs[direction][0] == -1 and (length - 1) > c) or \
(dirs[direction][1] == 1 and (length + r) > n_rows) or \
(dirs[direction][1] == -1 and (length - 1) > r):
return 0
rr = r
cc = c
i = 0
overlaps = 0
while i < length:
if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:
return 0
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
rr = r
cc = c
i = 0
while i < length:
if grid.cells[rr][cc] == word[i]:
overlaps += 1
else:
grid.cells[rr][cc] = word[i]
if i < length - 1:
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
letters_placed = length - overlaps
if letters_placed > 0:
grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr))
return letters_placed
def try_place_word(grid, word):
rand_dir = randint(0, len(dirs))
rand_pos = randint(0, grid_size)
for direction in range(0, len(dirs)):
direction = (direction + rand_dir) % len(dirs)
for pos in range(0, grid_size):
pos = (pos + rand_pos) % grid_size
letters_placed = try_location(grid, word, direction, pos)
if letters_placed > 0:
return letters_placed
return 0
def create_word_search(words):
grid = None
num_attempts = 0
while num_attempts < 100:
num_attempts += 1
shuffle(words)
grid = Grid()
message_len = place_message(grid, "Rosetta Code")
target = grid_size - message_len
cells_filled = 0
for word in words:
cells_filled += try_place_word(grid, word)
if cells_filled == target:
if len(grid.solutions) >= min_words:
grid.num_attempts = num_attempts
return grid
else:
break
return grid
def print_result(grid):
if grid is None or grid.num_attempts == 0:
print("No grid to display")
return
size = len(grid.solutions)
print("Attempts: {0}".format(grid.num_attempts))
print("Number of words: {0}".format(size))
print("\n 0 1 2 3 4 5 6 7 8 9\n")
for r in range(0, n_rows):
print("{0} ".format(r), end='')
for c in range(0, n_cols):
print(" %c " % grid.cells[r][c], end='')
print()
print()
for i in range(0, size - 1, 2):
print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1]))
if size % 2 == 1:
print(grid.solutions[size - 1])
if __name__ == "__main__":
print_result(create_word_search(read_words("unixdict.txt")))
| import java.io.*;
import static java.lang.String.format;
import java.util.*;
public class WordSearch {
static class Grid {
int numAttempts;
char[][] cells = new char[nRows][nCols];
List<String> solutions = new ArrayList<>();
}
final static int[][] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
final static int nRows = 10;
final static int nCols = 10;
final static int gridSize = nRows * nCols;
final static int minWords = 25;
final static Random rand = new Random();
public static void main(String[] args) {
printResult(createWordSearch(readWords("unixdict.txt")));
}
static List<String> readWords(String filename) {
int maxLen = Math.max(nRows, nCols);
List<String> words = new ArrayList<>();
try (Scanner sc = new Scanner(new FileReader(filename))) {
while (sc.hasNext()) {
String s = sc.next().trim().toLowerCase();
if (s.matches("^[a-z]{3," + maxLen + "}$"))
words.add(s);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
return words;
}
static Grid createWordSearch(List<String> words) {
Grid grid = null;
int numAttempts = 0;
outer:
while (++numAttempts < 100) {
Collections.shuffle(words);
grid = new Grid();
int messageLen = placeMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled = 0;
for (String word : words) {
cellsFilled += tryPlaceWord(grid, word);
if (cellsFilled == target) {
if (grid.solutions.size() >= minWords) {
grid.numAttempts = numAttempts;
break outer;
} else break;
}
}
}
return grid;
}
static int placeMessage(Grid grid, String msg) {
msg = msg.toUpperCase().replaceAll("[^A-Z]", "");
int messageLen = msg.length();
if (messageLen > 0 && messageLen < gridSize) {
int gapSize = gridSize / messageLen;
for (int i = 0; i < messageLen; i++) {
int pos = i * gapSize + rand.nextInt(gapSize);
grid.cells[pos / nCols][pos % nCols] = msg.charAt(i);
}
return messageLen;
}
return 0;
}
static int tryPlaceWord(Grid grid, String word) {
int randDir = rand.nextInt(dirs.length);
int randPos = rand.nextInt(gridSize);
for (int dir = 0; dir < dirs.length; dir++) {
dir = (dir + randDir) % dirs.length;
for (int pos = 0; pos < gridSize; pos++) {
pos = (pos + randPos) % gridSize;
int lettersPlaced = tryLocation(grid, word, dir, pos);
if (lettersPlaced > 0)
return lettersPlaced;
}
}
return 0;
}
static int tryLocation(Grid grid, String word, int dir, int pos) {
int r = pos / nCols;
int c = pos % nCols;
int len = word.length();
if ((dirs[dir][0] == 1 && (len + c) > nCols)
|| (dirs[dir][0] == -1 && (len - 1) > c)
|| (dirs[dir][1] == 1 && (len + r) > nRows)
|| (dirs[dir][1] == -1 && (len - 1) > r))
return 0;
int rr, cc, i, overlaps = 0;
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] != 0 && grid.cells[rr][cc] != word.charAt(i))
return 0;
cc += dirs[dir][0];
rr += dirs[dir][1];
}
for (i = 0, rr = r, cc = c; i < len; i++) {
if (grid.cells[rr][cc] == word.charAt(i))
overlaps++;
else
grid.cells[rr][cc] = word.charAt(i);
if (i < len - 1) {
cc += dirs[dir][0];
rr += dirs[dir][1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0) {
grid.solutions.add(format("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr));
}
return lettersPlaced;
}
static void printResult(Grid grid) {
if (grid == null || grid.numAttempts == 0) {
System.out.println("No grid to display");
return;
}
int size = grid.solutions.size();
System.out.println("Attempts: " + grid.numAttempts);
System.out.println("Number of words: " + size);
System.out.println("\n 0 1 2 3 4 5 6 7 8 9");
for (int r = 0; r < nRows; r++) {
System.out.printf("%n%d ", r);
for (int c = 0; c < nCols; c++)
System.out.printf(" %c ", grid.cells[r][c]);
}
System.out.println("\n");
for (int i = 0; i < size - 1; i += 2) {
System.out.printf("%s %s%n", grid.solutions.get(i),
grid.solutions.get(i + 1));
}
if (size % 2 == 1)
System.out.println(grid.solutions.get(size - 1));
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
| module BreakOO
{
class Exposed
{
public String pub = "public";
protected String pro = "protected";
private String pri = "private";
@Override
String toString()
{
return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
}
}
void run()
{
@Inject Console console;
Exposed expo = new Exposed();
console.print($"before: {expo}");
expo.pub = $"this was {expo.pub}";
assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
expoPro.pro = $"this was {expoPro.pro}";
assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
expoPri.pri = $"this was {expoPri.pri}";
assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
expoStr.pub = $"{expoStr.pub}!!!";
expoStr.pro = $"{expoStr.pro}!!!";
expoStr.pri = $"{expoStr.pri}!!!";
console.print($"after: {expo}");
}
}
|
Change the following Python code into Java without altering its purpose. | >>> class MyClassName:
__private = 123
non_private = __private * 2
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
File "<pyshell
mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
| module BreakOO
{
class Exposed
{
public String pub = "public";
protected String pro = "protected";
private String pri = "private";
@Override
String toString()
{
return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
}
}
void run()
{
@Inject Console console;
Exposed expo = new Exposed();
console.print($"before: {expo}");
expo.pub = $"this was {expo.pub}";
assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
expoPro.pro = $"this was {expoPro.pro}";
assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
expoPri.pri = $"this was {expoPri.pri}";
assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
expoStr.pub = $"{expoStr.pub}!!!";
expoStr.pro = $"{expoStr.pro}!!!";
expoStr.pri = $"{expoStr.pri}!!!";
console.print($"after: {expo}");
}
}
|
Translate the given Python code snippet into Java without altering its behavior. |
import pickle
class Entity:
def __init__(self):
self.name = "Entity"
def printName(self):
print self.name
class Person(Entity):
def __init__(self):
self.name = "Cletus"
instance1 = Person()
instance1.printName()
instance2 = Entity()
instance2.printName()
target = file("objects.dat", "w")
pickle.dump((instance1, instance2), target)
target.close()
print "Serialized..."
target = file("objects.dat")
i1, i2 = pickle.load(target)
print "Unserialized..."
i1.printName()
i2.printName()
| import java.io.*;
class Entity implements Serializable {
static final long serialVersionUID = 3504465751164822571L;
String name = "Entity";
public String toString() { return name; }
}
class Person extends Entity implements Serializable {
static final long serialVersionUID = -9170445713373959735L;
Person() { name = "Cletus"; }
}
public class SerializationTest {
public static void main(String[] args) {
Person instance1 = new Person();
System.out.println(instance1);
Entity instance2 = new Entity();
System.out.println(instance2);
try {
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("objects.dat"));
out.writeObject(instance1);
out.writeObject(instance2);
out.close();
System.out.println("Serialized...");
} catch (IOException e) {
System.err.println("Something screwed up while serializing");
e.printStackTrace();
System.exit(1);
}
try {
ObjectInput in = new ObjectInputStream(new FileInputStream("objects.dat"));
Object readObject1 = in.readObject();
Object readObject2 = in.readObject();
in.close();
System.out.println("Deserialized...");
System.out.println(readObject1);
System.out.println(readObject2);
} catch (IOException e) {
System.err.println("Something screwed up while deserializing");
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
System.err.println("Unknown class for deserialized object");
e.printStackTrace();
System.exit(1);
}
}
}
|
Write the same code in Java as shown below in Python. |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.rte.len = 0
self.S = [0]
self.maxSufT = self.rte
def get_max_suffix_pal(self, startNode, a):
u = startNode
i = len(self.S)
k = u.len
while id(u) != id(self.rto) and self.S[i - k - 1] != a:
assert id(u) != id(u.link)
u = u.link
k = u.len
return u
def add(self, a):
Q = self.get_max_suffix_pal(self.maxSufT, a)
createANewNode = not a in Q.edges
if createANewNode:
P = Node()
self.nodes.append(P)
P.len = Q.len + 2
if P.len == 1:
P.link = self.rte
else:
P.link = self.get_max_suffix_pal(Q.link, a).edges[a]
Q.edges[a] = P
self.maxSufT = Q.edges[a]
self.S.append(a)
return createANewNode
def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
for lnkName in nd.edges:
nd2 = nd.edges[lnkName]
self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)
if id(nd) != id(self.rto) and id(nd) != id(self.rte):
tmp = "".join(charsToHere)
if id(nodesToHere[0]) == id(self.rte):
assembled = tmp[::-1] + tmp
else:
assembled = tmp[::-1] + tmp[1:]
result.append(assembled)
if __name__=="__main__":
st = "eertree"
print ("Processing string", st)
eertree = Eertree()
for ch in st:
eertree.add(ch)
print ("Number of sub-palindromes:", len(eertree.nodes))
result = []
eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result)
eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result)
print ("Sub-palindromes:", result)
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
private static class Node {
int length;
Map<Character, Integer> edges = new HashMap<>();
int suffix;
public Node(int length) {
this.length = length;
}
public Node(int length, Map<Character, Integer> edges, int suffix) {
this.length = length;
this.edges = edges != null ? edges : new HashMap<>();
this.suffix = suffix;
}
}
private static final int EVEN_ROOT = 0;
private static final int ODD_ROOT = 1;
private static List<Node> eertree(String s) {
List<Node> tree = new ArrayList<>();
tree.add(new Node(0, null, ODD_ROOT));
tree.add(new Node(-1, null, ODD_ROOT));
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
for (n = suffix; ; n = tree.get(n).suffix) {
k = tree.get(n).length;
int b = i - k - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
if (tree.get(n).edges.containsKey(c)) {
suffix = tree.get(n).edges.get(c);
continue;
}
suffix = tree.size();
tree.add(new Node(k + 2));
tree.get(n).edges.put(c, suffix);
if (tree.get(suffix).length == 1) {
tree.get(suffix).suffix = 0;
continue;
}
while (true) {
n = tree.get(n).suffix;
int b = i - tree.get(n).length - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
tree.get(suffix).suffix = tree.get(n).edges.get(c);
}
return tree;
}
private static List<String> subPalindromes(List<Node> tree) {
List<String> s = new ArrayList<>();
subPalindromes_children(0, "", tree, s);
for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
String ct = String.valueOf(cm.getKey());
s.add(ct);
subPalindromes_children(cm.getValue(), ct, tree, s);
}
return s;
}
private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
Character c = cm.getKey();
Integer m = cm.getValue();
String pl = c + p + c;
s.add(pl);
subPalindromes_children(m, pl, tree, s);
}
}
}
|
Write the same algorithm in Java as shown in this Python implementation. |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.rte.len = 0
self.S = [0]
self.maxSufT = self.rte
def get_max_suffix_pal(self, startNode, a):
u = startNode
i = len(self.S)
k = u.len
while id(u) != id(self.rto) and self.S[i - k - 1] != a:
assert id(u) != id(u.link)
u = u.link
k = u.len
return u
def add(self, a):
Q = self.get_max_suffix_pal(self.maxSufT, a)
createANewNode = not a in Q.edges
if createANewNode:
P = Node()
self.nodes.append(P)
P.len = Q.len + 2
if P.len == 1:
P.link = self.rte
else:
P.link = self.get_max_suffix_pal(Q.link, a).edges[a]
Q.edges[a] = P
self.maxSufT = Q.edges[a]
self.S.append(a)
return createANewNode
def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
for lnkName in nd.edges:
nd2 = nd.edges[lnkName]
self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)
if id(nd) != id(self.rto) and id(nd) != id(self.rte):
tmp = "".join(charsToHere)
if id(nodesToHere[0]) == id(self.rte):
assembled = tmp[::-1] + tmp
else:
assembled = tmp[::-1] + tmp[1:]
result.append(assembled)
if __name__=="__main__":
st = "eertree"
print ("Processing string", st)
eertree = Eertree()
for ch in st:
eertree.add(ch)
print ("Number of sub-palindromes:", len(eertree.nodes))
result = []
eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result)
eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result)
print ("Sub-palindromes:", result)
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
private static class Node {
int length;
Map<Character, Integer> edges = new HashMap<>();
int suffix;
public Node(int length) {
this.length = length;
}
public Node(int length, Map<Character, Integer> edges, int suffix) {
this.length = length;
this.edges = edges != null ? edges : new HashMap<>();
this.suffix = suffix;
}
}
private static final int EVEN_ROOT = 0;
private static final int ODD_ROOT = 1;
private static List<Node> eertree(String s) {
List<Node> tree = new ArrayList<>();
tree.add(new Node(0, null, ODD_ROOT));
tree.add(new Node(-1, null, ODD_ROOT));
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
for (n = suffix; ; n = tree.get(n).suffix) {
k = tree.get(n).length;
int b = i - k - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
if (tree.get(n).edges.containsKey(c)) {
suffix = tree.get(n).edges.get(c);
continue;
}
suffix = tree.size();
tree.add(new Node(k + 2));
tree.get(n).edges.put(c, suffix);
if (tree.get(suffix).length == 1) {
tree.get(suffix).suffix = 0;
continue;
}
while (true) {
n = tree.get(n).suffix;
int b = i - tree.get(n).length - 1;
if (b >= 0 && s.charAt(b) == c) {
break;
}
}
tree.get(suffix).suffix = tree.get(n).edges.get(c);
}
return tree;
}
private static List<String> subPalindromes(List<Node> tree) {
List<String> s = new ArrayList<>();
subPalindromes_children(0, "", tree, s);
for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
String ct = String.valueOf(cm.getKey());
s.add(ct);
subPalindromes_children(cm.getValue(), ct, tree, s);
}
return s;
}
private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
Character c = cm.getKey();
Integer m = cm.getValue();
String pl = c + p + c;
s.add(pl);
subPalindromes_children(m, pl, tree, s);
}
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. |
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
| import java.time.LocalDate;
import java.time.temporal.WeekFields;
public class LongYear {
public static void main(String[] args) {
System.out.printf("Long years this century:%n");
for (int year = 2000 ; year < 2100 ; year++ ) {
if ( longYear(year) ) {
System.out.print(year + " ");
}
}
}
private static boolean longYear(int year) {
return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;
}
}
|
Please provide an equivalent version of this Python code in Java. | from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s % 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def printZumkellers(N, oddonly=False):
nprinted = 0
for n in range(1, 10**5):
if (oddonly == False or n % 2) and isZumkeller(n):
print(f'{n:>8}', end='')
nprinted += 1
if nprinted % 10 == 0:
print()
if nprinted >= N:
return
print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ZumkellerNumbers {
public static void main(String[] args) {
int n = 1;
System.out.printf("First 220 Zumkeller numbers:%n");
for ( int count = 1 ; count <= 220 ; n += 1 ) {
if ( isZumkeller(n) ) {
System.out.printf("%3d ", n);
if ( count % 20 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( isZumkeller(n) ) {
System.out.printf("%6d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
n = 1;
System.out.printf("%nFirst 40 odd Zumkeller numbers that do not end in a 5:%n");
for ( int count = 1 ; count <= 40 ; n += 2 ) {
if ( n % 5 != 0 && isZumkeller(n) ) {
System.out.printf("%8d", n);
if ( count % 10 == 0 ) {
System.out.printf("%n");
}
count++;
}
}
}
private static boolean isZumkeller(int n) {
if ( n % 18 == 6 || n % 18 == 12 ) {
return true;
}
List<Integer> divisors = getDivisors(n);
int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum();
if ( divisorSum % 2 == 1 ) {
return false;
}
int abundance = divisorSum - 2 * n;
if ( n % 2 == 1 && abundance > 0 && abundance % 2 == 0 ) {
return true;
}
Collections.sort(divisors);
int j = divisors.size() - 1;
int sum = divisorSum/2;
if ( divisors.get(j) > sum ) {
return false;
}
return canPartition(j, divisors, sum, new int[2]);
}
private static boolean canPartition(int j, List<Integer> divisors, int sum, int[] buckets) {
if ( j < 0 ) {
return true;
}
for ( int i = 0 ; i < 2 ; i++ ) {
if ( buckets[i] + divisors.get(j) <= sum ) {
buckets[i] += divisors.get(j);
if ( canPartition(j-1, divisors, sum, buckets) ) {
return true;
}
buckets[i] -= divisors.get(j);
}
if( buckets[i] == 0 ) {
break;
}
}
return false;
}
private static final List<Integer> getDivisors(int number) {
List<Integer> divisors = new ArrayList<Integer>();
long sqrt = (long) Math.sqrt(number);
for ( int i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
int div = number / i;
if ( div != i ) {
divisors.add(div);
}
}
}
return divisors;
}
}
|
Please provide an equivalent version of this Python code in Java. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| import java.util.*;
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.put("price", 15.25);
update.put("color", "red");
update.put("year", 1974);
Map<String, Object> result = new HashMap<>(base);
result.putAll(update);
System.out.println(result);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| import java.util.*;
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.put("price", 15.25);
update.put("color", "red");
update.put("year", 1974);
Map<String, Object> result = new HashMap<>(base);
result.putAll(update);
System.out.println(result);
}
}
|
Write a version of this Python function in Java with identical behavior. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256)
| import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
public class MetallicRatios {
private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};
public static void main(String[] args) {
int elements = 15;
for ( int b = 0 ; b < 10 ; b++ ) {
System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b);
System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements));
int decimalPlaces = 32;
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterationsΒ : %s%n", decimalPlaces, ratio[1], ratio[0]);
System.out.printf("%n");
}
int b = 1;
int decimalPlaces = 256;
System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b);
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterationsΒ : %s%n", decimalPlaces, ratio[1], ratio[0]);
}
private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {
BigDecimal x0Bi = BigDecimal.valueOf(x0);
BigDecimal x1Bi = BigDecimal.valueOf(x1);
BigDecimal bBi = BigDecimal.valueOf(b);
MathContext mc = new MathContext(digits);
BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);
int iterations = 0;
while ( true ) {
iterations++;
BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);
BigDecimal fractionCurrent = x.divide(x1Bi, mc);
if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {
break;
}
x0Bi = x1Bi;
x1Bi = x;
fractionPrior = fractionCurrent;
}
return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};
}
private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {
List<BigInteger> list = new ArrayList<>();
BigInteger x0Bi = BigInteger.valueOf(x0);
BigInteger x1Bi = BigInteger.valueOf(x1);
BigInteger bBi = BigInteger.valueOf(b);
if ( n > 0 ) {
list.add(x0Bi);
}
if ( n > 1 ) {
list.add(x1Bi);
}
while ( n > 2 ) {
BigInteger x = bBi.multiply(x1Bi).add(x0Bi);
list.add(x);
n--;
x0Bi = x1Bi;
x1Bi = x;
}
return list;
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256)
| import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
public class MetallicRatios {
private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};
public static void main(String[] args) {
int elements = 15;
for ( int b = 0 ; b < 10 ; b++ ) {
System.out.printf("Lucas sequence for %s ratio, where b = %d:%n", ratioDescription[b], b);
System.out.printf("First %d elements: %s%n", elements, lucasSequence(1, 1, b, elements));
int decimalPlaces = 32;
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterationsΒ : %s%n", decimalPlaces, ratio[1], ratio[0]);
System.out.printf("%n");
}
int b = 1;
int decimalPlaces = 256;
System.out.printf("%s ratio, where b = %d:%n", ratioDescription[b], b);
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to %d decimal places after %s iterationsΒ : %s%n", decimalPlaces, ratio[1], ratio[0]);
}
private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {
BigDecimal x0Bi = BigDecimal.valueOf(x0);
BigDecimal x1Bi = BigDecimal.valueOf(x1);
BigDecimal bBi = BigDecimal.valueOf(b);
MathContext mc = new MathContext(digits);
BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);
int iterations = 0;
while ( true ) {
iterations++;
BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);
BigDecimal fractionCurrent = x.divide(x1Bi, mc);
if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {
break;
}
x0Bi = x1Bi;
x1Bi = x;
fractionPrior = fractionCurrent;
}
return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};
}
private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {
List<BigInteger> list = new ArrayList<>();
BigInteger x0Bi = BigInteger.valueOf(x0);
BigInteger x1Bi = BigInteger.valueOf(x1);
BigInteger bBi = BigInteger.valueOf(b);
if ( n > 0 ) {
list.add(x0Bi);
}
if ( n > 1 ) {
list.add(x1Bi);
}
while ( n > 2 ) {
BigInteger x = bBi.multiply(x1Bi).add(x0Bi);
list.add(x);
n--;
x0Bi = x1Bi;
x1Bi = x;
}
return list;
}
}
|
Port the provided Python code into Java while preserving the original functionality. | import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index += 1
return rule
def makestring(rule, length):
oldwords = random.choice(list(rule.keys())).split(' ')
string = ' '.join(oldwords) + ' '
for i in range(length):
try:
key = ' '.join(oldwords)
newword = random.choice(rule[key])
string += newword + ' '
for word in range(len(oldwords)):
oldwords[word] = oldwords[(word + 1) % len(oldwords)]
oldwords[-1] = newword
except KeyError:
return string
return string
if __name__ == '__main__':
with open(sys.argv[1], encoding='utf8') as f:
data = f.read()
rule = makerule(data, int(sys.argv[2]))
string = makestring(rule, int(sys.argv[3]))
print(string)
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
public class MarkovChain {
private static Random r = new Random();
private static String markov(String filePath, int keySize, int outputSize) throws IOException {
if (keySize < 1) throw new IllegalArgumentException("Key size can't be less than 1");
Path path = Paths.get(filePath);
byte[] bytes = Files.readAllBytes(path);
String[] words = new String(bytes).trim().split(" ");
if (outputSize < keySize || outputSize >= words.length) {
throw new IllegalArgumentException("Output size is out of range");
}
Map<String, List<String>> dict = new HashMap<>();
for (int i = 0; i < (words.length - keySize); ++i) {
StringBuilder key = new StringBuilder(words[i]);
for (int j = i + 1; j < i + keySize; ++j) {
key.append(' ').append(words[j]);
}
String value = (i + keySize < words.length) ? words[i + keySize] : "";
if (!dict.containsKey(key.toString())) {
ArrayList<String> list = new ArrayList<>();
list.add(value);
dict.put(key.toString(), list);
} else {
dict.get(key.toString()).add(value);
}
}
int n = 0;
int rn = r.nextInt(dict.size());
String prefix = (String) dict.keySet().toArray()[rn];
List<String> output = new ArrayList<>(Arrays.asList(prefix.split(" ")));
while (true) {
List<String> suffix = dict.get(prefix);
if (suffix.size() == 1) {
if (Objects.equals(suffix.get(0), "")) return output.stream().reduce("", (a, b) -> a + " " + b);
output.add(suffix.get(0));
} else {
rn = r.nextInt(suffix.size());
output.add(suffix.get(rn));
}
if (output.size() >= outputSize) return output.stream().limit(outputSize).reduce("", (a, b) -> a + " " + b);
n++;
prefix = output.stream().skip(n).limit(keySize).reduce("", (a, b) -> a + " " + b).trim();
}
}
public static void main(String[] args) throws IOException {
System.out.println(markov("alice_oz.txt", 3, 200));
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | from collections import namedtuple, deque
from pprint import pprint as pp
inf = float('inf')
Edge = namedtuple('Edge', ['start', 'end', 'cost'])
class Graph():
def __init__(self, edges):
self.edges = [Edge(*edge) for edge in edges]
self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}
def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))
neighbours[end].add((start, cost))
while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]:
dist[v] = alt
previous[v] = u
s, u = deque(), dest
while previous[u]:
s.appendleft(u)
u = previous[u]
s.appendleft(u)
return s
graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10),
("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6),
("e", "f", 9)])
pp(graph.dijkstra("a", "e"))
| import java.io.*;
import java.util.*;
public class Dijkstra {
private static final Graph.Edge[] GRAPH = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
new Graph.Edge("c", "d", 11),
new Graph.Edge("c", "f", 2),
new Graph.Edge("d", "e", 6),
new Graph.Edge("e", "f", 9),
};
private static final String START = "a";
private static final String END = "e";
public static void main(String[] args) {
Graph g = new Graph(GRAPH);
g.dijkstra(START);
g.printPath(END);
}
}
class Graph {
private final Map<String, Vertex> graph;
public static class Edge {
public final String v1, v2;
public final int dist;
public Edge(String v1, String v2, int dist) {
this.v1 = v1;
this.v2 = v2;
this.dist = dist;
}
}
public static class Vertex implements Comparable<Vertex>{
public final String name;
public int dist = Integer.MAX_VALUE;
public Vertex previous = null;
public final Map<Vertex, Integer> neighbours = new HashMap<>();
public Vertex(String name)
{
this.name = name;
}
private void printPath()
{
if (this == this.previous)
{
System.out.printf("%s", this.name);
}
else if (this.previous == null)
{
System.out.printf("%s(unreached)", this.name);
}
else
{
this.previous.printPath();
System.out.printf(" -> %s(%d)", this.name, this.dist);
}
}
public int compareTo(Vertex other)
{
if (dist == other.dist)
return name.compareTo(other.name);
return Integer.compare(dist, other.dist);
}
@Override public String toString()
{
return "(" + name + ", " + dist + ")";
}
}
public Graph(Edge[] edges) {
graph = new HashMap<>(edges.length);
for (Edge e : edges) {
if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
}
for (Edge e : edges) {
graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
}
}
public void dijkstra(String startName) {
if (!graph.containsKey(startName)) {
System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
return;
}
final Vertex source = graph.get(startName);
NavigableSet<Vertex> q = new TreeSet<>();
for (Vertex v : graph.values()) {
v.previous = v == source ? source : null;
v.dist = v == source ? 0 : Integer.MAX_VALUE;
q.add(v);
}
dijkstra(q);
}
private void dijkstra(final NavigableSet<Vertex> q) {
Vertex u, v;
while (!q.isEmpty()) {
u = q.pollFirst();
if (u.dist == Integer.MAX_VALUE) break;
for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
v = a.getKey();
final int alternateDist = u.dist + a.getValue();
if (alternateDist < v.dist) {
q.remove(v);
v.dist = alternateDist;
v.previous = u;
q.add(v);
}
}
}
}
public void printPath(String endName) {
if (!graph.containsKey(endName)) {
System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
return;
}
graph.get(endName).printPath();
System.out.println();
}
public void printAllPaths() {
for (Vertex v : graph.values()) {
v.printPath();
System.out.println();
}
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | import copy, random
def bitcount(n):
return bin(n).count("1")
def reoderingSign(i, j):
k = i >> 1
sum = 0
while k != 0:
sum += bitcount(k & j)
k = k >> 1
return 1.0 if ((sum & 1) == 0) else -1.0
class Vector:
def __init__(self, da):
self.dims = da
def dot(self, other):
return (self * other + other * self) * 0.5
def __getitem__(self, i):
return self.dims[i]
def __setitem__(self, i, v):
self.dims[i] = v
def __neg__(self):
return self * -1.0
def __add__(self, other):
result = copy.copy(other.dims)
for i in xrange(0, len(self.dims)):
result[i] += self.dims[i]
return Vector(result)
def __mul__(self, other):
if isinstance(other, Vector):
result = [0.0] * 32
for i in xrange(0, len(self.dims)):
if self.dims[i] != 0.0:
for j in xrange(0, len(self.dims)):
if other.dims[j] != 0.0:
s = reoderingSign(i, j) * self.dims[i] * other.dims[j]
k = i ^ j
result[k] += s
return Vector(result)
else:
result = copy.copy(self.dims)
for i in xrange(0, len(self.dims)):
self.dims[i] *= other
return Vector(result)
def __str__(self):
return str(self.dims)
def e(n):
assert n <= 4, "n must be less than 5"
result = Vector([0.0] * 32)
result[1 << n] = 1.0
return result
def randomVector():
result = Vector([0.0] * 32)
for i in xrange(0, 5):
result += Vector([random.uniform(0, 1)]) * e(i)
return result
def randomMultiVector():
result = Vector([0.0] * 32)
for i in xrange(0, 32):
result[i] = random.uniform(0, 1)
return result
def main():
for i in xrange(0, 5):
for j in xrange(0, 5):
if i < j:
if e(i).dot(e(j))[0] != 0.0:
print "Unexpected non-null scalar product"
return
elif i == j:
if e(i).dot(e(j))[0] == 0.0:
print "Unexpected non-null scalar product"
a = randomMultiVector()
b = randomMultiVector()
c = randomMultiVector()
x = randomVector()
print (a * b) * c
print a * (b * c)
print
print a * (b + c)
print a * b + a * c
print
print (a + b) * c
print a * c + b * c
print
print x * x
main()
| import java.util.Arrays;
import java.util.Random;
public class GeometricAlgebra {
private static int bitCount(int i) {
i -= ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i + (i >> 4)) & 0x0F0F0F0F;
i += (i >> 8);
i += (i >> 16);
return i & 0x0000003F;
}
private static double reorderingSign(int i, int j) {
int k = i >> 1;
int sum = 0;
while (k != 0) {
sum += bitCount(k & j);
k = k >> 1;
}
return ((sum & 1) == 0) ? 1.0 : -1.0;
}
static class Vector {
private double[] dims;
public Vector(double[] dims) {
this.dims = dims;
}
public Vector dot(Vector rhs) {
return times(rhs).plus(rhs.times(this)).times(0.5);
}
public Vector unaryMinus() {
return times(-1.0);
}
public Vector plus(Vector rhs) {
double[] result = Arrays.copyOf(dims, 32);
for (int i = 0; i < rhs.dims.length; ++i) {
result[i] += rhs.get(i);
}
return new Vector(result);
}
public Vector times(Vector rhs) {
double[] result = new double[32];
for (int i = 0; i < dims.length; ++i) {
if (dims[i] != 0.0) {
for (int j = 0; j < rhs.dims.length; ++j) {
if (rhs.get(j) != 0.0) {
double s = reorderingSign(i, j) * dims[i] * rhs.dims[j];
int k = i ^ j;
result[k] += s;
}
}
}
}
return new Vector(result);
}
public Vector times(double scale) {
double[] result = dims.clone();
for (int i = 0; i < 5; ++i) {
dims[i] *= scale;
}
return new Vector(result);
}
double get(int index) {
return dims[index];
}
void set(int index, double value) {
dims[index] = value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for (double value : dims) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(value);
}
return sb.append(")").toString();
}
}
private static Vector e(int n) {
if (n > 4) {
throw new IllegalArgumentException("n must be less than 5");
}
Vector result = new Vector(new double[32]);
result.set(1 << n, 1.0);
return result;
}
private static final Random rand = new Random();
private static Vector randomVector() {
Vector result = new Vector(new double[32]);
for (int i = 0; i < 5; ++i) {
Vector temp = new Vector(new double[]{rand.nextDouble()});
result = result.plus(temp.times(e(i)));
}
return result;
}
private static Vector randomMultiVector() {
Vector result = new Vector(new double[32]);
for (int i = 0; i < 32; ++i) {
result.set(i, rand.nextDouble());
}
return result;
}
public static void main(String[] args) {
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (i < j) {
if (e(i).dot(e(j)).get(0) != 0.0) {
System.out.println("Unexpected non-null scalar product.");
return;
}
}
}
}
Vector a = randomMultiVector();
Vector b = randomMultiVector();
Vector c = randomMultiVector();
Vector x = randomVector();
System.out.println(a.times(b).times(c));
System.out.println(a.times(b.times(c)));
System.out.println();
System.out.println(a.times(b.plus(c)));
System.out.println(a.times(b).plus(a.times(c)));
System.out.println();
System.out.println(a.plus(b).times(c));
System.out.println(a.times(c).plus(b.times(c)));
System.out.println();
System.out.println(x.times(x));
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = 0
while i < len(suf):
b = suf[i]
x2 = 0
while True:
children = self.nodes[n].ch
if x2 == len(children):
n2 = len(self.nodes)
self.nodes.append(Node(suf[i:], []))
self.nodes[n].ch.append(n2)
return
n2 = children[x2]
if self.nodes[n2].sub[0] == b:
break
x2 = x2 + 1
sub2 = self.nodes[n2].sub
j = 0
while j < len(sub2):
if suf[i + j] != sub2[j]:
n3 = n2
n2 = len(self.nodes)
self.nodes.append(Node(sub2[:j], [n3]))
self.nodes[n3].sub = sub2[j:]
self.nodes[n].ch[x2] = n2
break
j = j + 1
i = i + j
n = n2
def visualize(self):
if len(self.nodes) == 0:
print "<empty>"
return
def f(n, pre):
children = self.nodes[n].ch
if len(children) == 0:
print "--", self.nodes[n].sub
return
print "+-", self.nodes[n].sub
for c in children[:-1]:
print pre, "+-",
f(c, pre + " | ")
print pre, "+-",
f(children[-1], pre + " ")
f(0, "")
SuffixTree("banana$").visualize()
| import java.util.ArrayList;
import java.util.List;
public class SuffixTreeProblem {
private static class Node {
String sub = "";
List<Integer> ch = new ArrayList<>();
}
private static class SuffixTree {
private List<Node> nodes = new ArrayList<>();
public SuffixTree(String str) {
nodes.add(new Node());
for (int i = 0; i < str.length(); ++i) {
addSuffix(str.substring(i));
}
}
private void addSuffix(String suf) {
int n = 0;
int i = 0;
while (i < suf.length()) {
char b = suf.charAt(i);
List<Integer> children = nodes.get(n).ch;
int x2 = 0;
int n2;
while (true) {
if (x2 == children.size()) {
n2 = nodes.size();
Node temp = new Node();
temp.sub = suf.substring(i);
nodes.add(temp);
children.add(n2);
return;
}
n2 = children.get(x2);
if (nodes.get(n2).sub.charAt(0) == b) break;
x2++;
}
String sub2 = nodes.get(n2).sub;
int j = 0;
while (j < sub2.length()) {
if (suf.charAt(i + j) != sub2.charAt(j)) {
int n3 = n2;
n2 = nodes.size();
Node temp = new Node();
temp.sub = sub2.substring(0, j);
temp.ch.add(n3);
nodes.add(temp);
nodes.get(n3).sub = sub2.substring(j);
nodes.get(n).ch.set(x2, n2);
break;
}
j++;
}
i += j;
n = n2;
}
}
public void visualize() {
if (nodes.isEmpty()) {
System.out.println("<empty>");
return;
}
visualize_f(0, "");
}
private void visualize_f(int n, String pre) {
List<Integer> children = nodes.get(n).ch;
if (children.isEmpty()) {
System.out.println("- " + nodes.get(n).sub);
return;
}
System.out.println("β " + nodes.get(n).sub);
for (int i = 0; i < children.size() - 1; i++) {
Integer c = children.get(i);
System.out.print(pre + "ββ");
visualize_f(c, pre + "β ");
}
System.out.print(pre + "ββ");
visualize_f(children.get(children.size() - 1), pre + " ");
}
}
public static void main(String[] args) {
new SuffixTree("banana$").visualize();
}
}
|
Keep all operations the same but rewrite the snippet in Java. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = 0
while i < len(suf):
b = suf[i]
x2 = 0
while True:
children = self.nodes[n].ch
if x2 == len(children):
n2 = len(self.nodes)
self.nodes.append(Node(suf[i:], []))
self.nodes[n].ch.append(n2)
return
n2 = children[x2]
if self.nodes[n2].sub[0] == b:
break
x2 = x2 + 1
sub2 = self.nodes[n2].sub
j = 0
while j < len(sub2):
if suf[i + j] != sub2[j]:
n3 = n2
n2 = len(self.nodes)
self.nodes.append(Node(sub2[:j], [n3]))
self.nodes[n3].sub = sub2[j:]
self.nodes[n].ch[x2] = n2
break
j = j + 1
i = i + j
n = n2
def visualize(self):
if len(self.nodes) == 0:
print "<empty>"
return
def f(n, pre):
children = self.nodes[n].ch
if len(children) == 0:
print "--", self.nodes[n].sub
return
print "+-", self.nodes[n].sub
for c in children[:-1]:
print pre, "+-",
f(c, pre + " | ")
print pre, "+-",
f(children[-1], pre + " ")
f(0, "")
SuffixTree("banana$").visualize()
| import java.util.ArrayList;
import java.util.List;
public class SuffixTreeProblem {
private static class Node {
String sub = "";
List<Integer> ch = new ArrayList<>();
}
private static class SuffixTree {
private List<Node> nodes = new ArrayList<>();
public SuffixTree(String str) {
nodes.add(new Node());
for (int i = 0; i < str.length(); ++i) {
addSuffix(str.substring(i));
}
}
private void addSuffix(String suf) {
int n = 0;
int i = 0;
while (i < suf.length()) {
char b = suf.charAt(i);
List<Integer> children = nodes.get(n).ch;
int x2 = 0;
int n2;
while (true) {
if (x2 == children.size()) {
n2 = nodes.size();
Node temp = new Node();
temp.sub = suf.substring(i);
nodes.add(temp);
children.add(n2);
return;
}
n2 = children.get(x2);
if (nodes.get(n2).sub.charAt(0) == b) break;
x2++;
}
String sub2 = nodes.get(n2).sub;
int j = 0;
while (j < sub2.length()) {
if (suf.charAt(i + j) != sub2.charAt(j)) {
int n3 = n2;
n2 = nodes.size();
Node temp = new Node();
temp.sub = sub2.substring(0, j);
temp.ch.add(n3);
nodes.add(temp);
nodes.get(n3).sub = sub2.substring(j);
nodes.get(n).ch.set(x2, n2);
break;
}
j++;
}
i += j;
n = n2;
}
}
public void visualize() {
if (nodes.isEmpty()) {
System.out.println("<empty>");
return;
}
visualize_f(0, "");
}
private void visualize_f(int n, String pre) {
List<Integer> children = nodes.get(n).ch;
if (children.isEmpty()) {
System.out.println("- " + nodes.get(n).sub);
return;
}
System.out.println("β " + nodes.get(n).sub);
for (int i = 0; i < children.size() - 1; i++) {
Integer c = children.get(i);
System.out.print(pre + "ββ");
visualize_f(c, pre + "β ");
}
System.out.print(pre + "ββ");
visualize_f(children.get(children.size() - 1), pre + " ");
}
}
public static void main(String[] args) {
new SuffixTree("banana$").visualize();
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | myDict = { "hello": 13,
"world": 31,
"!" : 71 }
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
for key in myDict:
print ("key = %s" % key)
for key in myDict.keys():
print ("key = %s" % key)
for value in myDict.values():
print ("value = %s" % value)
| Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);
for (Map.Entry<String, Integer> e : map.entrySet()) {
String key = e.getKey();
Integer value = e.getValue();
System.out.println("key = " + key + ", value = " + value);
}
for (String key : map.keySet()) {
System.out.println("key = " + key);
}
for (Integer value : map.values()) {
System.out.println("value = " + value);
}
|
Maintain the same structure and functionality when rewriting this code in Java. | >>> class num(int):
def __init__(self, b):
if 1 <= b <= 10:
return int.__init__(self+0)
else:
raise ValueError,"Value %s should be >=0 and <= 10" % b
>>> x = num(3)
>>> x = num(11)
Traceback (most recent call last):
File "<pyshell
x = num(11)
File "<pyshell
raise ValueError,"Value %s should be >=0 and <= 10" % b
ValueError: Value 11 should be >=0 and <= 10
>>> x
3
>>> type(x)
<class '__main__.num'>
>>>
| class BoundedIntOutOfBoundsException extends Exception
{
public BoundedIntOutOfBoundsException(int v, int l, int u) {
super("value " + v + " is out of bounds [" + l + "," + u + "]");
}
}
class BoundedInt {
private int value;
private int lower;
private int upper;
public BoundedInt(int l, int u) {
lower = Math.min(l, u);
upper = Math.max(l, u);
}
private boolean checkBounds(int v) {
return (v >= this.lower) && (v <= this.upper);
}
public void assign(BoundedInt i) throws BoundedIntOutOfBoundsException {{
assign(i.value());
}
public void assign(int v) throws BoundedIntOutOfBoundsException {
if ( checkBounds(v) ) {
this.value = v;
} else {
throw new BoundedIntOutOfBoundsException(v, this.lower, this.upper);
}
}
public int add(BoundedInt i) throws BoundedIntOutOfBoundsException {
return add(i.value());
}
public int add(int i) throws BoundedIntOutOfBoundsException {
if ( checkBounds(this.value + i) ) {
this.value += i;
} else {
throw new BoundedIntOutOfBoundsException(this.value + i, this.lower, this.upper);
}
return this.value;
}
public int value() {
return this.value;
}
}
public class Bounded {
public static void main(String[] args) throws BoundedIntOutOfBoundsException {
BoundedInt a = new BoundedInt(1, 10);
BoundedInt b = new BoundedInt(1, 10);
a.assign(6);
try {
b.assign(12);
} catch (Exception e) {
System.out.println(e.getMessage());
}
b.assign(9);
try {
a.add(b.value());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | def penrose(depth):
print( <g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)">
<use href="
<use href="
</g>
<g id="B{d+1}">
<use href="
<use href="
</g> <g id="G">
<use href="
<use href="
</g>
</defs>
<g transform="scale(2, 2)">
<use href="
<use href="
<use href="
<use href="
<use href="
</g>
</svg>''')
penrose(6)
| import java.awt.*;
import java.util.List;
import java.awt.geom.Path2D;
import java.util.*;
import javax.swing.*;
import static java.lang.Math.*;
import static java.util.stream.Collectors.toList;
public class PenroseTiling extends JPanel {
class Tile {
double x, y, angle, size;
Type type;
Tile(Type t, double x, double y, double a, double s) {
type = t;
this.x = x;
this.y = y;
angle = a;
size = s;
}
@Override
public boolean equals(Object o) {
if (o instanceof Tile) {
Tile t = (Tile) o;
return type == t.type && x == t.x && y == t.y && angle == t.angle;
}
return false;
}
}
enum Type {
Kite, Dart
}
static final double G = (1 + sqrt(5)) / 2;
static final double T = toRadians(36);
List<Tile> tiles = new ArrayList<>();
public PenroseTiling() {
int w = 700, h = 450;
setPreferredSize(new Dimension(w, h));
setBackground(Color.white);
tiles = deflateTiles(setupPrototiles(w, h), 5);
}
List<Tile> setupPrototiles(int w, int h) {
List<Tile> proto = new ArrayList<>();
for (double a = PI / 2 + T; a < 3 * PI; a += 2 * T)
proto.add(new Tile(Type.Kite, w / 2, h / 2, a, w / 2.5));
return proto;
}
List<Tile> deflateTiles(List<Tile> tls, int generation) {
if (generation <= 0)
return tls;
List<Tile> next = new ArrayList<>();
for (Tile tile : tls) {
double x = tile.x, y = tile.y, a = tile.angle, nx, ny;
double size = tile.size / G;
if (tile.type == Type.Dart) {
next.add(new Tile(Type.Kite, x, y, a + 5 * T, size));
for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {
nx = x + cos(a - 4 * T * sign) * G * tile.size;
ny = y - sin(a - 4 * T * sign) * G * tile.size;
next.add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));
}
} else {
for (int i = 0, sign = 1; i < 2; i++, sign *= -1) {
next.add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));
nx = x + cos(a - T * sign) * G * tile.size;
ny = y - sin(a - T * sign) * G * tile.size;
next.add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));
}
}
}
tls = next.stream().distinct().collect(toList());
return deflateTiles(tls, generation - 1);
}
void drawTiles(Graphics2D g) {
double[][] dist = {{G, G, G}, {-G, -1, -G}};
for (Tile tile : tiles) {
double angle = tile.angle - T;
Path2D path = new Path2D.Double();
path.moveTo(tile.x, tile.y);
int ord = tile.type.ordinal();
for (int i = 0; i < 3; i++) {
double x = tile.x + dist[ord][i] * tile.size * cos(angle);
double y = tile.y - dist[ord][i] * tile.size * sin(angle);
path.lineTo(x, y);
angle += T;
}
path.closePath();
g.setColor(ord == 0 ? Color.orange : Color.yellow);
g.fill(path);
g.setColor(Color.darkGray);
g.draw(path);
}
}
@Override
public void paintComponent(Graphics og) {
super.paintComponent(og);
Graphics2D g = (Graphics2D) og;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawTiles(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Penrose Tiling");
f.setResizable(false);
f.add(new PenroseTiling(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. |
from sympy import factorint
sphenics1m, sphenic_triplets1m = [], []
for i in range(3, 1_000_000):
d = factorint(i)
if len(d) == 3 and sum(d.values()) == 3:
sphenics1m.append(i)
if len(sphenics1m) > 2 and i - sphenics1m[-3] == 2 and i - sphenics1m[-2] == 1:
sphenic_triplets1m.append(i)
print('Sphenic numbers less than 1000:')
for i, n in enumerate(sphenics1m):
if n < 1000:
print(f'{n : 5}', end='\n' if (i + 1) % 15 == 0 else '')
else:
break
print('\n\nSphenic triplets less than 10_000:')
for i, n in enumerate(sphenic_triplets1m):
if n < 10_000:
print(f'({n - 2} {n - 1} {n})', end='\n' if (i + 1) % 3 == 0 else ' ')
else:
break
print('\nThere are', len(sphenics1m), 'sphenic numbers and', len(sphenic_triplets1m),
'sphenic triplets less than 1 million.')
S2HK = sphenics1m[200_000 - 1]
T5K = sphenic_triplets1m[5000 - 1]
print(f'The 200_000th sphenic number is {S2HK}, with prime factors {list(factorint(S2HK).keys())}.')
print(f'The 5000th sphenic triplet is ({T5K - 2} {T5K - 1} {T5K}).')
| import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class SphenicNumbers {
public static void main(String[] args) {
final int limit = 1000000;
final int imax = limit / 6;
boolean[] sieve = primeSieve(imax + 1);
boolean[] sphenic = new boolean[limit + 1];
for (int i = 0; i <= imax; ++i) {
if (!sieve[i])
continue;
int jmax = Math.min(imax, limit / (i * i));
if (jmax <= i)
break;
for (int j = i + 1; j <= jmax; ++j) {
if (!sieve[j])
continue;
int p = i * j;
int kmax = Math.min(imax, limit / p);
if (kmax <= j)
break;
for (int k = j + 1; k <= kmax; ++k) {
if (!sieve[k])
continue;
assert(p * k <= limit);
sphenic[p * k] = true;
}
}
}
System.out.println("Sphenic numbers < 1000:");
for (int i = 0, n = 0; i < 1000; ++i) {
if (!sphenic[i])
continue;
++n;
System.out.printf("%3d%c", i, n % 15 == 0 ? '\n' : ' ');
}
System.out.println("\nSphenic triplets < 10,000:");
for (int i = 0, n = 0; i < 10000; ++i) {
if (i > 1 && sphenic[i] && sphenic[i - 1] && sphenic[i - 2]) {
++n;
System.out.printf("(%d, %d, %d)%c",
i - 2, i - 1, i, n % 3 == 0 ? '\n' : ' ');
}
}
int count = 0, triplets = 0, s200000 = 0, t5000 = 0;
for (int i = 0; i < limit; ++i) {
if (!sphenic[i])
continue;
++count;
if (count == 200000)
s200000 = i;
if (i > 1 && sphenic[i - 1] && sphenic[i - 2]) {
++triplets;
if (triplets == 5000)
t5000 = i;
}
}
System.out.printf("\nNumber of sphenic numbers < 1,000,000: %d\n", count);
System.out.printf("Number of sphenic triplets < 1,000,000: %d\n", triplets);
List<Integer> factors = primeFactors(s200000);
assert(factors.size() == 3);
System.out.printf("The 200,000th sphenic number: %d = %d * %d * %d\n",
s200000, factors.get(0), factors.get(1),
factors.get(2));
System.out.printf("The 5,000th sphenic triplet: (%d, %d, %d)\n",
t5000 - 2, t5000 - 1, t5000);
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
private static List<Integer> primeFactors(int n) {
List<Integer> factors = new ArrayList<>();
if (n > 1 && (n & 1) == 0) {
factors.add(2);
while ((n & 1) == 0)
n >>= 1;
}
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0) {
factors.add(p);
while (n % p == 0)
n /= p;
}
}
if (n > 1)
factors.add(n);
return factors;
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | from __future__ import print_function
import os
import hashlib
import datetime
def FindDuplicateFiles(pth, minSize = 0, hashName = "md5"):
knownFiles = {}
for root, dirs, files in os.walk(pth):
for fina in files:
fullFina = os.path.join(root, fina)
isSymLink = os.path.islink(fullFina)
if isSymLink:
continue
si = os.path.getsize(fullFina)
if si < minSize:
continue
if si not in knownFiles:
knownFiles[si] = {}
h = hashlib.new(hashName)
h.update(open(fullFina, "rb").read())
hashed = h.digest()
if hashed in knownFiles[si]:
fileRec = knownFiles[si][hashed]
fileRec.append(fullFina)
else:
knownFiles[si][hashed] = [fullFina]
sizeList = list(knownFiles.keys())
sizeList.sort(reverse=True)
for si in sizeList:
filesAtThisSize = knownFiles[si]
for hashVal in filesAtThisSize:
if len(filesAtThisSize[hashVal]) < 2:
continue
fullFinaLi = filesAtThisSize[hashVal]
print ("=======Duplicate=======")
for fullFina in fullFinaLi:
st = os.stat(fullFina)
isHardLink = st.st_nlink > 1
infoStr = []
if isHardLink:
infoStr.append("(Hard linked)")
fmtModTime = datetime.datetime.utcfromtimestamp(st.st_mtime).strftime('%Y-%m-%dT%H:%M:%SZ')
print (fmtModTime, si, os.path.relpath(fullFina, pth), " ".join(infoStr))
if __name__=="__main__":
FindDuplicateFiles('/home/tim/Dropbox', 1024*1024)
| import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.security.*;
import java.util.*;
public class DuplicateFiles {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Directory name and minimum file size are required.");
System.exit(1);
}
try {
findDuplicateFiles(args[0], Long.parseLong(args[1]));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void findDuplicateFiles(String directory, long minimumSize)
throws IOException, NoSuchAlgorithmException {
System.out.println("Directory: '" + directory + "', minimum size: " + minimumSize + " bytes.");
Path path = FileSystems.getDefault().getPath(directory);
FileVisitor visitor = new FileVisitor(path, minimumSize);
Files.walkFileTree(path, visitor);
System.out.println("The following sets of files have the same size and checksum:");
for (Map.Entry<FileKey, Map<Object, List<String>>> e : visitor.fileMap_.entrySet()) {
Map<Object, List<String>> map = e.getValue();
if (!containsDuplicates(map))
continue;
List<List<String>> fileSets = new ArrayList<>(map.values());
for (List<String> files : fileSets)
Collections.sort(files);
Collections.sort(fileSets, new StringListComparator());
FileKey key = e.getKey();
System.out.println();
System.out.println("Size: " + key.size_ + " bytes");
for (List<String> files : fileSets) {
for (int i = 0, n = files.size(); i < n; ++i) {
if (i > 0)
System.out.print(" = ");
System.out.print(files.get(i));
}
System.out.println();
}
}
}
private static class StringListComparator implements Comparator<List<String>> {
public int compare(List<String> a, List<String> b) {
int len1 = a.size(), len2 = b.size();
for (int i = 0; i < len1 && i < len2; ++i) {
int c = a.get(i).compareTo(b.get(i));
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
private static boolean containsDuplicates(Map<Object, List<String>> map) {
if (map.size() > 1)
return true;
for (List<String> files : map.values()) {
if (files.size() > 1)
return true;
}
return false;
}
private static class FileVisitor extends SimpleFileVisitor<Path> {
private MessageDigest digest_;
private Path directory_;
private long minimumSize_;
private Map<FileKey, Map<Object, List<String>>> fileMap_ = new TreeMap<>();
private FileVisitor(Path directory, long minimumSize) throws NoSuchAlgorithmException {
directory_ = directory;
minimumSize_ = minimumSize;
digest_ = MessageDigest.getInstance("MD5");
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (attrs.size() >= minimumSize_) {
FileKey key = new FileKey(file, attrs, getMD5Sum(file));
Map<Object, List<String>> map = fileMap_.get(key);
if (map == null)
fileMap_.put(key, map = new HashMap<>());
List<String> files = map.get(attrs.fileKey());
if (files == null)
map.put(attrs.fileKey(), files = new ArrayList<>());
Path relative = directory_.relativize(file);
files.add(relative.toString());
}
return FileVisitResult.CONTINUE;
}
private byte[] getMD5Sum(Path file) throws IOException {
digest_.reset();
try (InputStream in = new FileInputStream(file.toString())) {
byte[] buffer = new byte[8192];
int bytes;
while ((bytes = in.read(buffer)) != -1) {
digest_.update(buffer, 0, bytes);
}
}
return digest_.digest();
}
}
private static class FileKey implements Comparable<FileKey> {
private byte[] hash_;
private long size_;
private FileKey(Path file, BasicFileAttributes attrs, byte[] hash) throws IOException {
size_ = attrs.size();
hash_ = hash;
}
public int compareTo(FileKey other) {
int c = Long.compare(other.size_, size_);
if (c == 0)
c = hashCompare(hash_, other.hash_);
return c;
}
}
private static int hashCompare(byte[] a, byte[] b) {
int len1 = a.length, len2 = b.length;
for (int i = 0; i < len1 && i < len2; ++i) {
int c = Byte.compare(a[i], b[i]);
if (c != 0)
return c;
}
return Integer.compare(len1, len2);
}
}
|
Write the same code in Java as shown below in Python. | from sys import stdout
moves = [
[-1, -2], [1, -2], [-1, 2], [1, 2],
[-2, -1], [-2, 1], [2, -1], [2, 1]
]
def solve(pz, sz, sx, sy, idx, cnt):
if idx > cnt:
return 1
for i in range(len(moves)):
x = sx + moves[i][0]
y = sy + moves[i][1]
if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:
pz[x][y] = idx
if 1 == solve(pz, sz, x, y, idx + 1, cnt):
return 1
pz[x][y] = 0
return 0
def find_solution(pz, sz):
p = [[-1 for j in range(sz)] for i in range(sz)]
idx = x = y = cnt = 0
for j in range(sz):
for i in range(sz):
if pz[idx] == "x":
p[i][j] = 0
cnt += 1
elif pz[idx] == "s":
p[i][j] = 1
cnt += 1
x = i
y = j
idx += 1
if 1 == solve(p, sz, x, y, 2, cnt):
for j in range(sz):
for i in range(sz):
if p[i][j] != -1:
stdout.write(" {:0{}d}".format(p[i][j], 2))
else:
stdout.write(" ")
print()
else:
print("Cannot solve this puzzle!")
find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8)
print()
find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
| import java.util.*;
public class HolyKnightsTour {
final static String[] board = {
" xxx ",
" x xx ",
" xxxxxxx",
"xxx x x",
"x x xxx",
"1xxxxxx ",
" xx x ",
" xxx "};
private final static int base = 12;
private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},
{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};
private static int[][] grid;
private static int total = 2;
public static void main(String[] args) {
int row = 0, col = 0;
grid = new int[base][base];
for (int r = 0; r < base; r++) {
Arrays.fill(grid[r], -1);
for (int c = 2; c < base - 2; c++) {
if (r >= 2 && r < base - 2) {
if (board[r - 2].charAt(c - 2) == 'x') {
grid[r][c] = 0;
total++;
}
if (board[r - 2].charAt(c - 2) == '1') {
row = r;
col = c;
}
}
}
}
grid[row][col] = 1;
if (solve(row, col, 2))
printResult();
}
private static boolean solve(int r, int c, int count) {
if (count == total)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != total)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
private static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
private static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
private static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from sys import stdout
moves = [
[-1, -2], [1, -2], [-1, 2], [1, 2],
[-2, -1], [-2, 1], [2, -1], [2, 1]
]
def solve(pz, sz, sx, sy, idx, cnt):
if idx > cnt:
return 1
for i in range(len(moves)):
x = sx + moves[i][0]
y = sy + moves[i][1]
if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:
pz[x][y] = idx
if 1 == solve(pz, sz, x, y, idx + 1, cnt):
return 1
pz[x][y] = 0
return 0
def find_solution(pz, sz):
p = [[-1 for j in range(sz)] for i in range(sz)]
idx = x = y = cnt = 0
for j in range(sz):
for i in range(sz):
if pz[idx] == "x":
p[i][j] = 0
cnt += 1
elif pz[idx] == "s":
p[i][j] = 1
cnt += 1
x = i
y = j
idx += 1
if 1 == solve(p, sz, x, y, 2, cnt):
for j in range(sz):
for i in range(sz):
if p[i][j] != -1:
stdout.write(" {:0{}d}".format(p[i][j], 2))
else:
stdout.write(" ")
print()
else:
print("Cannot solve this puzzle!")
find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8)
print()
find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
| import java.util.*;
public class HolyKnightsTour {
final static String[] board = {
" xxx ",
" x xx ",
" xxxxxxx",
"xxx x x",
"x x xxx",
"1xxxxxx ",
" xx x ",
" xxx "};
private final static int base = 12;
private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},
{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};
private static int[][] grid;
private static int total = 2;
public static void main(String[] args) {
int row = 0, col = 0;
grid = new int[base][base];
for (int r = 0; r < base; r++) {
Arrays.fill(grid[r], -1);
for (int c = 2; c < base - 2; c++) {
if (r >= 2 && r < base - 2) {
if (board[r - 2].charAt(c - 2) == 'x') {
grid[r][c] = 0;
total++;
}
if (board[r - 2].charAt(c - 2) == '1') {
row = r;
col = c;
}
}
}
}
grid[row][col] = 1;
if (solve(row, col, 2))
printResult();
}
private static boolean solve(int r, int c, int count) {
if (count == total)
return true;
List<int[]> nbrs = neighbors(r, c);
if (nbrs.isEmpty() && count != total)
return false;
Collections.sort(nbrs, (a, b) -> a[2] - b[2]);
for (int[] nb : nbrs) {
r = nb[0];
c = nb[1];
grid[r][c] = count;
if (solve(r, c, count + 1))
return true;
grid[r][c] = 0;
}
return false;
}
private static List<int[]> neighbors(int r, int c) {
List<int[]> nbrs = new ArrayList<>();
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[r + y][c + x] == 0) {
int num = countNeighbors(r + y, c + x) - 1;
nbrs.add(new int[]{r + y, c + x, num});
}
}
return nbrs;
}
private static int countNeighbors(int r, int c) {
int num = 0;
for (int[] m : moves)
if (grid[r + m[1]][c + m[0]] == 0)
num++;
return num;
}
private static void printResult() {
for (int[] row : grid) {
for (int i : row) {
if (i == -1)
System.out.printf("%2s ", ' ');
else
System.out.printf("%2d ", i);
}
System.out.println();
}
}
}
|
Change the following Python code into Java without altering its purpose. | from __future__ import print_function
def order_disjoint_list_items(data, items):
itemindices = []
for item in set(items):
itemcount = items.count(item)
lastindex = [-1]
for i in range(itemcount):
lastindex.append(data.index(item, lastindex[-1] + 1))
itemindices += lastindex[1:]
itemindices.sort()
for index, item in zip(itemindices, items):
data[index] = item
if __name__ == '__main__':
tostring = ' '.join
for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),
(str.split('the cat sat on the mat'), str.split('cat mat')),
(list('ABCABCABC'), list('CACA')),
(list('ABCABDABE'), list('EADA')),
(list('AB'), list('B')),
(list('AB'), list('BA')),
(list('ABBA'), list('BA')),
(list(''), list('')),
(list('A'), list('A')),
(list('AB'), list('')),
(list('ABBA'), list('AB')),
(list('ABAB'), list('AB')),
(list('ABAB'), list('BABA')),
(list('ABCCBA'), list('ACAC')),
(list('ABCCBA'), list('CACA')),
]:
print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')
order_disjoint_list_items(data, items)
print("-> M' %r" % tostring(data))
| import java.util.Arrays;
import java.util.BitSet;
import org.apache.commons.lang3.ArrayUtils;
public class OrderDisjointItems {
public static void main(String[] args) {
final String[][] MNs = {{"the cat sat on the mat", "mat cat"},
{"the cat sat on the mat", "cat mat"},
{"A B C A B C A B C", "C A C A"}, {"A B C A B D A B E", "E A D A"},
{"A B", "B"}, {"A B", "B A"}, {"A B B A", "B A"}, {"X X Y", "X"}};
for (String[] a : MNs) {
String[] r = orderDisjointItems(a[0].split(" "), a[1].split(" "));
System.out.printf("%s | %s -> %s%n", a[0], a[1], Arrays.toString(r));
}
}
static String[] orderDisjointItems(String[] m, String[] n) {
for (String e : n) {
int idx = ArrayUtils.indexOf(m, e);
if (idx != -1)
m[idx] = null;
}
for (int i = 0, j = 0; i < m.length; i++) {
if (m[i] == null)
m[i] = n[j++];
}
return m;
}
static String[] orderDisjointItems2(String[] m, String[] n) {
BitSet bitSet = new BitSet(m.length);
for (String e : n) {
int idx = -1;
do {
idx = ArrayUtils.indexOf(m, e, idx + 1);
} while (idx != -1 && bitSet.get(idx));
if (idx != -1)
bitSet.set(idx);
}
for (int i = 0, j = 0; i < m.length; i++) {
if (bitSet.get(i))
m[i] = n[j++];
}
return m;
}
}
|
Change the following Python code into Java without altering its purpose. | print()
| package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | print()
| package rosettacode.heredoc;
public class MainApp {
public static void main(String[] args) {
String hereDoc = """
This is a multiline string.
It includes all of this text,
but on separate lines in the code.
""";
System.out.println(hereDoc);
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
for row in hashJoin(table1, 1, table2, 0):
print(row)
| import java.util.*;
public class HashJoin {
public static void main(String[] args) {
String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
{"18", "Popeye"}, {"28", "Alan"}};
String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
{"Bob", "foo"}};
hashJoin(table1, 1, table2, 0).stream()
.forEach(r -> System.out.println(Arrays.deepToString(r)));
}
static List<String[][]> hashJoin(String[][] records1, int idx1,
String[][] records2, int idx2) {
List<String[][]> result = new ArrayList<>();
Map<String, List<String[]>> map = new HashMap<>();
for (String[] record : records1) {
List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
v.add(record);
map.put(record[idx1], v);
}
for (String[] record : records2) {
List<String[]> lst = map.get(record[idx2]);
if (lst != null) {
lst.stream().forEach(r -> {
result.add(new String[][]{r, record});
});
}
}
return result;
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb as hsv
def curve(axiom, rules, angle, depth):
for _ in range(depth):
axiom = ''.join(rules[c] if c in rules else c for c in axiom)
a, x, y = 0, [0], [0]
for c in axiom:
match c:
case '+':
a += 1
case '-':
a -= 1
case 'F' | 'G':
x.append(x[-1] + np.cos(a*angle*np.pi/180))
y.append(y[-1] + np.sin(a*angle*np.pi/180))
l = len(x)
for i in range(l - 1):
plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))
plt.gca().set_aspect(1)
plt.show()
curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
| import java.io.*;
public class SierpinskiCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
SierpinskiCurve s = new SierpinskiCurve(writer);
s.currentAngle = 45;
s.currentX = 5;
s.currentY = 10;
s.lineLength = 7;
s.begin(545);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
case 'G':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY -= length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F--XF--F--XF";
private static final String PRODUCTION = "XF+G+XF--F--XF+G+X";
private static final int ANGLE = 45;
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb as hsv
def curve(axiom, rules, angle, depth):
for _ in range(depth):
axiom = ''.join(rules[c] if c in rules else c for c in axiom)
a, x, y = 0, [0], [0]
for c in axiom:
match c:
case '+':
a += 1
case '-':
a -= 1
case 'F' | 'G':
x.append(x[-1] + np.cos(a*angle*np.pi/180))
y.append(y[-1] + np.sin(a*angle*np.pi/180))
l = len(x)
for i in range(l - 1):
plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))
plt.gca().set_aspect(1)
plt.show()
curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
| import java.io.*;
public class SierpinskiCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_curve.svg"))) {
SierpinskiCurve s = new SierpinskiCurve(writer);
s.currentAngle = 45;
s.currentX = 5;
s.currentY = 10;
s.lineLength = 7;
s.begin(545);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
case 'G':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY -= length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F--XF--F--XF";
private static final String PRODUCTION = "XF+G+XF--F--XF+G+X";
private static final int ANGLE = 45;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | import collections
def MostFreqKHashing(inputString, K):
occuDict = collections.defaultdict(int)
for c in inputString:
occuDict[c] += 1
occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)
outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])
return outputStr
def MostFreqKSimilarity(inputStr1, inputStr2):
similarity = 0
for i in range(0, len(inputStr1), 2):
c = inputStr1[i]
cnt1 = int(inputStr1[i + 1])
for j in range(0, len(inputStr2), 2):
if inputStr2[j] == c:
cnt2 = int(inputStr2[j + 1])
similarity += cnt1 + cnt2
break
return similarity
def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):
return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
| import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SDF {
public static HashMap<Character, Integer> countElementOcurrences(char[] array) {
HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();
for (char element : array) {
Integer count = countMap.get(element);
count = (count == null) ? 1 : count + 1;
countMap.put(element, count);
}
return countMap;
}
private static <K, V extends Comparable<? super V>>
HashMap<K, V> descendingSortByValues(HashMap<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
HashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
public static String mostOcurrencesElement(char[] array, int k) {
HashMap<Character, Integer> countMap = countElementOcurrences(array);
System.out.println(countMap);
Map<Character, Integer> map = descendingSortByValues(countMap);
System.out.println(map);
int i = 0;
String output = "";
for (Map.Entry<Character, Integer> pairs : map.entrySet()) {
if (i++ >= k)
break;
output += "" + pairs.getKey() + pairs.getValue();
}
return output;
}
public static int getDiff(String str1, String str2, int limit) {
int similarity = 0;
int k = 0;
for (int i = 0; i < str1.length() ; i = k) {
k ++;
if (Character.isLetter(str1.charAt(i))) {
int pos = str2.indexOf(str1.charAt(i));
if (pos >= 0) {
String digitStr1 = "";
while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {
digitStr1 += str1.charAt(k);
k++;
}
int k2 = pos+1;
String digitStr2 = "";
while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {
digitStr2 += str2.charAt(k2);
k2++;
}
similarity += Integer.parseInt(digitStr2)
+ Integer.parseInt(digitStr1);
}
}
}
return Math.abs(limit - similarity);
}
public static int SDFfunc(String str1, String str2, int limit) {
return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);
}
public static void main(String[] args) {
String input1 = "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV";
String input2 = "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG";
System.out.println(SDF.SDFfunc(input1,input2,100));
}
}
|
Write the same code in Java as shown below in Python. |
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
maxscore = 100
maxgames = 100000
Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')
class Player():
def __init__(self, player_index):
self.player_index = player_index
def __repr__(self):
return '%s(%i)' % (self.__class__.__name__, self.player_index)
def __call__(self, safescore, scores, game):
'Returns boolean True to roll again'
pass
class RandPlay(Player):
def __call__(self, safe, scores, game):
'Returns random boolean choice of whether to roll again'
return bool(random.randint(0, 1))
class RollTo20(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and(sum(scores) < 20))
class Desparat(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20 or someone is within 20 of winning'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and( (sum(scores) < 20)
or max(safe) >= (maxscore - 20)))
def game__str__(self):
'Pretty printer for Game class'
return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])"
% (self.players, self.maxscore,
',\n '.join(repr(round) for round in self.rounds)))
Game.__str__ = game__str__
def winningorder(players, safescores):
'Return (players in winning order, their scores)'
return tuple(zip(*sorted(zip(players, safescores),
key=lambda x: x[1], reverse=True)))
def playpig(game):
players, maxscore, rounds = game
playercount = len(players)
safescore = [0] * playercount
player = 0
scores=[]
while max(safescore) < maxscore:
startscore = safescore[player]
rolling = players[player](safescore, scores, game)
if rolling:
rolled = randint(1, 6)
scores.append(rolled)
if rolled == 1:
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
scores, player = [], (player + 1) % playercount
else:
safescore[player] += sum(scores)
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
if safescore[player] >= maxscore:
break
scores, player = [], (player + 1) % playercount
return winningorder(players, safescore)
if __name__ == '__main__':
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=20,
rounds=[])
print('ONE GAME')
print('Winning order: %r; Respective scores: %r\n' % playpig(game))
print(game)
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=maxscore,
rounds=[])
algos = (RollTo20, RandPlay, Desparat)
print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES'
% (', '.join(p.__name__ for p in algos), maxgames,))
winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)
for i in range(playercount)),
rounds=[]))[0])
for i in range(maxgames))
print(' Players(position) winning on left; occurrences on right:\n %s'
% ',\n '.join(str(w) for w in winners.most_common()))
| import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. |
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
maxscore = 100
maxgames = 100000
Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')
class Player():
def __init__(self, player_index):
self.player_index = player_index
def __repr__(self):
return '%s(%i)' % (self.__class__.__name__, self.player_index)
def __call__(self, safescore, scores, game):
'Returns boolean True to roll again'
pass
class RandPlay(Player):
def __call__(self, safe, scores, game):
'Returns random boolean choice of whether to roll again'
return bool(random.randint(0, 1))
class RollTo20(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and(sum(scores) < 20))
class Desparat(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20 or someone is within 20 of winning'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and( (sum(scores) < 20)
or max(safe) >= (maxscore - 20)))
def game__str__(self):
'Pretty printer for Game class'
return ("Game(players=%r, maxscore=%i,\n rounds=[\n %s\n ])"
% (self.players, self.maxscore,
',\n '.join(repr(round) for round in self.rounds)))
Game.__str__ = game__str__
def winningorder(players, safescores):
'Return (players in winning order, their scores)'
return tuple(zip(*sorted(zip(players, safescores),
key=lambda x: x[1], reverse=True)))
def playpig(game):
players, maxscore, rounds = game
playercount = len(players)
safescore = [0] * playercount
player = 0
scores=[]
while max(safescore) < maxscore:
startscore = safescore[player]
rolling = players[player](safescore, scores, game)
if rolling:
rolled = randint(1, 6)
scores.append(rolled)
if rolled == 1:
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
scores, player = [], (player + 1) % playercount
else:
safescore[player] += sum(scores)
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
if safescore[player] >= maxscore:
break
scores, player = [], (player + 1) % playercount
return winningorder(players, safescore)
if __name__ == '__main__':
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=20,
rounds=[])
print('ONE GAME')
print('Winning order: %r; Respective scores: %r\n' % playpig(game))
print(game)
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=maxscore,
rounds=[])
algos = (RollTo20, RandPlay, Desparat)
print('\n\nMULTIPLE STATISTICS using %r\n for %i GAMES'
% (', '.join(p.__name__ for p in algos), maxgames,))
winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)
for i in range(playercount)),
rounds=[]))[0])
for i in range(maxgames))
print(' Players(position) winning on left; occurrences on right:\n %s'
% ',\n '.join(str(w) for w in winners.most_common()))
| import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0;
while(true) {
System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if(nextInt > 0) {
players = nextInt;
break;
}
}
else {
System.out.println("That wasn't an integer. Try again. \n");
scan.next();
}
}
System.out.println("Alright, starting with " + players + " players. \n");
play(players, scan);
scan.close();
}
public static void play(int group, Scanner scan) {
final int STRATEGIES = 5;
Dice dice = new Dice();
Player[] players = new Player[group];
for(int count = 0; count < group; count++) {
players[count] = new Player(count);
System.out.println("Player " + players[count].getNumber() + " is alive! ");
}
System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
System.out.println(">> Enter '0' for a human player. ");
System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");
for(Player player : players) {
System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");
while(true) {
if(scan.hasNextInt()) {
int nextInt = scan.nextInt();
if (nextInt < Strategy.STRATEGIES.length) {
player.setStrategy(Strategy.STRATEGIES[nextInt]);
break;
}
}
else {
System.out.println("That wasn't an option. Try again. ");
scan.next();
}
}
}
int max = 0;
while(max < 100) {
for(Player player : players) {
System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");
player.setTurnPoints(0);
player.setMax(max);
while(true) {
Move choice = player.choose();
if(choice == Move.ROLL) {
int roll = dice.roll();
System.out.println(" A " + roll + " was rolled. ");
player.setTurnPoints(player.getTurnPoints() + roll);
player.incIter();
if(roll == 1) {
player.setTurnPoints(0);
break;
}
}
else {
System.out.println(" The player has held. ");
break;
}
}
player.addPoints(player.getTurnPoints());
System.out.println(" Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");
player.resetIter();
if(max < player.getPoints()) {
max = player.getPoints();
}
if(max >= 100) {
System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");
for(Player p : players) {
System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
}
break;
}
}
}
}
}
|
Translate the given Python code snippet into Java without altering its behavior. | from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
def reverse_int(num):
return int(str(num)[::-1])
def split_roots_from_relateds(roots_and_relateds):
roots = roots_and_relateds[::]
i = 1
while i < len(roots):
this = roots[i]
if any(this.intersection(prev) for prev in roots[:i]):
del roots[i]
else:
i += 1
root = [min(each_set) for each_set in roots]
related = [min(each_set) for each_set in roots_and_relateds]
related = [n for n in related if n not in root]
return root, related
def find_lychrel(maxn, max_reversions):
'Lychrel number generator'
series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]
roots_and_relateds = [s for s in series if len(s) > max_reversions]
return split_roots_from_relateds(roots_and_relateds)
if __name__ == '__main__':
maxn, reversion_limit = 10000, 500
print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds"
% (maxn, reversion_limit))
lychrel, l_related = find_lychrel(maxn, reversion_limit)
print(' Number of Lychrel numbers:', len(lychrel))
print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel))
print(' Number of Lychrel related:', len(l_related))
pals = [x for x in lychrel + l_related if x == reverse_int(x)]
print(' Number of Lychrel palindromes:', len(pals))
print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
| import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
def reverse_int(num):
return int(str(num)[::-1])
def split_roots_from_relateds(roots_and_relateds):
roots = roots_and_relateds[::]
i = 1
while i < len(roots):
this = roots[i]
if any(this.intersection(prev) for prev in roots[:i]):
del roots[i]
else:
i += 1
root = [min(each_set) for each_set in roots]
related = [min(each_set) for each_set in roots_and_relateds]
related = [n for n in related if n not in root]
return root, related
def find_lychrel(maxn, max_reversions):
'Lychrel number generator'
series = [add_reverse(n, max_reversions*2) for n in range(1, maxn + 1)]
roots_and_relateds = [s for s in series if len(s) > max_reversions]
return split_roots_from_relateds(roots_and_relateds)
if __name__ == '__main__':
maxn, reversion_limit = 10000, 500
print("Calculations using n = 1..%i and limiting each search to 2*%i reverse-digits-and-adds"
% (maxn, reversion_limit))
lychrel, l_related = find_lychrel(maxn, reversion_limit)
print(' Number of Lychrel numbers:', len(lychrel))
print(' Lychrel numbers:', ', '.join(str(n) for n in lychrel))
print(' Number of Lychrel related:', len(l_related))
pals = [x for x in lychrel + l_related if x == reverse_int(x)]
print(' Number of Lychrel palindromes:', len(pals))
print(' Lychrel palindromes:', ', '.join(str(n) for n in pals))
| import java.math.BigInteger;
import java.util.*;
public class Lychrel {
static Map<BigInteger, Tuple> cache = new HashMap<>();
static class Tuple {
final Boolean flag;
final BigInteger bi;
Tuple(boolean f, BigInteger b) {
flag = f;
bi = b;
}
}
static BigInteger rev(BigInteger bi) {
String s = new StringBuilder(bi.toString()).reverse().toString();
return new BigInteger(s);
}
static Tuple lychrel(BigInteger n) {
Tuple res;
if ((res = cache.get(n)) != null)
return res;
BigInteger r = rev(n);
res = new Tuple(true, n);
List<BigInteger> seen = new ArrayList<>();
for (int i = 0; i < 500; i++) {
n = n.add(r);
r = rev(n);
if (n.equals(r)) {
res = new Tuple(false, BigInteger.ZERO);
break;
}
if (cache.containsKey(n)) {
res = cache.get(n);
break;
}
seen.add(n);
}
for (BigInteger bi : seen)
cache.put(bi, res);
return res;
}
public static void main(String[] args) {
List<BigInteger> seeds = new ArrayList<>();
List<BigInteger> related = new ArrayList<>();
List<BigInteger> palin = new ArrayList<>();
for (int i = 1; i <= 10_000; i++) {
BigInteger n = BigInteger.valueOf(i);
Tuple t = lychrel(n);
if (!t.flag)
continue;
if (n.equals(t.bi))
seeds.add(t.bi);
else
related.add(t.bi);
if (n.equals(t.bi))
palin.add(t.bi);
}
System.out.printf("%d Lychrel seeds: %s%n", seeds.size(), seeds);
System.out.printf("%d Lychrel related%n", related.size());
System.out.printf("%d Lychrel palindromes: %s%n", palin.size(), palin);
}
}
|
Keep all operations the same but rewrite the snippet in Java. | import matplotlib.pyplot as plt
import math
def nextPoint(x, y, angle):
a = math.pi * angle / 180
x2 = (int)(round(x + (1 * math.cos(a))))
y2 = (int)(round(y + (1 * math.sin(a))))
return x2, y2
def expand(axiom, rules, level):
for l in range(0, level):
a2 = ""
for c in axiom:
if c in rules:
a2 += rules[c]
else:
a2 += c
axiom = a2
return axiom
def draw_lsystem(axiom, rules, angle, iterations):
xp = [1]
yp = [1]
direction = 0
for c in expand(axiom, rules, iterations):
if c == "F":
xn, yn = nextPoint(xp[-1], yp[-1], direction)
xp.append(xn)
yp.append(yn)
elif c == "-":
direction = direction - angle
if direction < 0:
direction = 360 + direction
elif c == "+":
direction = (direction + angle) % 360
plt.plot(xp, yp)
plt.show()
if __name__ == '__main__':
s_axiom = "F+XF+F+XF"
s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"}
s_angle = 90
draw_lsystem(s_axiom, s_rules, s_angle, 3)
| import java.io.*;
public class SierpinskiSquareCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) {
SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);
int size = 635, length = 5;
s.currentAngle = 0;
s.currentX = (size - length)/2;
s.currentY = length;
s.lineLength = length;
s.begin(size);
s.execute(rewrite(5));
s.end();
} catch (final Exception ex) {
ex.printStackTrace();
}
}
private SierpinskiSquareCurve(final Writer writer) {
this.writer = writer;
}
private void begin(final int size) throws IOException {
write("<svg xmlns='http:
write("<rect width='100%%' height='100%%' fill='white'/>\n");
write("<path stroke-width='1' stroke='black' fill='none' d='");
}
private void end() throws IOException {
write("'/>\n</svg>\n");
}
private void execute(final String s) throws IOException {
write("M%g,%g\n", currentX, currentY);
for (int i = 0, n = s.length(); i < n; ++i) {
switch (s.charAt(i)) {
case 'F':
line(lineLength);
break;
case '+':
turn(ANGLE);
break;
case '-':
turn(-ANGLE);
break;
}
}
}
private void line(final double length) throws IOException {
final double theta = (Math.PI * currentAngle) / 180.0;
currentX += length * Math.cos(theta);
currentY += length * Math.sin(theta);
write("L%g,%g\n", currentX, currentY);
}
private void turn(final int angle) {
currentAngle = (currentAngle + angle) % 360;
}
private void write(final String format, final Object... args) throws IOException {
writer.write(String.format(format, args));
}
private static String rewrite(final int order) {
String s = AXIOM;
for (int i = 0; i < order; ++i) {
final StringBuilder sb = new StringBuilder();
for (int j = 0, n = s.length(); j < n; ++j) {
final char ch = s.charAt(j);
if (ch == 'X')
sb.append(PRODUCTION);
else
sb.append(ch);
}
s = sb.toString();
}
return s;
}
private final Writer writer;
private double lineLength;
private double currentX;
private double currentY;
private int currentAngle;
private static final String AXIOM = "F+XF+F+XF";
private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X";
private static final int ANGLE = 90;
}
|
Write the same algorithm in Java as shown in this Python implementation. | from primesieve import primes
import math
def primepowers(k, upper_bound):
ub = int(math.pow(upper_bound, 1/k) + .5)
res = [(1,)]
for p in primes(ub):
a = [p**k]
u = upper_bound // a[-1]
while u >= p:
a.append(a[-1]*p)
u //= p
res.append(tuple(a))
return res
def kpowerful(k, upper_bound, count_only=True):
ps = primepowers(k, upper_bound)
def accu(i, ub):
c = 0 if count_only else []
for p in ps[i]:
u = ub//p
if not u: break
c += 1 if count_only else [p]
for j in range(i + 1, len(ps)):
if u < ps[j][0]:
break
c += accu(j, u) if count_only else [p*x for x in accu(j, u)]
return c
res = accu(0, upper_bound)
return res if count_only else sorted(res)
for k in range(2, 11):
res = kpowerful(k, 10**k, count_only=False)
print(f'{len(res)} {k}-powerfuls up to 10^{k}:',
' '.join(str(x) for x in res[:5]),
'...',
' '.join(str(x) for x in res[-5:])
)
for k in range(2, 11):
res = [kpowerful(k, 10**n) for n in range(k+10)]
print(f'{k}-powerful up to 10^{k+10}:',
' '.join(str(x) for x in res))
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
|
Preserve the algorithm and functionality while converting the code from Python to Java. | from primesieve import primes
import math
def primepowers(k, upper_bound):
ub = int(math.pow(upper_bound, 1/k) + .5)
res = [(1,)]
for p in primes(ub):
a = [p**k]
u = upper_bound // a[-1]
while u >= p:
a.append(a[-1]*p)
u //= p
res.append(tuple(a))
return res
def kpowerful(k, upper_bound, count_only=True):
ps = primepowers(k, upper_bound)
def accu(i, ub):
c = 0 if count_only else []
for p in ps[i]:
u = ub//p
if not u: break
c += 1 if count_only else [p]
for j in range(i + 1, len(ps)):
if u < ps[j][0]:
break
c += accu(j, u) if count_only else [p*x for x in accu(j, u)]
return c
res = accu(0, upper_bound)
return res if count_only else sorted(res)
for k in range(2, 11):
res = kpowerful(k, 10**k, count_only=False)
print(f'{len(res)} {k}-powerfuls up to 10^{k}:',
' '.join(str(x) for x in res[:5]),
'...',
' '.join(str(x) for x in res[-5:])
)
for k in range(2, 11):
res = [kpowerful(k, 10**n) for n in range(k+10)]
print(f'{k}-powerful up to 10^{k+10}:',
' '.join(str(x) for x in res))
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
|
Generate an equivalent Java version of this Python code. | from primesieve import primes
import math
def primepowers(k, upper_bound):
ub = int(math.pow(upper_bound, 1/k) + .5)
res = [(1,)]
for p in primes(ub):
a = [p**k]
u = upper_bound // a[-1]
while u >= p:
a.append(a[-1]*p)
u //= p
res.append(tuple(a))
return res
def kpowerful(k, upper_bound, count_only=True):
ps = primepowers(k, upper_bound)
def accu(i, ub):
c = 0 if count_only else []
for p in ps[i]:
u = ub//p
if not u: break
c += 1 if count_only else [p]
for j in range(i + 1, len(ps)):
if u < ps[j][0]:
break
c += accu(j, u) if count_only else [p*x for x in accu(j, u)]
return c
res = accu(0, upper_bound)
return res if count_only else sorted(res)
for k in range(2, 11):
res = kpowerful(k, 10**k, count_only=False)
print(f'{len(res)} {k}-powerfuls up to 10^{k}:',
' '.join(str(x) for x in res[:5]),
'...',
' '.join(str(x) for x in res[-5:])
)
for k in range(2, 11):
res = [kpowerful(k, 10**n) for n in range(k+10)]
print(f'{k}-powerful up to 10^{k+10}:',
' '.join(str(x) for x in res))
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PowerfulNumbers {
public static void main(String[] args) {
System.out.printf("Task: For k = 2..10, generate the set of k-powerful numbers <= 10^k and show the first 5 and the last 5 terms, along with the length of the set%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
BigInteger max = BigInteger.valueOf(10).pow(k);
List<BigInteger> powerfulNumbers = getPowerFulNumbers(max, k);
System.out.printf("There are %d %d-powerful numbers between 1 and %d. %nList: %s%n", powerfulNumbers.size(), k, max, getList(powerfulNumbers));
}
System.out.printf("%nTask: For k = 2..10, show the number of k-powerful numbers less than or equal to 10^j, for 0 <= j < k+10%n");
for ( int k = 2 ; k <= 10 ; k++ ) {
List<Integer> powCount = new ArrayList<>();
for ( int j = 0 ; j < k+10 ; j++ ) {
BigInteger max = BigInteger.valueOf(10).pow(j);
powCount.add(countPowerFulNumbers(max, k));
}
System.out.printf("Count of %2d-powerful numbers <= 10^j, j in [0, %d]: %s%n", k, k+9, powCount);
}
}
private static String getList(List<BigInteger> list) {
StringBuilder sb = new StringBuilder();
sb.append(list.subList(0, 5).toString().replace("]", ""));
sb.append(" ... ");
sb.append(list.subList(list.size()-5, list.size()).toString().replace("[", ""));
return sb.toString();
}
private static int countPowerFulNumbers(BigInteger max, int k) {
return potentialPowerful(max, k).size();
}
private static List<BigInteger> getPowerFulNumbers(BigInteger max, int k) {
List<BigInteger> powerfulNumbers = new ArrayList<>(potentialPowerful(max, k));
Collections.sort(powerfulNumbers);
return powerfulNumbers;
}
private static Set<BigInteger> potentialPowerful(BigInteger max, int k) {
int[] indexes = new int[k];
for ( int i = 0 ; i < k ; i++ ) {
indexes[i] = 1;
}
Set<BigInteger> powerful = new HashSet<>();
boolean foundPower = true;
while ( foundPower ) {
boolean genPowerful = false;
for ( int index = 0 ; index < k ; index++ ) {
BigInteger power = BigInteger.ONE;
for ( int i = 0 ; i < k ; i++ ) {
power = power.multiply(BigInteger.valueOf(indexes[i]).pow(k+i));
}
if ( power.compareTo(max) <= 0 ) {
powerful.add(power);
indexes[0] += 1;
genPowerful = true;
break;
}
else {
indexes[index] = 1;
if ( index < k-1 ) {
indexes[index+1] += 1;
}
}
}
if ( ! genPowerful ) {
foundPower = false;
}
}
return powerful;
}
}
|
Change the following Python code into Java without altering its purpose. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef = out[i]
if coef != 0:
for j in xrange(1, len(divisor)):
out[i + j] += -divisor[j] * coef
separator = -(len(divisor)-1)
return out[:separator], out[separator:]
if __name__ == '__main__':
print("POLYNOMIAL SYNTHETIC DIVISION")
N = [1, -12, 0, -42]
D = [1, -3]
print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
| import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef = out[i]
if coef != 0:
for j in xrange(1, len(divisor)):
out[i + j] += -divisor[j] * coef
separator = -(len(divisor)-1)
return out[:separator], out[separator:]
if __name__ == '__main__':
print("POLYNOMIAL SYNTHETIC DIVISION")
N = [1, -12, 0, -42]
D = [1, -3]
print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
| import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] N = {1, -12, 0, -42};
int[] D = {1, -3};
System.out.printf("%s / %s = %s",
Arrays.toString(N),
Arrays.toString(D),
Arrays.deepToString(extendedSyntheticDivision(N, D)));
}
static int[][] extendedSyntheticDivision(int[] dividend, int[] divisor) {
int[] out = dividend.clone();
int normalizer = divisor[0];
for (int i = 0; i < dividend.length - (divisor.length - 1); i++) {
out[i] /= normalizer;
int coef = out[i];
if (coef != 0) {
for (int j = 1; j < divisor.length; j++)
out[i + j] += -divisor[j] * coef;
}
}
int separator = out.length - (divisor.length - 1);
return new int[][]{
Arrays.copyOfRange(out, 0, separator),
Arrays.copyOfRange(out, separator, out.length)
};
}
}
|
Generate an equivalent Java version of this Python code. |
import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
dictionary = open("unixdict.txt","r")
wordList = dictionary.read().split('\n')
dictionary.close()
oddWordSet = set({})
for word in wordList:
if len(word)>=9 and word[::2] in wordList:
oddWordSet.add(word[::2])
[print(i) for i in sorted(oddWordSet)]
| import java.io.*;
import java.util.*;
public class OddWords {
public static void main(String[] args) {
try {
Set<String> dictionary = new TreeSet<>();
final int minLength = 5;
String fileName = "unixdict.txt";
if (args.length != 0)
fileName = args[0];
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() >= minLength)
dictionary.add(line);
}
}
StringBuilder word1 = new StringBuilder();
StringBuilder word2 = new StringBuilder();
List<StringPair> evenWords = new ArrayList<>();
List<StringPair> oddWords = new ArrayList<>();
for (String word : dictionary) {
int length = word.length();
if (length < minLength + 2 * (minLength/2))
continue;
word1.setLength(0);
word2.setLength(0);
for (int i = 0; i < length; ++i) {
if ((i & 1) == 0)
word1.append(word.charAt(i));
else
word2.append(word.charAt(i));
}
String oddWord = word1.toString();
String evenWord = word2.toString();
if (dictionary.contains(oddWord))
oddWords.add(new StringPair(word, oddWord));
if (dictionary.contains(evenWord))
evenWords.add(new StringPair(word, evenWord));
}
System.out.println("Odd words:");
printWords(oddWords);
System.out.println("\nEven words:");
printWords(evenWords);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printWords(List<StringPair> strings) {
int n = 1;
for (StringPair pair : strings) {
System.out.printf("%2d:Β %-14s%s\n", n++,
pair.string1, pair.string2);
}
}
private static class StringPair {
private String string1;
private String string2;
private StringPair(String s1, String s2) {
string1 = s1;
string2 = s2;
}
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | from mpmath import mp
heegner = [19,43,67,163]
mp.dps = 50
x = mp.exp(mp.pi*mp.sqrt(163))
print("calculated Ramanujan's constant: {}".format(x))
print("Heegner numbers yielding 'almost' integers:")
for i in heegner:
print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3dΒ : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
|
Write the same code in Java as shown below in Python. | from mpmath import mp
heegner = [19,43,67,163]
mp.dps = 50
x = mp.exp(mp.pi*mp.sqrt(163))
print("calculated Ramanujan's constant: {}".format(x))
print("Heegner numbers yielding 'almost' integers:")
for i in heegner:
print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Arrays;
import java.util.List;
public class RamanujanConstant {
public static void main(String[] args) {
System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100));
System.out.printf("Heegner numbers yielding 'almost' integers:%n");
List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163);
List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320);
for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) {
int heegnerNumber = heegnerNumbers.get(i);
int heegnerVal = heegnerVals.get(i);
BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744));
BigDecimal compute = ramanujanConstant(heegnerNumber, 50);
System.out.printf("%3dΒ : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString());
}
}
public static BigDecimal ramanujanConstant(int sqrt, int digits) {
MathContext mc = new MathContext(digits + 5);
return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits));
}
public static BigDecimal bigE(BigDecimal exponent, MathContext mc) {
BigDecimal e = BigDecimal.ONE;
BigDecimal ak = e;
int k = 0;
BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision()));
while ( true ) {
k++;
ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc);
e = e.add(ak, mc);
if ( ak.compareTo(min) < 0 ) {
break;
}
}
return e;
}
public static BigDecimal bigPi(MathContext mc) {
int k = 0;
BigDecimal ak = BigDecimal.ONE;
BigDecimal a = ak;
BigDecimal b = BigDecimal.ZERO;
BigDecimal c = BigDecimal.valueOf(640320);
BigDecimal c3 = c.pow(3);
double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72);
double digits = 0;
while ( digits < mc.getPrecision() ) {
k++;
digits += digitePerTerm;
BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1));
BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc);
ak = ak.multiply(term, mc);
a = a.add(ak, mc);
b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc);
}
BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc);
return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc);
}
public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) {
double sqrt = Math.sqrt(squareDecimal.doubleValue());
BigDecimal x0 = new BigDecimal(sqrt, mc);
BigDecimal two = BigDecimal.valueOf(2);
while ( true ) {
BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc);
String x1String = x1.toPlainString();
String x0String = x0.toPlainString();
if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) {
break;
}
x0 = x1;
}
return x0;
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? |
from itertools import (chain)
def stringParse(lexicon):
return lambda s: Node(s)(
tokenTrees(lexicon)(s)
)
def tokenTrees(wds):
def go(s):
return [Node(s)([])] if s in wds else (
concatMap(nxt(s))(wds)
)
def nxt(s):
return lambda w: parse(
w, go(s[len(w):])
) if s.startswith(w) else []
def parse(w, xs):
return [Node(w)(xs)] if xs else xs
return lambda s: go(s)
def showParse(tree):
def showTokens(x):
xs = x['nest']
return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')
parses = tree['nest']
return tree['root'] + ':\n' + (
'\n'.join(
map(showTokens, parses)
) if parses else ' ( Not parseable in terms of these words )'
)
def main():
lexicon = 'a bc abc cd b'.split()
testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()
print(unlines(
map(
showParse,
map(
stringParse(lexicon),
testSamples
)
)
))
def Node(v):
return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}
def concatMap(f):
return lambda xs: list(
chain.from_iterable(map(f, xs))
)
def unlines(xs):
return '\n'.join(xs)
if __name__ == '__main__':
main()
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class WordBreak {
public static void main(String[] args) {
List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab");
for ( String testString : Arrays.asList("aab", "aa b") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d");
for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
}
private static List<List<String>> wordBreak(String s, List<String> dictionary) {
List<List<String>> matches = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(s));
while ( ! queue.isEmpty() ) {
Node node = queue.remove();
if ( node.val.length() == 0 ) {
matches.add(node.parsed);
}
else {
for ( String word : dictionary ) {
if ( node.val.startsWith(word) ) {
String valNew = node.val.substring(word.length(), node.val.length());
List<String> parsedNew = new ArrayList<>();
parsedNew.addAll(node.parsed);
parsedNew.add(word);
queue.add(new Node(valNew, parsedNew));
}
}
}
}
return matches;
}
private static class Node {
private String val;
private List<String> parsed;
public Node(String initial) {
val = initial;
parsed = new ArrayList<>();
}
public Node(String s, List<String> p) {
val = s;
parsed = p;
}
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. |
from itertools import (chain)
def stringParse(lexicon):
return lambda s: Node(s)(
tokenTrees(lexicon)(s)
)
def tokenTrees(wds):
def go(s):
return [Node(s)([])] if s in wds else (
concatMap(nxt(s))(wds)
)
def nxt(s):
return lambda w: parse(
w, go(s[len(w):])
) if s.startswith(w) else []
def parse(w, xs):
return [Node(w)(xs)] if xs else xs
return lambda s: go(s)
def showParse(tree):
def showTokens(x):
xs = x['nest']
return ' ' + x['root'] + (showTokens(xs[0]) if xs else '')
parses = tree['nest']
return tree['root'] + ':\n' + (
'\n'.join(
map(showTokens, parses)
) if parses else ' ( Not parseable in terms of these words )'
)
def main():
lexicon = 'a bc abc cd b'.split()
testSamples = 'abcd abbc abcbcd acdbc abcdd'.split()
print(unlines(
map(
showParse,
map(
stringParse(lexicon),
testSamples
)
)
))
def Node(v):
return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}
def concatMap(f):
return lambda xs: list(
chain.from_iterable(map(f, xs))
)
def unlines(xs):
return '\n'.join(xs)
if __name__ == '__main__':
main()
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class WordBreak {
public static void main(String[] args) {
List<String> dict = Arrays.asList("a", "aa", "b", "ab", "aab");
for ( String testString : Arrays.asList("aab", "aa b") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
dict = Arrays.asList("abc", "a", "ac", "b", "c", "cb", "d");
for ( String testString : Arrays.asList("abcd", "abbc", "abcbcd", "acdbc", "abcdd") ) {
List<List<String>> matches = wordBreak(testString, dict);
System.out.printf("String = %s, Dictionary = %s. Solutions = %d:%n", testString, dict, matches.size());
for ( List<String> match : matches ) {
System.out.printf(" Word Break = %s%n", match);
}
System.out.printf("%n");
}
}
private static List<List<String>> wordBreak(String s, List<String> dictionary) {
List<List<String>> matches = new ArrayList<>();
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(s));
while ( ! queue.isEmpty() ) {
Node node = queue.remove();
if ( node.val.length() == 0 ) {
matches.add(node.parsed);
}
else {
for ( String word : dictionary ) {
if ( node.val.startsWith(word) ) {
String valNew = node.val.substring(word.length(), node.val.length());
List<String> parsedNew = new ArrayList<>();
parsedNew.addAll(node.parsed);
parsedNew.add(word);
queue.add(new Node(valNew, parsedNew));
}
}
}
}
return matches;
}
private static class Node {
private String val;
private List<String> parsed;
public Node(String initial) {
val = initial;
parsed = new ArrayList<>();
}
public Node(String s, List<String> p) {
val = s;
parsed = p;
}
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | from primesieve.numpy import primes
from math import isqrt
import numpy as np
max_order = 9
blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]
def smallest_brilliant(lb):
pos = 1
root = isqrt(lb)
for blk in blocks:
n = len(blk)
if blk[-1]*blk[-1] < lb:
pos += n*(n + 1)//2
continue
i = np.searchsorted(blk, root, 'left')
i += blk[i]*blk[i] < lb
if not i:
return blk[0]*blk[0], pos
p = blk[:i + 1]
q = (lb - 1)//p
idx = np.searchsorted(blk, q, 'right')
sel = idx < n
p, idx = p[sel], idx[sel]
q = blk[idx]
sel = q >= p
p, q, idx = p[sel], q[sel], idx[sel]
pos += np.sum(idx - np.arange(len(idx)))
return np.min(p*q), pos
res = []
p = 0
for i in range(100):
p, _ = smallest_brilliant(p + 1)
res.append(p)
print(f'first 100 are {res}')
for i in range(max_order*2):
thresh = 10**i
p, pos = smallest_brilliant(thresh)
print(f'Above 10^{i:2d}: {p:20d} at
| import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d isΒ %,d at positionΒ %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
}
|
Please provide an equivalent version of this Python code in Java. | from primesieve.numpy import primes
from math import isqrt
import numpy as np
max_order = 9
blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]
def smallest_brilliant(lb):
pos = 1
root = isqrt(lb)
for blk in blocks:
n = len(blk)
if blk[-1]*blk[-1] < lb:
pos += n*(n + 1)//2
continue
i = np.searchsorted(blk, root, 'left')
i += blk[i]*blk[i] < lb
if not i:
return blk[0]*blk[0], pos
p = blk[:i + 1]
q = (lb - 1)//p
idx = np.searchsorted(blk, q, 'right')
sel = idx < n
p, idx = p[sel], idx[sel]
q = blk[idx]
sel = q >= p
p, q, idx = p[sel], q[sel], idx[sel]
pos += np.sum(idx - np.arange(len(idx)))
return np.min(p*q), pos
res = []
p = 0
for i in range(100):
p, _ = smallest_brilliant(p + 1)
res.append(p)
print(f'first 100 are {res}')
for i in range(max_order*2):
thresh = 10**i
p, pos = smallest_brilliant(thresh)
print(f'Above 10^{i:2d}: {p:20d} at
| import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d isΒ %,d at positionΒ %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
}
|
Keep all operations the same but rewrite the snippet in Java. | import os,sys,zlib,urllib.request
def h ( str,x=9 ):
for c in str :
x = ( x*33 + ord( c )) & 0xffffffffff
return x
def cache ( func,*param ):
n = 'cache_%x.bin'%abs( h( repr( param )))
try : return eval( zlib.decompress( open( n,'rb' ).read()))
except : pass
s = func( *param )
open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))
return s
dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'
read_url = lambda url : urllib.request.urlopen( url ).read()
load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n'))
isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1
def build_map ( words ):
map = [(w.decode('ascii'),[]) for w in words]
for i1,(w1,n1) in enumerate( map ):
for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):
if isnext( w1,w2 ):
n1.append( i2 )
n2.append( i1 )
return map
def find_path ( words,w1,w2 ):
i = [w[0] for w in words].index( w1 )
front,done,res = [i],{i:-1},[]
while front :
i = front.pop(0)
word,next = words[i]
for n in next :
if n in done : continue
done[n] = i
if words[n][0] == w2 :
while n >= 0 :
res = [words[n][0]] + res
n = done[n]
return ' '.join( res )
front.append( n )
return '%s can not be turned into %s'%( w1,w2 )
for w in ('boy man','girl lady','john jane','alien drool','child adult'):
print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | import os,sys,zlib,urllib.request
def h ( str,x=9 ):
for c in str :
x = ( x*33 + ord( c )) & 0xffffffffff
return x
def cache ( func,*param ):
n = 'cache_%x.bin'%abs( h( repr( param )))
try : return eval( zlib.decompress( open( n,'rb' ).read()))
except : pass
s = func( *param )
open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))
return s
dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'
read_url = lambda url : urllib.request.urlopen( url ).read()
load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n'))
isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1
def build_map ( words ):
map = [(w.decode('ascii'),[]) for w in words]
for i1,(w1,n1) in enumerate( map ):
for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):
if isnext( w1,w2 ):
n1.append( i2 )
n2.append( i1 )
return map
def find_path ( words,w1,w2 ):
i = [w[0] for w in words].index( w1 )
front,done,res = [i],{i:-1},[]
while front :
i = front.pop(0)
word,next = words[i]
for n in next :
if n in done : continue
done[n] = i
if words[n][0] == w2 :
while n >= 0 :
res = [words[n][0]] + res
n = done[n]
return ' '.join( res )
front.append( n )
return '%s can not be turned into %s'%( w1,w2 )
for w in ('boy man','girl lady','john jane','alien drool','child adult'):
print( find_path( cache( build_map,load_dico( dico_url )),*w.split()))
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.IntStream;
public class WordLadder {
private static int distance(String s1, String s2) {
assert s1.length() == s2.length();
return (int) IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i))
.count();
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw) {
wordLadder(words, fw, tw, 8);
}
private static void wordLadder(Map<Integer, Set<String>> words, String fw, String tw, int limit) {
if (fw.length() != tw.length()) {
throw new IllegalArgumentException("From word and to word must have the same length");
}
Set<String> ws = words.get(fw.length());
if (ws.contains(fw)) {
List<String> primeList = new ArrayList<>();
primeList.add(fw);
PriorityQueue<List<String>> queue = new PriorityQueue<>((chain1, chain2) -> {
int cmp1 = Integer.compare(chain1.size(), chain2.size());
if (cmp1 == 0) {
String last1 = chain1.get(chain1.size() - 1);
int d1 = distance(last1, tw);
String last2 = chain2.get(chain2.size() - 1);
int d2 = distance(last2, tw);
return Integer.compare(d1, d2);
}
return cmp1;
});
queue.add(primeList);
while (queue.size() > 0) {
List<String> curr = queue.remove();
if (curr.size() > limit) {
continue;
}
String last = curr.get(curr.size() - 1);
for (String word : ws) {
if (distance(last, word) == 1) {
if (word.equals(tw)) {
curr.add(word);
System.out.println(String.join(" -> ", curr));
return;
}
if (!curr.contains(word)) {
List<String> cp = new ArrayList<>(curr);
cp.add(word);
queue.add(cp);
}
}
}
}
}
System.err.printf("Cannot turn `%s` into `%s`%n", fw, tw);
}
public static void main(String[] args) throws IOException {
Map<Integer, Set<String>> words = new HashMap<>();
for (String line : Files.readAllLines(Path.of("unixdict.txt"))) {
Set<String> wl = words.computeIfAbsent(line.length(), HashSet::new);
wl.add(line);
}
wordLadder(words, "boy", "man");
wordLadder(words, "girl", "lady");
wordLadder(words, "john", "jane");
wordLadder(words, "child", "adult");
wordLadder(words, "cat", "dog");
wordLadder(words, "lead", "gold");
wordLadder(words, "white", "black");
wordLadder(words, "bubble", "tickle", 12);
}
}
|
Keep all operations the same but rewrite the snippet in Java. |
from primesieve import primes
LIMIT = 10**9
pri = primes(LIMIT * 5)
gapstarts = {}
for i in range(1, len(pri)):
if pri[i] - pri[i - 1] not in gapstarts:
gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]
PM, GAP1, = 10, 2
while True:
while GAP1 not in gapstarts:
GAP1 += 2
start1 = gapstarts[GAP1]
GAP2 = GAP1 + 2
if GAP2 not in gapstarts:
GAP1 = GAP2 + 2
continue
start2 = gapstarts[GAP2]
diff = abs(start2 - start1)
if diff > PM:
print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:")
print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n")
if PM == LIMIT:
break
PM *= 10
else:
GAP1 = GAP2
| import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 100000000;
PrimeGaps pg = new PrimeGaps();
for (int pm = 10, gap1 = 2;;) {
int start1 = pg.findGapStart(gap1);
int gap2 = gap1 + 2;
int start2 = pg.findGapStart(gap2);
int diff = start2 > start1 ? start2 - start1 : start1 - start2;
if (diff > pm) {
System.out.printf(
"Earliest difference >Β %,d between adjacent prime gap starting primes:\n"
+ "GapΒ %,d starts atΒ %,d, gapΒ %,d starts atΒ %,d, difference isΒ %,d.\n\n",
pm, gap1, start1, gap2, start2, diff);
if (pm == limit)
break;
pm *= 10;
} else {
gap1 = gap2;
}
}
}
private int findGapStart(int gap) {
Integer start = gapStarts.get(gap);
if (start != null)
return start;
for (;;) {
int prev = lastPrime;
lastPrime = primeGenerator.nextPrime();
int diff = lastPrime - prev;
gapStarts.putIfAbsent(diff, prev);
if (diff == gap)
return prev;
}
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | def dList(n, start):
start -= 1
a = range(n)
a[start] = a[0]
a[0] = start
a[1:] = sorted(a[1:])
first = a[1]
r = []
def recurse(last):
if (last == first):
for j,v in enumerate(a[1:]):
if j + 1 == v:
return
b = [x + 1 for x in a]
r.append(b)
return
for i in xrange(last, 0, -1):
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
recurse(n - 1)
return r
def printSquare(latin,n):
for row in latin:
print row
print
def reducedLatinSquares(n,echo):
if n <= 0:
if echo:
print []
return 0
elif n == 1:
if echo:
print [1]
return 1
rlatin = [None] * n
for i in xrange(n):
rlatin[i] = [None] * n
for j in xrange(0, n):
rlatin[0][j] = j + 1
class OuterScope:
count = 0
def recurse(i):
rows = dList(n, i)
for r in xrange(len(rows)):
rlatin[i - 1] = rows[r]
justContinue = False
k = 0
while not justContinue and k < i - 1:
for j in xrange(1, n):
if rlatin[k][j] == rlatin[i - 1][j]:
if r < len(rows) - 1:
justContinue = True
break
if i > 2:
return
k += 1
if not justContinue:
if i < n:
recurse(i + 1)
else:
OuterScope.count += 1
if echo:
printSquare(rlatin, n)
recurse(2)
return OuterScope.count
def factorial(n):
if n == 0:
return 1
prod = 1
for i in xrange(2, n + 1):
prod *= i
return prod
print "The four reduced latin squares of order 4 are:\n"
reducedLatinSquares(4,True)
print "The size of the set of reduced latin squares for the following orders"
print "and hence the total number of latin squares of these orders are:\n"
for n in xrange(1, 7):
size = reducedLatinSquares(n, False)
f = factorial(n - 1)
f *= f * n * size
print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LatinSquaresInReducedForm {
public static void main(String[] args) {
System.out.printf("Reduced latin squares of order 4:%n");
for ( LatinSquare square : getReducedLatinSquares(4) ) {
System.out.printf("%s%n", square);
}
System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n");
for ( int n = 1 ; n <= 6 ; n++ ) {
List<LatinSquare> list = getReducedLatinSquares(n);
System.out.printf("Size = %d, %d * %d * %d =Β %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));
}
}
private static long fact(int n) {
if ( n == 0 ) {
return 1;
}
int prod = 1;
for ( int i = 1 ; i <= n ; i++ ) {
prod *= i;
}
return prod;
}
private static List<LatinSquare> getReducedLatinSquares(int n) {
List<LatinSquare> squares = new ArrayList<>();
squares.add(new LatinSquare(n));
PermutationGenerator permGen = new PermutationGenerator(n);
for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {
List<LatinSquare> squaresNext = new ArrayList<>();
for ( LatinSquare square : squares ) {
while ( permGen.hasMore() ) {
int[] perm = permGen.getNext();
if ( (perm[0]+1) != (fillRow+1) ) {
continue;
}
boolean permOk = true;
done:
for ( int row = 0 ; row < fillRow ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
if ( square.get(row, col) == (perm[col]+1) ) {
permOk = false;
break done;
}
}
}
if ( permOk ) {
LatinSquare newSquare = new LatinSquare(square);
for ( int col = 0 ; col < n ; col++ ) {
newSquare.set(fillRow, col, perm[col]+1);
}
squaresNext.add(newSquare);
}
}
permGen.reset();
}
squares = squaresNext;
}
return squares;
}
@SuppressWarnings("unused")
private static int[] display(int[] in) {
int [] out = new int[in.length];
for ( int i = 0 ; i < in.length ; i++ ) {
out[i] = in[i] + 1;
}
return out;
}
private static class LatinSquare {
int[][] square;
int size;
public LatinSquare(int n) {
square = new int[n][n];
size = n;
for ( int col = 0 ; col < n ; col++ ) {
set(0, col, col + 1);
}
}
public LatinSquare(LatinSquare ls) {
int n = ls.size;
square = new int[n][n];
size = n;
for ( int row = 0 ; row < n ; row++ ) {
for ( int col = 0 ; col < n ; col++ ) {
set(row, col, ls.get(row, col));
}
}
}
public void set(int row, int col, int value) {
square[row][col] = value;
}
public int get(int row, int col) {
return square[row][col];
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for ( int row = 0 ; row < size ; row++ ) {
sb.append(Arrays.toString(square[row]));
sb.append("\n");
}
return sb.toString();
}
}
private static class PermutationGenerator {
private int[] a;
private BigInteger numLeft;
private BigInteger total;
public PermutationGenerator (int n) {
if (n < 1) {
throw new IllegalArgumentException ("Min 1");
}
a = new int[n];
total = getFactorial(n);
reset();
}
private void reset () {
for ( int i = 0 ; i < a.length ; i++ ) {
a[i] = i;
}
numLeft = new BigInteger(total.toString());
}
public boolean hasMore() {
return numLeft.compareTo(BigInteger.ZERO) == 1;
}
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for ( int i = n ; i > 1 ; i-- ) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
return fact;
}
public int[] getNext() {
if ( numLeft.equals(total) ) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
int j = a.length - 2;
while ( a[j] > a[j+1] ) {
j--;
}
int k = a.length - 1;
while ( a[j] > a[k] ) {
k--;
}
int temp = a[k];
a[k] = a[j];
a[j] = temp;
int r = a.length - 1;
int s = j + 1;
while (r > s) {
int temp2 = a[s];
a[s] = a[r];
a[r] = temp2;
r--;
s++;
}
numLeft = numLeft.subtract(BigInteger.ONE);
return a;
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. |
import itertools
import re
RE_BARCODE = re.compile(
r"^(?P<s_quiet> +)"
r"(?P<s_guard>
r"(?P<left>[
r"(?P<m_guard>
r"(?P<right>[
r"(?P<e_guard>
r"(?P<e_quiet> +)$"
)
LEFT_DIGITS = {
(0, 0, 0, 1, 1, 0, 1): 0,
(0, 0, 1, 1, 0, 0, 1): 1,
(0, 0, 1, 0, 0, 1, 1): 2,
(0, 1, 1, 1, 1, 0, 1): 3,
(0, 1, 0, 0, 0, 1, 1): 4,
(0, 1, 1, 0, 0, 0, 1): 5,
(0, 1, 0, 1, 1, 1, 1): 6,
(0, 1, 1, 1, 0, 1, 1): 7,
(0, 1, 1, 0, 1, 1, 1): 8,
(0, 0, 0, 1, 0, 1, 1): 9,
}
RIGHT_DIGITS = {
(1, 1, 1, 0, 0, 1, 0): 0,
(1, 1, 0, 0, 1, 1, 0): 1,
(1, 1, 0, 1, 1, 0, 0): 2,
(1, 0, 0, 0, 0, 1, 0): 3,
(1, 0, 1, 1, 1, 0, 0): 4,
(1, 0, 0, 1, 1, 1, 0): 5,
(1, 0, 1, 0, 0, 0, 0): 6,
(1, 0, 0, 0, 1, 0, 0): 7,
(1, 0, 0, 1, 0, 0, 0): 8,
(1, 1, 1, 0, 1, 0, 0): 9,
}
MODULES = {
" ": 0,
"
}
DIGITS_PER_SIDE = 6
MODULES_PER_DIGIT = 7
class ParityError(Exception):
class ChecksumError(Exception):
def group(iterable, n):
args = [iter(iterable)] * n
return tuple(itertools.zip_longest(*args))
def parse(barcode):
match = RE_BARCODE.match(barcode)
left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT)
right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT)
left, right = check_parity(left, right)
return tuple(
itertools.chain(
(LEFT_DIGITS[d] for d in left),
(RIGHT_DIGITS[d] for d in right),
)
)
def check_parity(left, right):
left_parity = sum(sum(d) % 2 for d in left)
right_parity = sum(sum(d) % 2 for d in right)
if left_parity == 0 and right_parity == DIGITS_PER_SIDE:
_left = tuple(tuple(reversed(d)) for d in reversed(right))
right = tuple(tuple(reversed(d)) for d in reversed(left))
left = _left
elif left_parity != DIGITS_PER_SIDE or right_parity != 0:
error = tuple(
itertools.chain(
(LEFT_DIGITS.get(d, "_") for d in left),
(RIGHT_DIGITS.get(d, "_") for d in right),
)
)
raise ParityError(" ".join(str(d) for d in error))
return left, right
def checksum(digits):
odds = (digits[i] for i in range(0, 11, 2))
evens = (digits[i] for i in range(1, 10, 2))
check_digit = (sum(odds) * 3 + sum(evens)) % 10
if check_digit != 0:
check_digit = 10 - check_digit
if digits[-1] != check_digit:
raise ChecksumError(str(check_digit))
return check_digit
def main():
barcodes = [
"
"
"
"
"
"
"
"
"
"
"
]
for barcode in barcodes:
try:
digits = parse(barcode)
except ParityError as err:
print(f"{err} parity error!")
continue
try:
check_digit = checksum(digits)
except ChecksumError as err:
print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})")
continue
print(f"{' '.join(str(d) for d in digits)}")
if __name__ == "__main__":
main()
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
def playfair(key, from_ = 'J', to = None):
if to is None:
to = 'I' if from_ == 'J' else ''
def canonicalize(s):
return filter(str.isupper, s.upper()).replace(from_, to)
m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)
enc = {}
for row in m:
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]
for c in zip(*m):
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]
for i1, j1, i2, j2 in product(xrange(5), repeat=4):
if i1 != i2 and j1 != j2:
enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]
dec = dict((v, k) for k, v in enc.iteritems())
def sub_enc(txt):
lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt))
return " ".join(enc[a + (b if b else 'X')] for a, b in lst)
def sub_dec(encoded):
return " ".join(dec[p] for p in partition(canonicalize(encoded), 2))
return sub_enc, sub_dec
(encode, decode) = playfair("Playfair example")
orig = "Hide the gold in...the TREESTUMP!!!"
print "Original:", orig
enc = encode(orig)
print "Encoded:", enc
print "Decoded:", decode(enc)
| import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
|
Write a version of this Python function in Java with identical behavior. | from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
def playfair(key, from_ = 'J', to = None):
if to is None:
to = 'I' if from_ == 'J' else ''
def canonicalize(s):
return filter(str.isupper, s.upper()).replace(from_, to)
m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)
enc = {}
for row in m:
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]
for c in zip(*m):
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]
for i1, j1, i2, j2 in product(xrange(5), repeat=4):
if i1 != i2 and j1 != j2:
enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]
dec = dict((v, k) for k, v in enc.iteritems())
def sub_enc(txt):
lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt))
return " ".join(enc[a + (b if b else 'X')] for a, b in lst)
def sub_dec(encoded):
return " ".join(dec[p] for p in partition(canonicalize(encoded), 2))
return sub_enc, sub_dec
(encode, decode) = playfair("Playfair example")
orig = "Hide the gold in...the TREESTUMP!!!"
print "Original:", orig
enc = encode(orig)
print "Encoded:", enc
print "Decoded:", decode(enc)
| import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);
boolean changeJtoI = jti.equalsIgnoreCase("y");
createTable(key, changeJtoI);
String enc = encode(prepareText(txt, changeJtoI));
System.out.printf("%nEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}
private static String prepareText(String s, boolean changeJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTable(String key, boolean changeJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
else if (sb.charAt(i) == sb.charAt(i + 1))
sb.insert(i + 1, 'X');
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
private static String codec(StringBuilder text, int direction) {
int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + direction) % 5;
} else if (col1 == col2) {
row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;
} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}
|
Convert this Python block to Java, preserving its control flow and logic. |
from random import randint, randrange
from operator import itemgetter, attrgetter
infinity = float('inf')
def bruteForceClosestPair(point):
numPoints = len(point)
if numPoints < 2:
return infinity, (None, None)
return min( ((abs(point[i] - point[j]), (point[i], point[j]))
for i in range(numPoints-1)
for j in range(i+1,numPoints)),
key=itemgetter(0))
def closestPair(point):
xP = sorted(point, key= attrgetter('real'))
yP = sorted(point, key= attrgetter('imag'))
return _closestPair(xP, yP)
def _closestPair(xP, yP):
numPoints = len(xP)
if numPoints <= 3:
return bruteForceClosestPair(xP)
Pl = xP[:numPoints/2]
Pr = xP[numPoints/2:]
Yl, Yr = [], []
xDivider = Pl[-1].real
for p in yP:
if p.real <= xDivider:
Yl.append(p)
else:
Yr.append(p)
dl, pairl = _closestPair(Pl, Yl)
dr, pairr = _closestPair(Pr, Yr)
dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)
closeY = [p for p in yP if abs(p.real - xDivider) < dm]
numCloseY = len(closeY)
if numCloseY > 1:
closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))
for i in range(numCloseY-1)
for j in range(i+1,min(i+8, numCloseY))),
key=itemgetter(0))
return (dm, pairm) if dm <= closestY[0] else closestY
else:
return dm, pairm
def times():
import timeit
functions = [bruteForceClosestPair, closestPair]
for f in functions:
print 'Time for', f.__name__, timeit.Timer(
'%s(pointList)' % f.__name__,
'from closestpair import %s, pointList' % f.__name__).timeit(number=1)
pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]
if __name__ == '__main__':
pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]
print pointList
print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)
print ' closestPair:', closestPair(pointList)
for i in range(10):
pointList = [randrange(11)+1j*randrange(11) for i in range(10)]
print '\n', pointList
print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)
print ' closestPair:', closestPair(pointList)
print '\n'
times()
times()
times()
| import java.util.*;
public class ClosestPair
{
public static class Point
{
public final double x;
public final double y;
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public String toString()
{ return "(" + x + ", " + y + ")"; }
}
public static class Pair
{
public Point point1 = null;
public Point point2 = null;
public double distance = 0.0;
public Pair()
{ }
public Pair(Point point1, Point point2)
{
this.point1 = point1;
this.point2 = point2;
calcDistance();
}
public void update(Point point1, Point point2, double distance)
{
this.point1 = point1;
this.point2 = point2;
this.distance = distance;
}
public void calcDistance()
{ this.distance = distance(point1, point2); }
public String toString()
{ return point1 + "-" + point2 + "Β : " + distance; }
}
public static double distance(Point p1, Point p2)
{
double xdist = p2.x - p1.x;
double ydist = p2.y - p1.y;
return Math.hypot(xdist, ydist);
}
public static Pair bruteForce(List<? extends Point> points)
{
int numPoints = points.size();
if (numPoints < 2)
return null;
Pair pair = new Pair(points.get(0), points.get(1));
if (numPoints > 2)
{
for (int i = 0; i < numPoints - 1; i++)
{
Point point1 = points.get(i);
for (int j = i + 1; j < numPoints; j++)
{
Point point2 = points.get(j);
double distance = distance(point1, point2);
if (distance < pair.distance)
pair.update(point1, point2, distance);
}
}
}
return pair;
}
public static void sortByX(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.x < point2.x)
return -1;
if (point1.x > point2.x)
return 1;
return 0;
}
}
);
}
public static void sortByY(List<? extends Point> points)
{
Collections.sort(points, new Comparator<Point>() {
public int compare(Point point1, Point point2)
{
if (point1.y < point2.y)
return -1;
if (point1.y > point2.y)
return 1;
return 0;
}
}
);
}
public static Pair divideAndConquer(List<? extends Point> points)
{
List<Point> pointsSortedByX = new ArrayList<Point>(points);
sortByX(pointsSortedByX);
List<Point> pointsSortedByY = new ArrayList<Point>(points);
sortByY(pointsSortedByY);
return divideAndConquer(pointsSortedByX, pointsSortedByY);
}
private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY)
{
int numPoints = pointsSortedByX.size();
if (numPoints <= 3)
return bruteForce(pointsSortedByX);
int dividingIndex = numPoints >>> 1;
List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex);
List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);
List<Point> tempList = new ArrayList<Point>(leftOfCenter);
sortByY(tempList);
Pair closestPair = divideAndConquer(leftOfCenter, tempList);
tempList.clear();
tempList.addAll(rightOfCenter);
sortByY(tempList);
Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);
if (closestPairRight.distance < closestPair.distance)
closestPair = closestPairRight;
tempList.clear();
double shortestDistance =closestPair.distance;
double centerX = rightOfCenter.get(0).x;
for (Point point : pointsSortedByY)
if (Math.abs(centerX - point.x) < shortestDistance)
tempList.add(point);
for (int i = 0; i < tempList.size() - 1; i++)
{
Point point1 = tempList.get(i);
for (int j = i + 1; j < tempList.size(); j++)
{
Point point2 = tempList.get(j);
if ((point2.y - point1.y) >= shortestDistance)
break;
double distance = distance(point1, point2);
if (distance < closestPair.distance)
{
closestPair.update(point1, point2, distance);
shortestDistance = distance;
}
}
}
return closestPair;
}
public static void main(String[] args)
{
int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);
List<Point> points = new ArrayList<Point>();
Random r = new Random();
for (int i = 0; i < numPoints; i++)
points.add(new Point(r.nextDouble(), r.nextDouble()));
System.out.println("Generated " + numPoints + " random points");
long startTime = System.currentTimeMillis();
Pair bruteForceClosestPair = bruteForce(points);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair);
startTime = System.currentTimeMillis();
Pair dqClosestPair = divideAndConquer(points);
elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair);
if (bruteForceClosestPair.distance != dqClosestPair.distance)
System.out.println("MISMATCH");
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Lab(Dog):
pass
class Collie(Dog):
pass
| public class Animal{
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. | hash = dict()
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
| Map<String, Int> map = new HashMap();
map["foo"] = 5;
map["bar"] = 10;
map["baz"] = 15;
map["foo"] = 6;
|
Convert this Python block to Java, preserving its control flow and logic. | size(300, 300)
background(0)
radius = min(width, height) / 2.0
cx, cy = width / 2, width / 2
for x in range(width):
for y in range(height):
rx = x - cx
ry = y - cy
s = sqrt(rx ** 2 + ry ** 2) / radius
if s <= 1.0:
h = ((atan2(ry, rx) / PI) + 1.0) / 2.0
colorMode(HSB)
c = color(int(h * 255), int(s * 255), 255)
set(x, y, c)
| import java.awt.*;
import javax.swing.*;
public class ColorWheel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ColorWheelFrame frame = new ColorWheelFrame();
frame.setVisible(true);
}
});
}
private static class ColorWheelFrame extends JFrame {
private ColorWheelFrame() {
super("Color Wheel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new ColorWheelPanel());
pack();
}
}
private static class ColorWheelPanel extends JComponent {
private ColorWheelPanel() {
setPreferredSize(new Dimension(400, 400));
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
int margin = 10;
int radius = (Math.min(w, h) - 2 * margin)/2;
int cx = w/2;
int cy = h/2;
float[] dist = {0.F, 1.0F};
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, w, h);
for (int angle = 0; angle < 360; ++angle) {
Color color = hsvToRgb(angle, 1.0, 1.0);
Color[] colors = {Color.WHITE, color};
RadialGradientPaint paint = new RadialGradientPaint(cx, cy,
radius, dist, colors);
g2.setPaint(paint);
g2.fillArc(cx - radius, cy - radius, radius*2, radius*2,
angle, 1);
}
}
}
private static Color hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - Math.abs(hp % 2.0 - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1) {
r = c;
g = x;
} else if (hp <= 2) {
r = x;
g = c;
} else if (hp <= 3) {
g = c;
b = x;
} else if (hp <= 4) {
g = x;
b = c;
} else if (hp <= 5) {
r = x;
b = c;
} else {
r = c;
b = x;
}
r += m;
g += m;
b += m;
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. |
pal = [0] * 128
r = 42
g = 84
b = 126
rd = gd = bd = False
def setup():
global buffer
size(600, 600)
frameRate(25)
buffer = [None] * width * height
for x in range(width):
for y in range(width):
value = int(((128 + (128 * sin(x / 32.0)))
+ (128 + (128 * cos(y / 32.0)))
+ (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)
buffer[x + y * width] = value
def draw():
global r, g, b, rd, gd, bd
if r > 128: rd = True
if not rd: r += 1
else: r-=1
if r < 0: rd = False
if g > 128: gd = True
if not gd: g += 1
else: g- = 1
if r < 0: gd = False
if b > 128: bd = True
if not bd: b += 1
else: b- = 1
if b < 0: bd = False
for i in range(128):
s_1 = sin(i * PI / 25)
s_2 = sin(i * PI / 50 + PI / 4)
pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)
loadPixels()
for i, b in enumerate(buffer):
pixels[i] = pal[(b + frameCount) % 127]
updatePixels()
| import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;
public class PlasmaEffect extends JPanel {
float[][] plasma;
float hueShift = 0;
BufferedImage img;
public PlasmaEffect() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
plasma = createPlasma(dim.height, dim.width);
new Timer(42, (ActionEvent e) -> {
hueShift = (hueShift + 0.02f) % 1;
repaint();
}).start();
}
float[][] createPlasma(int w, int h) {
float[][] buffer = new float[h][w];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
double value = sin(x / 16.0);
value += sin(y / 8.0);
value += sin((x + y) / 16.0);
value += sin(sqrt(x * x + y * y) / 8.0);
value += 4;
value /= 8;
assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";
buffer[y][x] = (float) value;
}
return buffer;
}
void drawPlasma(Graphics2D g) {
int h = plasma.length;
int w = plasma[0].length;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
float hue = hueShift + plasma[y][x] % 1;
img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
}
g.drawImage(img, 0, 0, null);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPlasma(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Plasma Effect");
f.setResizable(false);
f.add(new PlasmaEffect(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? |
pal = [0] * 128
r = 42
g = 84
b = 126
rd = gd = bd = False
def setup():
global buffer
size(600, 600)
frameRate(25)
buffer = [None] * width * height
for x in range(width):
for y in range(width):
value = int(((128 + (128 * sin(x / 32.0)))
+ (128 + (128 * cos(y / 32.0)))
+ (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)
buffer[x + y * width] = value
def draw():
global r, g, b, rd, gd, bd
if r > 128: rd = True
if not rd: r += 1
else: r-=1
if r < 0: rd = False
if g > 128: gd = True
if not gd: g += 1
else: g- = 1
if r < 0: gd = False
if b > 128: bd = True
if not bd: b += 1
else: b- = 1
if b < 0: bd = False
for i in range(128):
s_1 = sin(i * PI / 25)
s_2 = sin(i * PI / 50 + PI / 4)
pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)
loadPixels()
for i, b in enumerate(buffer):
pixels[i] = pal[(b + frameCount) % 127]
updatePixels()
| import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;
public class PlasmaEffect extends JPanel {
float[][] plasma;
float hueShift = 0;
BufferedImage img;
public PlasmaEffect() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
plasma = createPlasma(dim.height, dim.width);
new Timer(42, (ActionEvent e) -> {
hueShift = (hueShift + 0.02f) % 1;
repaint();
}).start();
}
float[][] createPlasma(int w, int h) {
float[][] buffer = new float[h][w];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
double value = sin(x / 16.0);
value += sin(y / 8.0);
value += sin((x + y) / 16.0);
value += sin(sqrt(x * x + y * y) / 8.0);
value += 4;
value /= 8;
assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";
buffer[y][x] = (float) value;
}
return buffer;
}
void drawPlasma(Graphics2D g) {
int h = plasma.length;
int w = plasma[0].length;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
float hue = hueShift + plasma[y][x] % 1;
img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
}
g.drawImage(img, 0, 0, null);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPlasma(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Plasma Effect");
f.setResizable(false);
f.add(new PlasmaEffect(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | print "Goodbye, World!"
| public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.