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 C# code.
using System; using System.Diagnostics; using System.Linq; using System.Numerics; static class Program { static void Main() { BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2))); string result = n.ToString(); Debug.Assert(result.Length == 183231); Debug.Assert(result.StartsWith("62060698786608744707")); Debug.Assert(result.EndsWith("92256259918212890625")); Console.WriteLine("n = 5^4^3^2"); Console.WriteLine("n = {0}...{1}", result.Substring(0, 20), result.Substring(result.Length - 20, 20) ); Console.WriteLine("n digits = {0}", result.Length); } }
import java.math.BigInteger; class IntegerPower { public static void main(String[] args) { BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact()); String str = power.toString(); int len = str.length(); System.out.printf("5**4**3**2 = %s...%s and has %d digits%n", str.substring(0, 20), str.substring(len - 20), len); } }
Please provide an equivalent version of this C# code in Java.
using System; using System.Collections.Generic; using System.IO; using System.Linq; class InvertedIndex { static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary) { return dictionary .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key))) .GroupBy(keyValuePair => keyValuePair.Key) .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value)); } static void Main() { Console.Write("files: "); var files = Console.ReadLine(); Console.Write("find: "); var find = Console.ReadLine(); var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable()); Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find])); } }
package org.rosettacode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class InvertedIndex { List<String> stopwords = Arrays.asList("a", "able", "about", "across", "after", "all", "almost", "also", "am", "among", "an", "and", "any", "are", "as", "at", "be", "because", "been", "but", "by", "can", "cannot", "could", "dear", "did", "do", "does", "either", "else", "ever", "every", "for", "from", "get", "got", "had", "has", "have", "he", "her", "hers", "him", "his", "how", "however", "i", "if", "in", "into", "is", "it", "its", "just", "least", "let", "like", "likely", "may", "me", "might", "most", "must", "my", "neither", "no", "nor", "not", "of", "off", "often", "on", "only", "or", "other", "our", "own", "rather", "said", "say", "says", "she", "should", "since", "so", "some", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "tis", "to", "too", "twas", "us", "wants", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "would", "yet", "you", "your"); Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>(); List<String> files = new ArrayList<String>(); public void indexFile(File file) throws IOException { int fileno = files.indexOf(file.getPath()); if (fileno == -1) { files.add(file.getPath()); fileno = files.size() - 1; } int pos = 0; BufferedReader reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader .readLine()) { for (String _word : line.split("\\W+")) { String word = _word.toLowerCase(); pos++; if (stopwords.contains(word)) continue; List<Tuple> idx = index.get(word); if (idx == null) { idx = new LinkedList<Tuple>(); index.put(word, idx); } idx.add(new Tuple(fileno, pos)); } } System.out.println("indexed " + file.getPath() + " " + pos + " words"); } public void search(List<String> words) { for (String _word : words) { Set<String> answer = new HashSet<String>(); String word = _word.toLowerCase(); List<Tuple> idx = index.get(word); if (idx != null) { for (Tuple t : idx) { answer.add(files.get(t.fileno)); } } System.out.print(word); for (String f : answer) { System.out.print(" " + f); } System.out.println(""); } } public static void main(String[] args) { try { InvertedIndex idx = new InvertedIndex(); for (int i = 1; i < args.length; i++) { idx.indexFile(new File(args[i])); } idx.search(Arrays.asList(args[0].split(","))); } catch (Exception e) { e.printStackTrace(); } } private class Tuple { private int fileno; private int position; public Tuple(int fileno, int position) { this.fileno = fileno; this.position = position; } } }
Convert this C# snippet to Java and keep its semantics consistent.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Rewrite this program in Java while keeping its functionality equivalent to the C# version.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
Generate an equivalent Java version of this C# code.
class Program { static void Main(string[] args) { Random random = new Random(); while (true) { int a = random.Next(20); Console.WriteLine(a); if (a == 10) break; int b = random.Next(20) Console.WriteLine(b); } Console.ReadLine(); } }
import java.util.Random; Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
Write a version of this C# function in Java with identical behavior.
class Program { static void Main(string[] args) { int[][] wta = { new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 }, new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }}; string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " "; for (int i = 0; i < wta.Length; i++) { int bpf; blk = ""; do { string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++) { if (wta[i][j] > 0) { floor += tb; wta[i][j] -= 1; bpf += 1; } else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt); } if (bpf > 0) blk = floor + lf + blk; } while (bpf > 0); while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt); while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt); if (args.Length > 0) System.Console.Write("\n{0}", blk); System.Console.WriteLine("Block {0} retains {1,2} water units.", i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2); } } }
public class WaterBetweenTowers { public static void main(String[] args) { int i = 1; int[][] tba = new int[][]{ new int[]{1, 5, 3, 7, 2}, new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, new int[]{5, 5, 5, 5}, new int[]{5, 6, 7, 8}, new int[]{8, 7, 7, 6}, new int[]{6, 7, 10, 7, 6} }; for (int[] tea : tba) { int rht, wu = 0, bof; do { for (rht = tea.length - 1; rht >= 0; rht--) { if (tea[rht] > 0) { break; } } if (rht < 0) { break; } bof = 0; for (int col = 0; col <= rht; col++) { if (tea[col] > 0) { tea[col]--; bof += 1; } else if (bof > 0) { wu++; } } if (bof < 2) { break; } } while (true); System.out.printf("Block %d", i++); if (wu == 0) { System.out.print(" does not hold any"); } else { System.out.printf(" holds %d", wu); } System.out.println(" water units."); } } }
Rewrite the snippet below in Java so it works the same as the original C# code.
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { const int maxSum = 100; var pairs = ( from X in 2.To(maxSum / 2 - 1) from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum) select new { X, Y, S = X + Y, P = X * Y } ).ToHashSet(); Console.WriteLine(pairs.Count); var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet(); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); foreach (var pair in pairs) Console.WriteLine(pair); } } public static class Extensions { public static IEnumerable<int> To(this int start, int end) { for (int i = start; i <= end; i++) yield return i; } public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source); }
package org.rosettacode; import java.util.ArrayList; import java.util.List; public class SumAndProductPuzzle { private final long beginning; private final int maxSum; private static final int MIN_VALUE = 2; private List<int[]> firstConditionExcludes = new ArrayList<>(); private List<int[]> secondConditionExcludes = new ArrayList<>(); public static void main(String... args){ if (args.length == 0){ new SumAndProductPuzzle(100).run(); new SumAndProductPuzzle(1684).run(); new SumAndProductPuzzle(1685).run(); } else { for (String arg : args){ try{ new SumAndProductPuzzle(Integer.valueOf(arg)).run(); } catch (NumberFormatException e){ System.out.println("Please provide only integer arguments. " + "Provided argument " + arg + " was not an integer. " + "Alternatively, calling the program with no arguments " + "will run the puzzle where maximum sum equals 100, 1684, and 1865."); } } } } public SumAndProductPuzzle(int maxSum){ this.beginning = System.currentTimeMillis(); this.maxSum = maxSum; System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " started at " + String.valueOf(beginning) + "."); } public void run(){ for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){ for (int y = x + 1; y < maxSum - MIN_VALUE; y++){ if (isSumNoGreaterThanMax(x,y) && isSKnowsPCannotKnow(x,y) && isPKnowsNow(x,y) && isSKnowsNow(x,y) ){ System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) + " in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } } } System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } public boolean isSumNoGreaterThanMax(int x, int y){ return x + y <= maxSum; } public boolean isSKnowsPCannotKnow(int x, int y){ if (firstConditionExcludes.contains(new int[] {x, y})){ return false; } for (int[] addends : sumAddends(x, y)){ if ( !(productFactors(addends[0], addends[1]).size() > 1) ) { firstConditionExcludes.add(new int[] {x, y}); return false; } } return true; } public boolean isPKnowsNow(int x, int y){ if (secondConditionExcludes.contains(new int[] {x, y})){ return false; } int countSolutions = 0; for (int[] factors : productFactors(x, y)){ if (isSKnowsPCannotKnow(factors[0], factors[1])){ countSolutions++; } } if (countSolutions == 1){ return true; } else { secondConditionExcludes.add(new int[] {x, y}); return false; } } public boolean isSKnowsNow(int x, int y){ int countSolutions = 0; for (int[] addends : sumAddends(x, y)){ if (isPKnowsNow(addends[0], addends[1])){ countSolutions++; } } return countSolutions == 1; } public List<int[]> sumAddends(int x, int y){ List<int[]> list = new ArrayList<>(); int sum = x + y; for (int addend = MIN_VALUE; addend < sum - addend; addend++){ if (isSumNoGreaterThanMax(addend, sum - addend)){ list.add(new int[]{addend, sum - addend}); } } return list; } public List<int[]> productFactors(int x, int y){ List<int[]> list = new ArrayList<>(); int product = x * y; for (int factor = MIN_VALUE; factor < product / factor; factor++){ if (product % factor == 0){ if (isSumNoGreaterThanMax(factor, product / factor)){ list.add(new int[]{factor, product / factor}); } } } return list; } }
Produce a functionally identical Java code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators = new (string symbol, int precedence, bool rightAssociative) [] { ("^", 4, true), ("*", 3, false), ("/", 3, false), ("+", 2, false), ("-", 2, false) }.ToDictionary(op => op.symbol); public static string ToPostfix(this string infix) { string[] tokens = infix.Split(' '); var stack = new Stack<string>(); var output = new List<string>(); foreach (string token in tokens) { if (int.TryParse(token, out _)) { output.Add(token); Print(token); } else if (operators.TryGetValue(token, out var op1)) { while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { int c = op1.precedence.CompareTo(op2.precedence); if (c < 0 || !op1.rightAssociative && c <= 0) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); Print(token); } else if (token == "(") { stack.Push(token); Print(token); } else if (token == ")") { string top = ""; while (stack.Count > 0 && (top = stack.Pop()) != "(") { output.Add(top); } if (top != "(") throw new ArgumentException("No matching left parenthesis."); Print(token); } } while (stack.Count > 0) { var top = stack.Pop(); if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); output.Add(top); } Print("pop"); return string.Join(" ", output); void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); } }
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) sb.append(ops.charAt(s.pop())).append(' '); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); } else { sb.append(token).append(' '); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())).append(' '); return sb.toString(); } }
Rewrite the snippet below in Java so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators = new (string symbol, int precedence, bool rightAssociative) [] { ("^", 4, true), ("*", 3, false), ("/", 3, false), ("+", 2, false), ("-", 2, false) }.ToDictionary(op => op.symbol); public static string ToPostfix(this string infix) { string[] tokens = infix.Split(' '); var stack = new Stack<string>(); var output = new List<string>(); foreach (string token in tokens) { if (int.TryParse(token, out _)) { output.Add(token); Print(token); } else if (operators.TryGetValue(token, out var op1)) { while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { int c = op1.precedence.CompareTo(op2.precedence); if (c < 0 || !op1.rightAssociative && c <= 0) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); Print(token); } else if (token == "(") { stack.Push(token); Print(token); } else if (token == ")") { string top = ""; while (stack.Count > 0 && (top = stack.Pop()) != "(") { output.Add(top); } if (top != "(") throw new ArgumentException("No matching left parenthesis."); Print(token); } } while (stack.Count > 0) { var top = stack.Pop(); if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); output.Add(top); } Print("pop"); return string.Join(" ", output); void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); } }
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) sb.append(ops.charAt(s.pop())).append(' '); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); } else { sb.append(token).append(' '); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())).append(' '); return sb.toString(); } }
Please provide an equivalent version of this C# code in Java.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { string text = Math.Abs(int.Parse(Console.ReadLine())).ToString(); Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3)); } } }
public class MiddleThreeDigits { public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE}; final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}; for (long n : passing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); for (int n : failing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); } public static <T> String middleThreeDigits(T n) { String s = String.valueOf(n); if (s.charAt(0) == '-') s = s.substring(1); int len = s.length(); if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; int mid = len / 2; return s.substring(mid - 1, mid + 2); } }
Please provide an equivalent version of this C# code in Java.
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<int> l = new List<int>() { 1, 1 }; static int gcd(int a, int b) { return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; } static void Main(string[] args) { int max = 1000; int take = 15; int i = 1; int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 }; do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; } while (l.Count < max || l[l.Count - 2] != selection.Last()); Console.Write("The first {0} items In the Stern-Brocot sequence: ", take); Console.WriteLine("{0}\n", string.Join(", ", l.Take(take))); Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:"); foreach (int ii in selection) { int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); } Console.WriteLine(); bool good = true; for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } } Console.WriteLine("The greatest common divisor of all the two consecutive items of the" + " series up to the {0}th item is {1}always one.", max, good ? "" : "not "); } }
import java.math.BigInteger; import java.util.LinkedList; public class SternBrocot { static LinkedList<Integer> sequence = new LinkedList<Integer>(){{ add(1); add(1); }}; private static void genSeq(int n){ for(int conIdx = 1; sequence.size() < n; conIdx++){ int consider = sequence.get(conIdx); int pre = sequence.get(conIdx - 1); sequence.add(consider + pre); sequence.add(consider); } } public static void main(String[] args){ genSeq(1200); System.out.println("The first 15 elements are: " + sequence.subList(0, 15)); for(int i = 1; i <= 10; i++){ System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1)); } System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1)); boolean failure = false; for(int i = 0; i < 999; i++){ failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE); } System.out.println("All GCDs are" + (failure ? " not" : "") + " 1"); } }
Write the same code in Java as shown below in C#.
public static class XMLSystem { static XMLSystem() { } public static XmlDocument GetXML(string name) { return null; } }
public class Doc{ private String field; public int method(long num) throws BadException{ } }
Transform the following C# implementation into Java, maintaining the same output and logic.
public static class XMLSystem { static XMLSystem() { } public static XmlDocument GetXML(string name) { return null; } }
public class Doc{ private String field; public int method(long num) throws BadException{ } }
Port the provided C# code into Java while preserving the original functionality.
using System; namespace ApolloniusProblemCalc { class Program { static float rs = 0; static float xs = 0; static float ys = 0; public static void Main(string[] args) { float gx1; float gy1; float gr1; float gx2; float gy2; float gr2; float gx3; float gy3; float gr3; gx1 = 0; gy1 = 0; gr1 = 1; gx2 = 4; gy2 = 0; gr2 = 1; gx3 = 2; gy3 = 4; gr3 = 2; for (int i = 1; i <= 8; i++) { SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3); if (i == 1) { Console.WriteLine("X of point of the " + i + "st solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "st solution: " + ys.ToString()); Console.WriteLine(i + "st Solution circle's radius: " + rs.ToString()); } else if (i == 2) { Console.WriteLine("X of point of the " + i + "ed solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "ed solution: " + ys.ToString()); Console.WriteLine(i + "ed Solution circle's radius: " + rs.ToString()); } else if(i == 3) { Console.WriteLine("X of point of the " + i + "rd solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "rd solution: " + ys.ToString()); Console.WriteLine(i + "rd Solution circle's radius: " + rs.ToString()); } else { Console.WriteLine("X of point of the " + i + "th solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "th solution: " + ys.ToString()); Console.WriteLine(i + "th Solution circle's radius: " + rs.ToString()); } Console.WriteLine(); } Console.ReadKey(true); } private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3) { float s1 = 1; float s2 = 1; float s3 = 1; if (calcCounter == 2) { s1 = -1; s2 = -1; s3 = -1; } else if (calcCounter == 3) { s1 = 1; s2 = -1; s3 = -1; } else if (calcCounter == 4) { s1 = -1; s2 = 1; s3 = -1; } else if (calcCounter == 5) { s1 = -1; s2 = -1; s3 = 1; } else if (calcCounter == 6) { s1 = 1; s2 = 1; s3 = -1; } else if (calcCounter == 7) { s1 = -1; s2 = 1; s3 = 1; } else if (calcCounter == 8) { s1 = 1; s2 = -1; s3 = 1; } float v11 = 2 * x2 - 2 * x1; float v12 = 2 * y2 - 2 * y1; float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2; float v14 = 2 * s2 * r2 - 2 * s1 * r1; float v21 = 2 * x3 - 2 * x2; float v22 = 2 * y3 - 2 * y2; float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3; float v24 = 2 * s3 * r3 - 2 * s2 * r2; float w12 = v12 / v11; float w13 = v13 / v11; float w14 = v14 / v11; float w22 = v22 / v21 - w12; float w23 = v23 / v21 - w13; float w24 = v24 / v21 - w14; float P = -w23 / w22; float Q = w24 / w22; float M = -w12 * P - w13; float N = w14 - w12 * Q; float a = N * N + Q * Q - 1; float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1; float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1; float D = b * b - 4 * a * c; rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString())); xs = M + N * rs; ys = P + Q * rs; } } }
public class Circle { public double[] center; public double radius; public Circle(double[] center, double radius) { this.center = center; this.radius = radius; } public String toString() { return String.format("Circle[x=%.2f,y=%.2f,r=%.2f]",center[0],center[1], radius); } } public class ApolloniusSolver { public static Circle solveApollonius(Circle c1, Circle c2, Circle c3, int s1, int s2, int s3) { float x1 = c1.center[0]; float y1 = c1.center[1]; float r1 = c1.radius; float x2 = c2.center[0]; float y2 = c2.center[1]; float r2 = c2.radius; float x3 = c3.center[0]; float y3 = c3.center[1]; float r3 = c3.radius; float v11 = 2*x2 - 2*x1; float v12 = 2*y2 - 2*y1; float v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2; float v14 = 2*s2*r2 - 2*s1*r1; float v21 = 2*x3 - 2*x2; float v22 = 2*y3 - 2*y2; float v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3; float v24 = 2*s3*r3 - 2*s2*r2; float w12 = v12/v11; float w13 = v13/v11; float w14 = v14/v11; float w22 = v22/v21-w12; float w23 = v23/v21-w13; float w24 = v24/v21-w14; float P = -w23/w22; float Q = w24/w22; float M = -w12*P-w13; float N = w14 - w12*Q; float a = N*N + Q*Q - 1; float b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1; float c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1; float D = b*b-4*a*c; float rs = (-b-Math.sqrt(D))/(2*a); float xs = M + N * rs; float ys = P + Q * rs; return new Circle(new double[]{xs,ys}, rs); } public static void main(final String[] args) { Circle c1 = new Circle(new double[]{0,0}, 1); Circle c2 = new Circle(new double[]{4,0}, 1); Circle c3 = new Circle(new double[]{2,4}, 2); System.out.println(solveApollonius(c1,c2,c3,1,1,1)); System.out.println(solveApollonius(c1,c2,c3,-1,-1,-1)); } }
Please provide an equivalent version of this C# code in Java.
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Rewrite this program in Java while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { public class FastaEntry { public string Name { get; set; } public StringBuilder Sequence { get; set; } } static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile) { FastaEntry f = null; string line; while ((line = fastaFile.ReadLine()) != null) { if (line.StartsWith(";")) continue; if (line.StartsWith(">")) { if (f != null) yield return f; f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() }; } else if (f != null) f.Sequence.Append(line); } yield return f; } static void Main(string[] args) { try { using (var fastaFile = new StreamReader("fasta.txt")) { foreach (FastaEntry f in ParseFasta(fastaFile)) Console.WriteLine("{0}: {1}", f.Name, f.Sequence); } } catch (FileNotFoundException e) { Console.WriteLine(e); } Console.ReadLine(); } }
import java.io.*; import java.util.Scanner; public class ReadFastaFile { public static void main(String[] args) throws FileNotFoundException { boolean first = true; try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.charAt(0) == '>') { if (first) first = false; else System.out.println(); System.out.printf("%s: ", line.substring(1)); } else { System.out.print(line); } } } System.out.println(); } }
Write the same code in Java as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; public class FindPalindromicNumbers { static void Main(string[] args) { var query = PalindromicTernaries() .Where(IsPalindromicBinary) .Take(6); foreach (var x in query) { Console.WriteLine("Decimal: " + x); Console.WriteLine("Ternary: " + ToTernary(x)); Console.WriteLine("Binary: " + Convert.ToString(x, 2)); Console.WriteLine(); } } public static IEnumerable<long> PalindromicTernaries() { yield return 0; yield return 1; yield return 13; yield return 23; var f = new List<long> {0}; long fMiddle = 9; while (true) { for (long edge = 1; edge < 3; edge++) { int i; do { long result = fMiddle; long fLeft = fMiddle * 3; long fRight = fMiddle / 3; for (int j = f.Count - 1; j >= 0; j--) { result += (fLeft + fRight) * f[j]; fLeft *= 3; fRight /= 3; } result += (fLeft + fRight) * edge; yield return result; for (i = f.Count - 1; i >= 0; i--) { if (f[i] == 2) { f[i] = 0; } else { f[i]++; break; } } } while (i >= 0); } f.Add(0); fMiddle *= 3; } } public static bool IsPalindromicBinary(long number) { long n = number; long reverse = 0; while (n != 0) { reverse <<= 1; if ((n & 1) == 1) reverse++; n >>= 1; } return reverse == number; } public static string ToTernary(long n) { if (n == 0) return "0"; string result = ""; while (n > 0) { { result = (n % 3) + result; n /= 3; } return result; } }
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Maintain the same structure and functionality when rewriting this code in Java.
using System; using System.Collections.Generic; using System.Linq; public class FindPalindromicNumbers { static void Main(string[] args) { var query = PalindromicTernaries() .Where(IsPalindromicBinary) .Take(6); foreach (var x in query) { Console.WriteLine("Decimal: " + x); Console.WriteLine("Ternary: " + ToTernary(x)); Console.WriteLine("Binary: " + Convert.ToString(x, 2)); Console.WriteLine(); } } public static IEnumerable<long> PalindromicTernaries() { yield return 0; yield return 1; yield return 13; yield return 23; var f = new List<long> {0}; long fMiddle = 9; while (true) { for (long edge = 1; edge < 3; edge++) { int i; do { long result = fMiddle; long fLeft = fMiddle * 3; long fRight = fMiddle / 3; for (int j = f.Count - 1; j >= 0; j--) { result += (fLeft + fRight) * f[j]; fLeft *= 3; fRight /= 3; } result += (fLeft + fRight) * edge; yield return result; for (i = f.Count - 1; i >= 0; i--) { if (f[i] == 2) { f[i] = 0; } else { f[i]++; break; } } } while (i >= 0); } f.Add(0); fMiddle *= 3; } } public static bool IsPalindromicBinary(long number) { long n = number; long reverse = 0; while (n != 0) { reverse <<= 1; if ((n & 1) == 1) reverse++; n >>= 1; } return reverse == number; } public static string ToTernary(long n) { if (n == 0) return "0"; string result = ""; while (n > 0) { { result = (n % 3) + result; n /= 3; } return result; } }
public class Pali23 { public static boolean isPali(String x){ return x.equals(new StringBuilder(x).reverse().toString()); } public static void main(String[] args){ for(long i = 0, count = 0; count < 6;i++){ if((i & 1) == 0 && (i != 0)) continue; if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){ System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3)); count++; } } } }
Transform the following C# implementation into Java, maintaining the same output and logic.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Change the following C# code into Java without altering its purpose.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
import java.math.BigInteger; import java.util.function.BiFunction; import java.util.function.Function; public class CipollasAlgorithm { private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151)); private static final BigInteger BIG_TWO = BigInteger.valueOf(2); private static class Point { BigInteger x; BigInteger y; Point(BigInteger x, BigInteger y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%s, %s)", this.x, this.y); } } private static class Triple { BigInteger x; BigInteger y; boolean b; Triple(BigInteger x, BigInteger y, boolean b) { this.x = x; this.y = y; this.b = b; } @Override public String toString() { return String.format("(%s, %s, %s)", this.x, this.y, this.b); } } private static Triple c(String ns, String ps) { BigInteger n = new BigInteger(ns); BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG; Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p); if (!ls.apply(n).equals(BigInteger.ONE)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } BigInteger a = BigInteger.ZERO; BigInteger omega2; while (true) { omega2 = a.multiply(a).add(p).subtract(n).mod(p); if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) { break; } a = a.add(BigInteger.ONE); } BigInteger finalOmega = omega2; BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point( aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p) ); Point r = new Point(BigInteger.ONE, BigInteger.ZERO); Point s = new Point(a, BigInteger.ONE); BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p); while (nn.compareTo(BigInteger.ZERO) > 0) { if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) { r = mul.apply(r, s); } s = mul.apply(s, s); nn = nn.shiftRight(1); } if (!r.y.equals(BigInteger.ZERO)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } if (!r.x.multiply(r.x).mod(p).equals(n)) { return new Triple(BigInteger.ZERO, BigInteger.ZERO, false); } return new Triple(r.x, p.subtract(r.x), true); } public static void main(String[] args) { System.out.println(c("10", "13")); System.out.println(c("56", "101")); System.out.println(c("8218", "10007")); System.out.println(c("8219", "10007")); System.out.println(c("331575", "1000003")); System.out.println(c("665165880", "1000000007")); System.out.println(c("881398088036", "1000000000039")); System.out.println(c("34035243914635549601583369544560650254325084643201", "")); } }
Change the programming language of this snippet from C# to Java without modifying what it does.
string path = @"C:\Windows\System32"; string multiline = @"Line 1. Line 2. Line 3.";
char a = 'a'; String b = "abc"; char doubleQuote = '"'; char singleQuote = '\''; String singleQuotes = "''"; String doubleQuotes = "\"\"";
Convert this C# block to Java, preserving its control flow and logic.
using System; using System.Drawing; using System.Windows.Forms; static class Program { static void Main() { Rectangle bounds = Screen.PrimaryScreen.Bounds; Console.WriteLine($"Primary screen bounds: {bounds.Width}x{bounds.Height}"); Rectangle workingArea = Screen.PrimaryScreen.WorkingArea; Console.WriteLine($"Primary screen working area: {workingArea.Width}x{workingArea.Height}"); } }
import java.awt.*; import javax.swing.JFrame; public class Test extends JFrame { public static void main(String[] args) { new Test(); } Test() { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); System.out.println("Physical screen size: " + screenSize); Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration()); System.out.println("Insets: " + insets); screenSize.width -= (insets.left + insets.right); screenSize.height -= (insets.top + insets.bottom); System.out.println("Max available: " + screenSize); } }
Write the same code in Java as shown below in C#.
enum fruits { apple, banana, cherry } enum fruits { apple = 0, banana = 1, cherry = 2 } enum fruits : int { apple = 0, banana = 1, cherry = 2 } [FlagsAttribute] enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
enum Fruits{ APPLE, BANANA, CHERRY }
Preserve the algorithm and functionality while converting the code from C# to Java.
using System; class Program { static void Main() { uint[] r = items1(); Console.WriteLine(r[0] + " v " + r[1] + " a " + r[2] + " b"); var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 1000; i > 0; i--) items1(); Console.Write(sw.Elapsed); Console.Read(); } static uint[] items0() { uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0; for (a = 0; a <= 10; a++) for (b = 0; a * 5 + b * 3 <= 50; b++) for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++) if (v0 < (v = a * 30 + b * 18 + c * 25)) { v0 = v; a0 = a; b0 = b; c0 = c; } return new uint[] { a0, b0, c0 }; } static uint[] items1() { uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0; for (a = 0; a <= 10; a++) for (b = 0; a * 5 + b * 3 <= 50; b++) { c = (250 - a * 25 - b * 15) / 2; if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1; if (v0 < (v = a * 30 + b * 18 + c * 25)) { v0 = v; a0 = a; b0 = b; c0 = c; } } return new uint[] { a0, b0, c0 }; } }
package hu.pj.alg; import hu.pj.obj.Item; import java.text.*; public class UnboundedKnapsack { protected Item [] items = { new Item("panacea", 3000, 0.3, 0.025), new Item("ichor" , 1800, 0.2, 0.015), new Item("gold" , 2500, 2.0, 0.002) }; protected final int n = items.length; protected Item sack = new Item("sack" , 0, 25.0, 0.250); protected Item best = new Item("best" , 0, 0.0, 0.000); protected int [] maxIt = new int [n]; protected int [] iIt = new int [n]; protected int [] bestAm = new int [n]; public UnboundedKnapsack() { for (int i = 0; i < n; i++) { maxIt [i] = Math.min( (int)(sack.getWeight() / items[i].getWeight()), (int)(sack.getVolume() / items[i].getVolume()) ); } calcWithRecursion(0); NumberFormat nf = NumberFormat.getInstance(); System.out.println("Maximum value achievable is: " + best.getValue()); System.out.print("This is achieved by carrying (one solution): "); for (int i = 0; i < n; i++) { System.out.print(bestAm[i] + " " + items[i].getName() + ", "); } System.out.println(); System.out.println("The weight to carry is: " + nf.format(best.getWeight()) + " and the volume used is: " + nf.format(best.getVolume()) ); } public void calcWithRecursion(int item) { for (int i = 0; i <= maxIt[item]; i++) { iIt[item] = i; if (item < n-1) { calcWithRecursion(item+1); } else { int currVal = 0; double currWei = 0.0; double currVol = 0.0; for (int j = 0; j < n; j++) { currVal += iIt[j] * items[j].getValue(); currWei += iIt[j] * items[j].getWeight(); currVol += iIt[j] * items[j].getVolume(); } if (currVal > best.getValue() && currWei <= sack.getWeight() && currVol <= sack.getVolume() ) { best.setValue (currVal); best.setWeight(currWei); best.setVolume(currVol); for (int j = 0; j < n; j++) bestAm[j] = iIt[j]; } } } } public static void main(String[] args) { new UnboundedKnapsack(); } }
Port the following code from C# to Java with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; class RangeExtraction { static void Main() { const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39"; var result = String.Join(",", RangesToStrings(GetRanges(testString))); Console.Out.WriteLine(result); } public static IEnumerable<IEnumerable<int>> GetRanges(string testString) { var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x)); var current = new List<int>(); foreach (var n in numbers) { if (current.Count == 0) { current.Add(n); } else { if (current.Max() + 1 == n) { current.Add(n); } else { yield return current; current = new List<int> { n }; } } } yield return current; } public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges) { foreach (var range in ranges) { if (range.Count() == 1) { yield return range.Single().ToString(); } else if (range.Count() == 2) { yield return range.Min() + "," + range.Max(); } else { yield return range.Min() + "-" + range.Max(); } } } }
public class RangeExtraction { public static void main(String[] args) { int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39}; int len = arr.length; int idx = 0, idx2 = 0; while (idx < len) { while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1); if (idx2 - idx > 2) { System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]); idx = idx2; } else { for (; idx < idx2; idx++) System.out.printf("%s,", arr[idx]); } } } }
Generate a Java translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Linq; class RangeExtraction { static void Main() { const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39"; var result = String.Join(",", RangesToStrings(GetRanges(testString))); Console.Out.WriteLine(result); } public static IEnumerable<IEnumerable<int>> GetRanges(string testString) { var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x)); var current = new List<int>(); foreach (var n in numbers) { if (current.Count == 0) { current.Add(n); } else { if (current.Max() + 1 == n) { current.Add(n); } else { yield return current; current = new List<int> { n }; } } } yield return current; } public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges) { foreach (var range in ranges) { if (range.Count() == 1) { yield return range.Single().ToString(); } else if (range.Count() == 2) { yield return range.Min() + "," + range.Max(); } else { yield return range.Min() + "-" + range.Max(); } } } }
public class RangeExtraction { public static void main(String[] args) { int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39}; int len = arr.length; int idx = 0, idx2 = 0; while (idx < len) { while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1); if (idx2 - idx > 2) { System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]); idx = idx2; } else { for (; idx < idx2; idx++) System.out.printf("%s,", arr[idx]); } } } }
Generate an equivalent Java version of this C# code.
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); ShowType(7.5); ShowType('d'); ShowType(true); ShowType("Rosetta"); ShowType(new C()); ShowType(new S()); ShowType(E.NONE); ShowType(new int[] { 1, 2, 3 }); } } }
public class TypeDetection { private static void showType(Object a) { if (a instanceof Integer) { System.out.printf("'%s' is an integer\n", a); } else if (a instanceof Double) { System.out.printf("'%s' is a double\n", a); } else if (a instanceof Character) { System.out.printf("'%s' is a character\n", a); } else { System.out.printf("'%s' is some other type\n", a); } } public static void main(String[] args) { showType(5); showType(7.5); showType('d'); showType(true); } }
Convert this C# block to Java, preserving its control flow and logic.
using System; namespace RosetaCode { class MainClass { public static void Main (string[] args) { int[,] list = new int[18,19]; string input = @"55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"; var charArray = input.Split ('\n'); for (int i=0; i < charArray.Length; i++) { var numArr = charArray[i].Trim().Split(' '); for (int j = 0; j<numArr.Length; j++) { int number = Convert.ToInt32 (numArr[j]); list [i, j] = number; } } for (int i = 16; i >= 0; i--) { for (int j = 0; j < 18; j++) { list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]); } } Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0])); } } }
import java.nio.file.*; import static java.util.Arrays.stream; public class MaxPathSum { public static void main(String[] args) throws Exception { int[][] data = Files.lines(Paths.get("triangle.txt")) .map(s -> stream(s.trim().split("\\s+")) .mapToInt(Integer::parseInt) .toArray()) .toArray(int[][]::new); for (int r = data.length - 1; r > 0; r--) for (int c = 0; c < data[r].length - 1; c++) data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]); System.out.println(data[0][0]); } }
Produce a language-to-language conversion: from C# to Java, same semantics.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks.FourBitAdder { public struct BitAdderOutput { public bool S { get; set; } public bool C { get; set; } public override string ToString ( ) { return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" ); } } public struct Nibble { public bool _1 { get; set; } public bool _2 { get; set; } public bool _3 { get; set; } public bool _4 { get; set; } public override string ToString ( ) { return ( _4 ? "1" : "0" ) + ( _3 ? "1" : "0" ) + ( _2 ? "1" : "0" ) + ( _1 ? "1" : "0" ); } } public struct FourBitAdderOutput { public Nibble N { get; set; } public bool C { get; set; } public override string ToString ( ) { return N.ToString ( ) + "c" + ( C ? "1" : "0" ); } } public static class LogicGates { public static bool Not ( bool A ) { return !A; } public static bool And ( bool A, bool B ) { return A && B; } public static bool Or ( bool A, bool B ) { return A || B; } public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); } } public static class ConstructiveBlocks { public static BitAdderOutput HalfAdder ( bool A, bool B ) { return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) }; } public static BitAdderOutput FullAdder ( bool A, bool B, bool CI ) { BitAdderOutput HA1 = HalfAdder ( CI, A ); BitAdderOutput HA2 = HalfAdder ( HA1.S, B ); return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) }; } public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI ) { BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI ); BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C ); BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C ); BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C ); return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C }; } public static void Test ( ) { Console.WriteLine ( "Four Bit Adder" ); for ( int i = 0; i < 256; i++ ) { Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; if ( (i & 1) == 1) { A._1 = true; } if ( ( i & 2 ) == 2 ) { A._2 = true; } if ( ( i & 4 ) == 4 ) { A._3 = true; } if ( ( i & 8 ) == 8 ) { A._4 = true; } if ( ( i & 16 ) == 16 ) { B._1 = true; } if ( ( i & 32 ) == 32) { B._2 = true; } if ( ( i & 64 ) == 64 ) { B._3 = true; } if ( ( i & 128 ) == 128 ) { B._4 = true; } Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) ); } Console.WriteLine ( ); } } }
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
Write a version of this C# function in Java with identical behavior.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks.FourBitAdder { public struct BitAdderOutput { public bool S { get; set; } public bool C { get; set; } public override string ToString ( ) { return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" ); } } public struct Nibble { public bool _1 { get; set; } public bool _2 { get; set; } public bool _3 { get; set; } public bool _4 { get; set; } public override string ToString ( ) { return ( _4 ? "1" : "0" ) + ( _3 ? "1" : "0" ) + ( _2 ? "1" : "0" ) + ( _1 ? "1" : "0" ); } } public struct FourBitAdderOutput { public Nibble N { get; set; } public bool C { get; set; } public override string ToString ( ) { return N.ToString ( ) + "c" + ( C ? "1" : "0" ); } } public static class LogicGates { public static bool Not ( bool A ) { return !A; } public static bool And ( bool A, bool B ) { return A && B; } public static bool Or ( bool A, bool B ) { return A || B; } public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); } } public static class ConstructiveBlocks { public static BitAdderOutput HalfAdder ( bool A, bool B ) { return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) }; } public static BitAdderOutput FullAdder ( bool A, bool B, bool CI ) { BitAdderOutput HA1 = HalfAdder ( CI, A ); BitAdderOutput HA2 = HalfAdder ( HA1.S, B ); return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) }; } public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI ) { BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI ); BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C ); BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C ); BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C ); return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C }; } public static void Test ( ) { Console.WriteLine ( "Four Bit Adder" ); for ( int i = 0; i < 256; i++ ) { Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; if ( (i & 1) == 1) { A._1 = true; } if ( ( i & 2 ) == 2 ) { A._2 = true; } if ( ( i & 4 ) == 4 ) { A._3 = true; } if ( ( i & 8 ) == 8 ) { A._4 = true; } if ( ( i & 16 ) == 16 ) { B._1 = true; } if ( ( i & 32 ) == 32) { B._2 = true; } if ( ( i & 64 ) == 64 ) { B._3 = true; } if ( ( i & 128 ) == 128 ) { B._4 = true; } Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) ); } Console.WriteLine ( ); } } }
public class GateLogic { public interface OneInputGate { boolean eval(boolean input); } public interface TwoInputGate { boolean eval(boolean input1, boolean input2); } public interface MultiGate { boolean[] eval(boolean... inputs); } public static OneInputGate NOT = new OneInputGate() { public boolean eval(boolean input) { return !input; } }; public static TwoInputGate AND = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 && input2; } }; public static TwoInputGate OR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return input1 || input2; } }; public static TwoInputGate XOR = new TwoInputGate() { public boolean eval(boolean input1, boolean input2) { return OR.eval( AND.eval(input1, NOT.eval(input2)), AND.eval(NOT.eval(input1), input2) ); } }; public static MultiGate HALF_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 2) throw new IllegalArgumentException(); return new boolean[] { XOR.eval(inputs[0], inputs[1]), AND.eval(inputs[0], inputs[1]) }; } }; public static MultiGate FULL_ADDER = new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != 3) throw new IllegalArgumentException(); boolean[] haOutputs1 = HALF_ADDER.eval(inputs[0], inputs[1]); boolean[] haOutputs2 = HALF_ADDER.eval(haOutputs1[0], inputs[2]); return new boolean[] { haOutputs2[0], OR.eval(haOutputs1[1], haOutputs2[1]) }; } }; public static MultiGate buildAdder(final int numBits) { return new MultiGate() { public boolean[] eval(boolean... inputs) { if (inputs.length != (numBits << 1)) throw new IllegalArgumentException(); boolean[] outputs = new boolean[numBits + 1]; boolean[] faInputs = new boolean[3]; boolean[] faOutputs = null; for (int i = 0; i < numBits; i++) { faInputs[0] = (faOutputs == null) ? false : faOutputs[1]; faInputs[1] = inputs[i]; faInputs[2] = inputs[numBits + i]; faOutputs = FULL_ADDER.eval(faInputs); outputs[i] = faOutputs[0]; } if (faOutputs != null) outputs[numBits] = faOutputs[1]; return outputs; } }; } public static void main(String[] args) { int numBits = Integer.parseInt(args[0]); int firstNum = Integer.parseInt(args[1]); int secondNum = Integer.parseInt(args[2]); int maxNum = 1 << numBits; if ((firstNum < 0) || (firstNum >= maxNum)) { System.out.println("First number is out of range"); return; } if ((secondNum < 0) || (secondNum >= maxNum)) { System.out.println("Second number is out of range"); return; } MultiGate multiBitAdder = buildAdder(numBits); boolean[] inputs = new boolean[numBits << 1]; String firstNumDisplay = ""; String secondNumDisplay = ""; for (int i = 0; i < numBits; i++) { boolean firstBit = ((firstNum >>> i) & 1) == 1; boolean secondBit = ((secondNum >>> i) & 1) == 1; inputs[i] = firstBit; inputs[numBits + i] = secondBit; firstNumDisplay = (firstBit ? "1" : "0") + firstNumDisplay; secondNumDisplay = (secondBit ? "1" : "0") + secondNumDisplay; } boolean[] outputs = multiBitAdder.eval(inputs); int outputNum = 0; String outputNumDisplay = ""; String outputCarryDisplay = null; for (int i = numBits; i >= 0; i--) { outputNum = (outputNum << 1) | (outputs[i] ? 1 : 0); if (i == numBits) outputCarryDisplay = outputs[i] ? "1" : "0"; else outputNumDisplay += (outputs[i] ? "1" : "0"); } System.out.println("numBits=" + numBits); System.out.println("A=" + firstNumDisplay + " (" + firstNum + "), B=" + secondNumDisplay + " (" + secondNum + "), S=" + outputCarryDisplay + " " + outputNumDisplay + " (" + outputNum + ")"); return; } }
Write a version of this C# function in Java with identical behavior.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Unix_ls { public class UnixLS { public static void Main(string[] args) { UnixLS ls = new UnixLS(); ls.list(args.Length.Equals(0) ? "." : args[0]); } private void list(string folder) { foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly)) { Console.WriteLine(fileSystemInfo.Name); } } } }
package rosetta; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class UnixLS { public static void main(String[] args) throws IOException { Files.list(Path.of("")).sorted().forEach(System.out::println); } }
Write the same algorithm in Java as shown in this C# implementation.
using System; using System.Text; namespace Rosetta { class Program { static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint)); static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes); static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; foreach (int unicodePoint in new int[] { 0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] asUtf8bytes = MyEncoder(unicodePoint); string theCharacter = MyDecoder(asUtf8bytes); Console.WriteLine("{0,8} {1,5} {2,-15}", unicodePoint.ToString("X4"), theCharacter, BitConverter.ToString(asUtf8bytes)); } } } }
import java.nio.charset.StandardCharsets; import java.util.Formatter; public class UTF8EncodeDecode { public static byte[] utf8encode(int codepoint) { return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8); } public static int utf8decode(byte[] bytes) { return new String(bytes, StandardCharsets.UTF_8).codePointAt(0); } public static void main(String[] args) { System.out.printf("%-7s %-43s %7s\t%s\t%7s%n", "Char", "Name", "Unicode", "UTF-8 encoded", "Decoded"); for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] encoded = utf8encode(codepoint); Formatter formatter = new Formatter(); for (byte b : encoded) { formatter.format("%02X ", b); } String encodedHex = formatter.toString(); int decoded = utf8decode(encoded); System.out.printf("%-7c %-43s U+%04X\t%-12s\tU+%04X%n", codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded); } } }
Maintain the same structure and functionality when rewriting this code in Java.
using System; namespace MagicSquareDoublyEven { class Program { static void Main(string[] args) { int n = 8; var result = MagicSquareDoublyEven(n); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) Console.Write("{0,2} ", result[i, j]); Console.WriteLine(); } Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2); Console.ReadLine(); } private static int[,] MagicSquareDoublyEven(int n) { if (n < 4 || n % 4 != 0) throw new ArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[,] result = new int[n, n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } } }
public class MagicSquareDoublyEven { public static void main(String[] args) { int n = 8; for (int[] row : magicSquareDoublyEven(n)) { for (int x : row) System.out.printf("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } static int[][] magicSquareDoublyEven(final int n) { if (n < 4 || n % 4 != 0) throw new IllegalArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[][] result = new int[n][n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } }
Convert this C# snippet to Java and keep its semantics consistent.
using System; using System.Collections.Generic; using System.Linq; namespace Same_Fringe { class Program { static void Main() { var rnd = new Random(110456); var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList(); var bt1 = new BinTree<int>(randList); Shuffle(randList, 428); var bt2 = new BinTree<int>(randList); Console.WriteLine(bt1.CompareTo(bt2) ? "True compare worked" : "True compare failed"); bt1.Insert(0); Console.WriteLine(bt1.CompareTo(bt2) ? "False compare failed" : "False compare worked"); } static void Shuffle<T>(List<T> values, int seed) { var rnd = new Random(seed); for (var i = 0; i < values.Count - 2; i++) { var iSwap = rnd.Next(values.Count - i) + i; var tmp = values[iSwap]; values[iSwap] = values[i]; values[i] = tmp; } } } class BinTree<T> where T:IComparable { private BinTree<T> _left; private BinTree<T> _right; private T _value; private BinTree<T> Left { get { return _left; } } private BinTree<T> Right { get { return _right; } } private T Value { get { return _value; } } public bool IsLeaf { get { return Left == null; } } private BinTree(BinTree<T> left, BinTree<T> right, T value) { _left = left; _right = right; _value = value; } public BinTree(T value) : this(null, null, value) { } public BinTree(IEnumerable<T> values) { _value = values.First(); foreach (var value in values.Skip(1)) { Insert(value); } } public void Insert(T value) { if (IsLeaf) { if (value.CompareTo(Value) < 0) { _left = new BinTree<T>(value); _right = new BinTree<T>(Value); } else { _left = new BinTree<T>(Value); _right = new BinTree<T>(value); _value = value; } } else { if (value.CompareTo(Value) < 0) { Left.Insert(value); } else { Right.Insert(value); } } } public IEnumerable<T> GetLeaves() { if (IsLeaf) { yield return Value; yield break; } foreach (var val in Left.GetLeaves()) { yield return val; } foreach (var val in Right.GetLeaves()) { yield return val; } } internal bool CompareTo(BinTree<T> other) { return other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f); } } }
import java.util.*; class SameFringe { public interface Node<T extends Comparable<? super T>> { Node<T> getLeft(); Node<T> getRight(); boolean isLeaf(); T getData(); } public static class SimpleNode<T extends Comparable<? super T>> implements Node<T> { private final T data; public SimpleNode<T> left; public SimpleNode<T> right; public SimpleNode(T data) { this(data, null, null); } public SimpleNode(T data, SimpleNode<T> left, SimpleNode<T> right) { this.data = data; this.left = left; this.right = right; } public Node<T> getLeft() { return left; } public Node<T> getRight() { return right; } public boolean isLeaf() { return ((left == null) && (right == null)); } public T getData() { return data; } public SimpleNode<T> addToTree(T data) { int cmp = data.compareTo(this.data); if (cmp == 0) throw new IllegalArgumentException("Same data!"); if (cmp < 0) { if (left == null) return (left = new SimpleNode<T>(data)); return left.addToTree(data); } if (right == null) return (right = new SimpleNode<T>(data)); return right.addToTree(data); } } public static <T extends Comparable<? super T>> boolean areLeavesSame(Node<T> node1, Node<T> node2) { Stack<Node<T>> stack1 = new Stack<Node<T>>(); Stack<Node<T>> stack2 = new Stack<Node<T>>(); stack1.push(node1); stack2.push(node2); while (((node1 = advanceToLeaf(stack1)) != null) & ((node2 = advanceToLeaf(stack2)) != null)) if (!node1.getData().equals(node2.getData())) return false; return (node1 == null) && (node2 == null); } private static <T extends Comparable<? super T>> Node<T> advanceToLeaf(Stack<Node<T>> stack) { while (!stack.isEmpty()) { Node<T> node = stack.pop(); if (node.isLeaf()) return node; Node<T> rightNode = node.getRight(); if (rightNode != null) stack.push(rightNode); Node<T> leftNode = node.getLeft(); if (leftNode != null) stack.push(leftNode); } return null; } public static void main(String[] args) { SimpleNode<Integer> headNode1 = new SimpleNode<Integer>(35, new SimpleNode<Integer>(25, new SimpleNode<Integer>(15, new SimpleNode<Integer>(10), new SimpleNode<Integer>(20)), new SimpleNode<Integer>(30)), new SimpleNode<Integer>(45, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50))); SimpleNode<Integer> headNode2 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(56, new SimpleNode<Integer>(50), null)))); SimpleNode<Integer> headNode3 = new SimpleNode<Integer>(24, new SimpleNode<Integer>(14, new SimpleNode<Integer>(10), new SimpleNode<Integer>(16, null, new SimpleNode<Integer>(20))), new SimpleNode<Integer>(34, new SimpleNode<Integer>(30), new SimpleNode<Integer>(42, new SimpleNode<Integer>(40), new SimpleNode<Integer>(50, null, new SimpleNode<Integer>(56))))); System.out.print("Leaves for set 1: "); simpleWalk(headNode1); System.out.println(); System.out.print("Leaves for set 2: "); simpleWalk(headNode2); System.out.println(); System.out.print("Leaves for set 3: "); simpleWalk(headNode3); System.out.println(); System.out.println("areLeavesSame(1, 2)? " + areLeavesSame(headNode1, headNode2)); System.out.println("areLeavesSame(2, 3)? " + areLeavesSame(headNode2, headNode3)); } public static void simpleWalk(Node<Integer> node) { if (node.isLeaf()) System.out.print(node.getData() + " "); else { Node<Integer> left = node.getLeft(); if (left != null) simpleWalk(left); Node<Integer> right = node.getRight(); if (right != null) simpleWalk(right); } } }
Generate an equivalent Java version of this C# code.
using System; using System.Collections.Generic; namespace PeacefulChessQueenArmies { using Position = Tuple<int, int>; enum Piece { Empty, Black, White } class Program { static bool IsAttacking(Position queen, Position pos) { return queen.Item1 == pos.Item1 || queen.Item2 == pos.Item2 || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2); } static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { var pos = new Position(i, j); foreach (var queen in pBlackQueens) { if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) { goto inner; } } foreach (var queen in pWhiteQueens) { if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.Add(pos); placingBlack = false; } else { pWhiteQueens.Add(pos); if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.RemoveAt(pBlackQueens.Count - 1); pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1); placingBlack = true; } inner: { } } } if (!placingBlack) { pBlackQueens.RemoveAt(pBlackQueens.Count - 1); } return false; } static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { var board = new Piece[n * n]; foreach (var queen in blackQueens) { board[queen.Item1 * n + queen.Item2] = Piece.Black; } foreach (var queen in whiteQueens) { board[queen.Item1 * n + queen.Item2] = Piece.White; } for (int i = 0; i < board.Length; i++) { if (i != 0 && i % n == 0) { Console.WriteLine(); } switch (board[i]) { case Piece.Black: Console.Write("B "); break; case Piece.White: Console.Write("W "); break; case Piece.Empty: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { Console.Write(" "); } else { Console.Write("# "); } break; } } Console.WriteLine("\n"); } static void Main() { var nms = new int[,] { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (int i = 0; i < nms.GetLength(0); i++) { Console.WriteLine("{0} black and {0} white queens on a {1} x {1} board:", nms[i, 1], nms[i, 0]); List<Position> blackQueens = new List<Position>(); List<Position> whiteQueens = new List<Position>(); if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) { PrintBoard(nms[i, 0], blackQueens, whiteQueens); } else { Console.WriteLine("No solution exists.\n"); } } } } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Peaceful { enum Piece { Empty, Black, White, } public static class Position { public int x, y; public Position(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj instanceof Position) { Position pos = (Position) obj; return pos.x == x && pos.y == y; } return false; } } private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } boolean placingBlack = true; for (int i = 0; i < n; ++i) { inner: for (int j = 0; j < n; ++j) { Position pos = new Position(i, j); for (Position queen : pBlackQueens) { if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) { continue inner; } } for (Position queen : pWhiteQueens) { if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) { continue inner; } } if (placingBlack) { pBlackQueens.add(pos); placingBlack = false; } else { pWhiteQueens.add(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.remove(pBlackQueens.size() - 1); pWhiteQueens.remove(pWhiteQueens.size() - 1); placingBlack = true; } } } if (!placingBlack) { pBlackQueens.remove(pBlackQueens.size() - 1); } return false; } private static boolean isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y); } private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { Piece[] board = new Piece[n * n]; Arrays.fill(board, Piece.Empty); for (Position queen : blackQueens) { board[queen.x + n * queen.y] = Piece.Black; } for (Position queen : whiteQueens) { board[queen.x + n * queen.y] = Piece.White; } for (int i = 0; i < board.length; ++i) { if ((i != 0) && i % n == 0) { System.out.println(); } Piece b = board[i]; if (b == Piece.Black) { System.out.print("B "); } else if (b == Piece.White) { System.out.print("W "); } else { int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { System.out.print("• "); } else { System.out.print("◦ "); } } } System.out.println('\n'); } public static void main(String[] args) { List<Position> nms = List.of( new Position(2, 1), new Position(3, 1), new Position(3, 2), new Position(4, 1), new Position(4, 2), new Position(4, 3), new Position(5, 1), new Position(5, 2), new Position(5, 3), new Position(5, 4), new Position(5, 5), new Position(6, 1), new Position(6, 2), new Position(6, 3), new Position(6, 4), new Position(6, 5), new Position(6, 6), new Position(7, 1), new Position(7, 2), new Position(7, 3), new Position(7, 4), new Position(7, 5), new Position(7, 6), new Position(7, 7) ); for (Position nm : nms) { int m = nm.y; int n = nm.x; System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n); List<Position> blackQueens = new ArrayList<>(); List<Position> whiteQueens = new ArrayList<>(); if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens); } else { System.out.println("No solution exists.\n"); } } } }
Convert this C# snippet to Java and keep its semantics consistent.
using System; using System.Collections.Generic; using System.Text; namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); } private static void moveToFront(int charIndex) { char toFront = symbolTable[charIndex]; for (int j = charIndex; j > 0; j--) { symbolTable[j] = symbolTable[j - 1]; } symbolTable[0] = toFront; } public static int[] Encode(string input) { setSymbolTable(); var output = new List<int>(); foreach (char c in input) { for (int i = 0; i < 26; i++) { if (symbolTable[i] == c) { output.Add(i); moveToFront(i); break; } } } return output.ToArray(); } public static string Decode(int[] input) { setSymbolTable(); var output = new StringBuilder(input.Length); foreach (int n in input) { output.Append(symbolTable[n]); moveToFront(n); } return output.ToString(); } static void Main(string[] args) { string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" }; int[] encoding; foreach (string s in testInputs) { Console.WriteLine($"Encoding for '{s}':"); encoding = Encode(s); foreach (int i in encoding) { Console.Write($"{i} "); } Console.WriteLine($"\nDecoding for '{s}':"); Console.WriteLine($"{Decode(encoding)}\n"); } } } }
import java.util.LinkedList; import java.util.List; public class MTF{ public static List<Integer> encode(String msg, String symTable){ List<Integer> output = new LinkedList<Integer>(); StringBuilder s = new StringBuilder(symTable); for(char c : msg.toCharArray()){ int idx = s.indexOf("" + c); output.add(idx); s = s.deleteCharAt(idx).insert(0, c); } return output; } public static String decode(List<Integer> idxs, String symTable){ StringBuilder output = new StringBuilder(); StringBuilder s = new StringBuilder(symTable); for(int idx : idxs){ char c = s.charAt(idx); output = output.append(c); s = s.deleteCharAt(idx).insert(0, c); } return output.toString(); } private static void test(String toEncode, String symTable){ List<Integer> encoded = encode(toEncode, symTable); System.out.println(toEncode + ": " + encoded); String decoded = decode(encoded, symTable); System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded); } public static void main(String[] args){ String symTable = "abcdefghijklmnopqrstuvwxyz"; test("broood", symTable); test("bananaaa", symTable); test("hiphophiphop", symTable); } }
Convert the following code from C# to Java, ensuring the logic remains intact.
using System.Diagnostics; namespace Execute { class Program { static void Main(string[] args) { Process.Start("cmd.exe", "/c dir"); } } }
import java.util.Scanner; import java.io.*; public class Program { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec("cmd /C dir"); Scanner sc = new Scanner(p.getInputStream()); while (sc.hasNext()) System.out.println(sc.nextLine()); } catch (IOException e) { System.out.println(e.getMessage()); } } }
Transform the following C# implementation into Java, maintaining the same output and logic.
using System; using System.Xml; using System.Xml.Schema; using System.IO; public class Test { public static void Main() { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add(null, "http: XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = sc; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); XmlReader reader = XmlReader.Create("http: while (reader.Read()); Console.WriteLine("The XML file is valid for the given xsd file"); } private static void ValidationCallBack(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: {0}", e.Message); } }
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import javax.xml.ws.Holder; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class XmlValidation { public static void main(String... args) throws MalformedURLException { URL schemaLocation = new URL("http: URL documentLocation = new URL("http: if (validate(schemaLocation, documentLocation)) { System.out.println("document is valid"); } else { System.out.println("document is invalid"); } } public static boolean minimalValidate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.validate(new StreamSource(documentLocation.toString())); return true; } catch (Exception e) { return false; } } public static boolean validate(URL schemaLocation, URL documentLocation) { SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); final Holder<Boolean> valid = new Holder<>(true); try { Validator validator = factory.newSchema(schemaLocation).newValidator(); validator.setErrorHandler(new ErrorHandler(){ @Override public void warning(SAXParseException exception) { System.out.println("warning: " + exception.getMessage()); } @Override public void error(SAXParseException exception) { System.out.println("error: " + exception.getMessage()); valid.value = false; } @Override public void fatalError(SAXParseException exception) throws SAXException { System.out.println("fatal error: " + exception.getMessage()); throw exception; }}); validator.validate(new StreamSource(documentLocation.toString())); return valid.value; } catch (SAXException e) { return false; } catch (Exception e) { System.err.println(e); return false; } } }
Keep all operations the same but rewrite the snippet in Java.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse(); private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) { if (index == values.Count) return current; if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0) return FindRecImpl(values, current, index + 1, comparer); return Max( FindRecImpl(values, current, index + 1, comparer), FindRecImpl(values, current + values[index], index + 1, comparer) ); } private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a; class Sequence<T> : IEnumerable<T> { public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null); public Sequence(T value, Sequence<T> tail) { Value = value; Tail = tail; Length = tail == null ? 0 : tail.Length + 1; } public T Value { get; } public Sequence<T> Tail { get; } public int Length { get; } public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s); public IEnumerator<T> GetEnumerator() { for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>(); for (E x : n) { Node<E> node = new Node<E>(); node.value = x; int i = Collections.binarySearch(pileTops, node); if (i < 0) i = ~i; if (i != 0) node.pointer = pileTops.get(i-1); if (i != pileTops.size()) pileTops.set(i, node); else pileTops.add(node); } List<E> result = new ArrayList<E>(); for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1); node != null; node = node.pointer) result.add(node.value); Collections.reverse(result); return result; } private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> { public E value; public Node<E> pointer; public int compareTo(Node<E> y) { return value.compareTo(y.value); } } public static void main(String[] args) { List<Integer> d = Arrays.asList(3,2,6,4,5,1); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15); System.out.printf("an L.I.S. of %s is %s\n", d, lis(d)); } }
Write a version of this C# function in Java with identical behavior.
public protected internal protected internal private private protected
public protected private static public void function(int x){ int y; { int z; } }
Translate the given C# code snippet into Java without altering its behavior.
using System; using System.Collections; using System.Collections.Generic; using System.Text; using static System.Linq.Enumerable; public static class BraceExpansion { enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat } const char L = '{', R = '}', S = ','; public static void Main() { string[] input = { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", @"{,{,gotta have{ ,\, again\, }}more }cowbell!", @"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" }; foreach (string text in input) Expand(text); } static void Expand(string input) { Token token = Tokenize(input); foreach (string value in token) Console.WriteLine(value); Console.WriteLine(); } static Token Tokenize(string input) { var tokens = new List<Token>(); var buffer = new StringBuilder(); bool escaping = false; int level = 0; foreach (char c in input) { (escaping, level, tokens, buffer) = c switch { _ when escaping => (false, level, tokens, buffer.Append(c)), '\\' => (true, level, tokens, buffer.Append(c)), L => (escaping, level + 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer), S when level > 0 => (escaping, level, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer), R when level > 0 => (escaping, level - 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer), _ => (escaping, level, tokens, buffer.Append(c)) }; } if (buffer.Length > 0) tokens.Add(buffer.Flush()); for (int i = 0; i < tokens.Count; i++) { if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) { tokens[i] = tokens[i].Value; } } return new Token(tokens, TokenType.Concat); } static List<Token> Merge(this List<Token> list) { int separators = 0; int last = list.Count - 1; for (int i = list.Count - 3; i >= 0; i--) { if (list[i].Type == TokenType.Separator) { separators++; Concat(list, i + 1, last); list.RemoveAt(i); last = i; } else if (list[i].Type == TokenType.OpenBrace) { Concat(list, i + 1, last); if (separators > 0) { list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate); list.RemoveRange(i+1, list.Count - i - 1); } else { list[i] = L.ToString(); list[^1] = R.ToString(); Concat(list, i, list.Count); } break; } } return list; } static void Concat(List<Token> list, int s, int e) { for (int i = e - 2; i >= s; i--) { (Token a, Token b) = (list[i], list[i+1]); switch (a.Type, b.Type) { case (TokenType.Text, TokenType.Text): list[i] = a.Value + b.Value; list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Concat): a.SubTokens.AddRange(b.SubTokens); list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Text) when b.Value == "": list.RemoveAt(i+1); break; case (TokenType.Text, TokenType.Concat) when a.Value == "": list.RemoveAt(i); break; default: list[i] = new Token(new [] { a, b }, TokenType.Concat); list.RemoveAt(i+1); break; } } } private struct Token : IEnumerable<string> { private List<Token>? _subTokens; public string Value { get; } public TokenType Type { get; } public List<Token> SubTokens => _subTokens ??= new List<Token>(); public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null); public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList()); public static implicit operator Token(string value) => new Token(value, TokenType.Text); public IEnumerator<string> GetEnumerator() => (Type switch { TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)), TokenType.Alternate => from t in SubTokens from s in t select s, _ => Repeat(Value, 1) }).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } static List<Token> With(this List<Token> list, Token token) { list.Add(token); return list; } static IEnumerable<Token> Range(this List<Token> list, Range range) { int start = range.Start.GetOffset(list.Count); int end = range.End.GetOffset(list.Count); for (int i = start; i < end; i++) yield return list[i]; } static string Flush(this StringBuilder builder) { string result = builder.ToString(); builder.Clear(); return result; } }
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) { System.out.println(); expand(s); } } public static void expand(String s) { expandR("", s, ""); } private static void expandR(String pre, String s, String suf) { int i1 = -1, i2 = 0; String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", " "); StringBuilder sb = null; outer: while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) { i2 = i1 + 1; sb = new StringBuilder(s); for (int depth = 1; i2 < s.length() && depth > 0; i2++) { char c = noEscape.charAt(i2); depth = (c == '{') ? ++depth : depth; depth = (c == '}') ? --depth : depth; if (c == ',' && depth == 1) { sb.setCharAt(i2, '\u0000'); } else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1) break outer; } } if (i1 == -1) { if (suf.length() > 0) expandR(pre + s, suf, ""); else System.out.printf("%s%s%s%n", pre, s, suf); } else { for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1)) expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf); } } }
Convert this C# snippet to Java and keep its semantics consistent.
using System; using System.ComponentModel; using System.Windows.Forms; class RosettaInteractionForm : Form { class NumberModel: INotifyPropertyChanged { Random rnd = new Random(); public event PropertyChangedEventHandler PropertyChanged = delegate {}; int _value; public int Value { get { return _value; } set { _value = value; PropertyChanged(this, new PropertyChangedEventArgs("Value")); } } public void ResetToRandom(){ Value = rnd.Next(5000); } } NumberModel model = new NumberModel{ Value = 0}; RosettaInteractionForm() { var tbNumber = new MaskedTextBox { Mask="0000", ResetOnSpace = false, Dock = DockStyle.Top }; tbNumber.DataBindings.Add("Text", model, "Value"); var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom}; btIncrement.Click += delegate { model.Value++; }; var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom}; btDecrement.Click += delegate { model.Value--; }; var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom }; btRandom.Click += delegate { if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes) model.ResetToRandom(); }; Controls.Add(tbNumber); Controls.Add(btIncrement); Controls.Add(btDecrement); Controls.Add(btRandom); } static void Main() { Application.Run(new RosettaInteractionForm()); } }
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class Interact extends JFrame{ final JTextField numberField; final JButton incButton, randButton; public Interact(){ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); numberField = new JTextField(); incButton = new JButton("Increment"); randButton = new JButton("Random"); numberField.setText("0"); numberField.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if(!Character.isDigit(e.getKeyChar())){ e.consume(); } } @Override public void keyReleased(KeyEvent e){} @Override public void keyPressed(KeyEvent e){} }); incButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = numberField.getText(); if(text.isEmpty()){ numberField.setText("1"); }else{ numberField.setText((Long.valueOf(text) + 1) + ""); } } }); randButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if(JOptionPane.showConfirmDialog(null, "Are you sure?") == JOptionPane.YES_OPTION){ numberField.setText(Long.toString((long)(Math.random() * Long.MAX_VALUE))); } } }); setLayout(new GridLayout(2, 1)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); buttonPanel.add(incButton); buttonPanel.add(randButton); add(numberField); add(buttonPanel); pack(); } public static void main(String[] args){ new Interact().setVisible(true); } }
Keep all operations the same but rewrite the snippet in Java.
class Program { private static Random rnd = new Random(); public static int one_of_n(int n) { int currentChoice = 1; for (int i = 2; i <= n; i++) { double outerLimit = 1D / (double)i; if (rnd.NextDouble() < outerLimit) currentChoice = i; } return currentChoice; } static void Main(string[] args) { Dictionary<int, int> results = new Dictionary<int, int>(); for (int i = 1; i < 11; i++) results.Add(i, 0); for (int i = 0; i < 1000000; i++) { int result = one_of_n(10); results[result] = results[result] + 1; } for (int i = 1; i < 11; i++) Console.WriteLine("{0}\t{1}", i, results[i]); Console.ReadLine(); } }
import java.util.Arrays; import java.util.Random; public class OneOfNLines { static Random rand; public static int oneOfN(int n) { int choice = 0; for(int i = 1; i < n; i++) { if(rand.nextInt(i+1) == 0) choice = i; } return choice; } public static void main(String[] args) { int n = 10; int trials = 1000000; int[] bins = new int[n]; rand = new Random(); for(int i = 0; i < trials; i++) bins[oneOfN(n)]++; System.out.println(Arrays.toString(bins)); } }
Please provide an equivalent version of this C# code in Java.
using System; namespace AdditionChains { class Program { static int[] Prepend(int n, int[] seq) { int[] result = new int[seq.Length + 1]; Array.Copy(seq, 0, result, 1, seq.Length); result[0] = n; return result; } static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0); if (seq[0] == n) return new Tuple<int, int>(pos, 1); if (pos < min_len) return TryPerm(0, pos, seq, n, min_len); return new Tuple<int, int>(min_len, 0); } static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Tuple<int, int>(min_len, 0); Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len); Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1); if (res2.Item1 < res1.Item1) return res2; if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2); throw new Exception("TryPerm exception"); } static Tuple<int, int> InitTryPerm(int x) { return TryPerm(0, 0, new int[] { 1 }, x, 12); } static void FindBrauer(int num) { Tuple<int, int> res = InitTryPerm(num); Console.WriteLine(); Console.WriteLine("N = {0}", num); Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1); Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2); } static void Main(string[] args) { int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; Array.ForEach(nums, n => FindBrauer(n)); } } }
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); } } }
Rewrite the snippet below in Java so it works the same as the original C# code.
using System; namespace Repeat { class Program { static void Repeat(int count, Action<int> fn) { if (null == fn) { throw new ArgumentNullException("fn"); } for (int i = 0; i < count; i++) { fn.Invoke(i + 1); } } static void Main(string[] args) { Repeat(3, x => Console.WriteLine("Example {0}", x)); } } }
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 this program into Java but keep the logic exactly as in C#.
public class Program { static void Main() { System.Console.WriteLine(42.ModInverse(2017)); } } public static class IntExtensions { public static int ModInverse(this int a, int m) { if (m == 1) return 0; int m0 = m; (int x, int y) = (1, 0); while (a > 1) { int q = a / m; (a, m) = (m, a % m); (x, y) = (y, x - q * y); } return x < 0 ? x + m0 : x; } }
System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
Write a version of this C# function in Java with identical behavior.
using System.Text; using System.Net.Sockets; using System.Net; namespace WebServer { class GoodByeWorld { static void Main(string[] args) { const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n"; const int port = 8080; bool serverRunning = true; TcpListener tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); while (serverRunning) { Socket socketConnection = tcpListener.AcceptSocket(); byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length); socketConnection.Send(bMsg); socketConnection.Disconnect(true); } } } }
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(); } } }
Produce a functionally identical Java code for the snippet given in C#.
using System.Text; using System.Net.Sockets; using System.Net; namespace WebServer { class GoodByeWorld { static void Main(string[] args) { const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n"; const int port = 8080; bool serverRunning = true; TcpListener tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); while (serverRunning) { Socket socketConnection = tcpListener.AcceptSocket(); byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length); socketConnection.Send(bMsg); socketConnection.Disconnect(true); } } } }
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(); } } }
Convert the following code from C# to Java, ensuring the logic remains intact.
System.Console.Clear();
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
Transform the following C# implementation into Java, maintaining the same output and logic.
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
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(); } } }
Write a version of this C# function in Java with identical behavior.
using System; namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2; static void Main(string[] args) { bool[] found = new bool[MAX + 1]; bool[] a2b2 = new bool[MAX2 + 1]; int s = 3; for(int a = 1; a <= MAX; a++) { int a2 = a * a; for (int b=a; b<=MAX; b++) { a2b2[a2 + b * b] = true; } } for (int c = 1; c <= MAX; c++) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= MAX; d++) { if (a2b2[s1]) found[d] = true; s1 += s2; s2 += 2; } } Console.WriteLine("The values of d <= {0} which can't be represented:", MAX); for (int d = 1; d < MAX; d++) { if (!found[d]) Console.Write("{0} ", d); } Console.WriteLine(); } } }
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; } }
Convert this C# snippet to Java and keep its semantics consistent.
using System.Collections.Generic; using System.Linq; using System.Text; namespace SokobanSolver { public class SokobanSolver { private class Board { public string Cur { get; internal set; } public string Sol { get; internal set; } public int X { get; internal set; } public int Y { get; internal set; } public Board(string cur, string sol, int x, int y) { Cur = cur; Sol = sol; X = x; Y = y; } } private string destBoard, currBoard; private int playerX, playerY, nCols; SokobanSolver(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][c]; destBuf.Append(ch != '$' && ch != '@' ? ch : ' '); currBuf.Append(ch != '.' ? ch : ' '); if (ch == '@') { this.playerX = c; this.playerY = r; } } } destBoard = destBuf.ToString(); currBoard = currBuf.ToString(); } private string Move(int x, int y, int dx, int dy, string trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard[newPlayerPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[newPlayerPos] = '@'; return new string(trial); } private string Push(int x, int y, int dx, int dy, string trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard[newBoxPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = '$'; return new string(trial); } private bool IsSolved(string trialBoard) { for (int i = 0; i < trialBoard.Length; i++) if ((destBoard[i] == '.') != (trialBoard[i] == '$')) return false; return true; } private string Solve() { char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } }; int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } }; ISet<string> history = new HashSet<string>(); LinkedList<Board> open = new LinkedList<Board>(); history.Add(currBoard); open.AddLast(new Board(currBoard, string.Empty, playerX, playerY)); while (!open.Count.Equals(0)) { Board item = open.First(); open.RemoveFirst(); string cur = item.Cur; string sol = item.Sol; int x = item.X; int y = item.Y; for (int i = 0; i < dirs.GetLength(0); i++) { string trial = cur; int dx = dirs[i, 0]; int dy = dirs[i, 1]; if (trial[(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.AddLast(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.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } } return "No solution"; } public static void Main(string[] a) { string level = "#######," + "# #," + "# #," + "#. # #," + "#. $$ #," + "#.$$ #," + "#.# @#," + "#######"; System.Console.WriteLine("Level:\n"); foreach (string line in level.Split(',')) { System.Console.WriteLine(line); } System.Console.WriteLine("\nSolution:\n"); System.Console.WriteLine(new SokobanSolver(level.Split(',')).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()); } }
Translate the given C# code snippet into Java without altering its behavior.
using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static bool soas(int n, IEnumerable<int> f) { if (n <= 0) return false; if (f.Contains(n)) return true; switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true; case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0); return soas(d, rf) || soas(n, rf); } return true; } static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList(); return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f)); } static void Main() { int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2) if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : ""); Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m); do Write("\n{0,5} is a{1}practical number.", m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
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(); } }
Translate this program into Java but keep the logic exactly as in C#.
double d = 1; d = 1d; d = 1D; d = 1.2; d = 1.2d; d = .2; d = 12e-12; d = 12E-12; d = 1_234e-1_2; float f = 1; f = 1f; f = 1F; f = 1.2f; f = .2f; f = 12e-12f; f = 12E-12f; f = 1_234e-1_2f; decimal m = 1; m = 1m; m = 1m; m = 1.2m; m = .2m; m = 12e-12m; m = 12E-12m; m = 1_234e-1_2m;
1. 1.0 2432311.7567374 1.234E-10 1.234e-10 758832d 728832f 1.0f 758832D 728832F 1.0F 1 / 2. 1 / 2
Translate the given C# code snippet into Java without altering its behavior.
using System; using static System.Console; class Program { const int lmt = (int)1e6, first = 2500; static int[] f = new int[10]; static void Main(string[] args) { f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++) f[b] = f[a] * (b + 1); int pc = 0, nth = 0, lv = 0; for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) { if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " "); nth++; lv = i; } Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); } static string ord(int n) { return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; } static bool is_erdos_prime(int p) { if (!is_pr(p)) return false; int m = 0, t; while ((t = p - f[m++]) > 0) if (is_pr(t)) return false; return true; bool is_pr(int x) { if (x < 4) return x > 1; if ((x & 1) == 0) return false; for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } } }
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } 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; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
Keep all operations the same but rewrite the snippet in Java.
using System; using static System.Console; class Program { const int lmt = (int)1e6, first = 2500; static int[] f = new int[10]; static void Main(string[] args) { f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++) f[b] = f[a] * (b + 1); int pc = 0, nth = 0, lv = 0; for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) { if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " "); nth++; lv = i; } Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); } static string ord(int n) { return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; } static bool is_erdos_prime(int p) { if (!is_pr(p)) return false; int m = 0, t; while ((t = p - f[m++]) > 0) if (is_pr(t)) return false; return true; bool is_pr(int x) { if (x < 4) return x > 1; if ((x & 1) == 0) return false; for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } } }
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } 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; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
Convert the following code from C# to Java, ensuring the logic remains intact.
using System; using static System.Console; class Program { const int lmt = (int)1e6, first = 2500; static int[] f = new int[10]; static void Main(string[] args) { f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++) f[b] = f[a] * (b + 1); int pc = 0, nth = 0, lv = 0; for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) { if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " "); nth++; lv = i; } Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); } static string ord(int n) { return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; } static bool is_erdos_prime(int p) { if (!is_pr(p)) return false; int m = 0, t; while ((t = p - f[m++]) > 0) if (is_pr(t)) return false; return true; bool is_pr(int x) { if (x < 4) return x > 1; if ((x & 1) == 0) return false; for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } } }
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < maxCount; ++prime) { if (erdos(sieve, prime)) { ++count; if (prime < maxPrint) { System.out.printf("%6d", prime); if (count % 10 == 0) System.out.println(); } if (count == maxCount) System.out.printf("\n\nThe %dth Erd\u0151s prime is %d.\n", maxCount, prime); } } } private static boolean erdos(boolean[] sieve, int p) { if (!sieve[p]) return false; for (int k = 1, f = 1; f < p; ++k, f *= k) { if (sieve[p - f]) return false; } return true; } 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; ; p += 2) { int q = p * p; if (q >= limit) break; if (sieve[p]) { int inc = 2 * p; for (; q < limit; q += inc) sieve[q] = false; } } return sieve; } }
Convert this C# block to Java, preserving its control flow and logic.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
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(); } } }
Rewrite this program in Java while keeping its functionality equivalent to the C# version.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
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(); } } }
Change the programming language of this snippet from C# to Java without modifying what it does.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
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 a version of this C# function in Java with identical behavior.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
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))); } }
Convert this C# snippet to Java and keep its semantics consistent.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
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))); } }
Change the programming language of this snippet from C# to Java without modifying what it does.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
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(); } } }
Ensure the translated Java code behaves exactly like the original C# snippet.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
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(); } } }
Ensure the translated Java code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("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"), ("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"), ("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") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
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 this program into Java but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("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"), ("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"), ("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") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
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 this program in Java while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Wordseach { static class Program { readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; class Grid { public char[,] Cells = new char[nRows, nCols]; public List<string> Solutions = new List<string>(); public int NumAttempts; } readonly static int nRows = 10; readonly static int nCols = 10; readonly static int gridSize = nRows * nCols; readonly static int minWords = 25; readonly static Random rand = new Random(); static void Main(string[] args) { PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))); } private static List<string> ReadWords(string filename) { int maxLen = Math.Max(nRows, nCols); return System.IO.File.ReadAllLines(filename) .Select(s => s.Trim().ToLower()) .Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$")) .ToList(); } private static Grid CreateWordSearch(List<string> words) { int numAttempts = 0; while (++numAttempts < 100) { words.Shuffle(); var grid = new Grid(); int messageLen = PlaceMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; foreach (var word in words) { cellsFilled += TryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.Solutions.Count >= minWords) { grid.NumAttempts = numAttempts; return grid; } else break; } } } return null; } private static int TryPlaceWord(Grid grid, string word) { int randDir = rand.Next(dirs.GetLength(0)); int randPos = rand.Next(gridSize); for (int dir = 0; dir < dirs.GetLength(0); dir++) { dir = (dir + randDir) % dirs.GetLength(0); 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; } private 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[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[i]) overlaps++; else grid.Cells[rr, cc] = word[i]; if (i < len - 1) { cc += dirs[dir, 0]; rr += dirs[dir, 1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})"); } return lettersPlaced; } private static int PlaceMessage(Grid grid, string msg) { msg = Regex.Replace(msg.ToUpper(), "[^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.Next(gapSize); grid.Cells[pos / nCols, pos % nCols] = msg[i]; } return messageLen; } return 0; } public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rand.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } private static void PrintResult(Grid grid) { if (grid == null || grid.NumAttempts == 0) { Console.WriteLine("No grid to display"); return; } int size = grid.Solutions.Count; Console.WriteLine("Attempts: " + grid.NumAttempts); Console.WriteLine("Number of words: " + size); Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { Console.Write("\n{0} ", r); for (int c = 0; c < nCols; c++) Console.Write(" {0} ", grid.Cells[r, c]); } Console.WriteLine("\n"); for (int i = 0; i < size - 1; i += 2) { Console.WriteLine("{0} {1}", grid.Solutions[i], grid.Solutions[i + 1]); } if (size % 2 == 1) Console.WriteLine(grid.Solutions[size - 1]); Console.ReadLine(); } } }
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 C# snippet to Java and keep its semantics consistent.
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
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 C# code snippet into Java without altering its behavior.
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
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}"); } }
Write a version of this C# function in Java with identical behavior.
using System; using System.IO; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace Object_serialization { [Serializable] public class Being { public bool Alive { get; set; } } [Serializable] public class Animal: Being { public Animal() { } public Animal(long id, string name, bool alive = true) { Id = id; Name = name; Alive = alive; } public long Id { get; set; } public string Name { get; set; } public void Print() { Console.WriteLine("{0}, id={1} is {2}", Name, Id, Alive ? "alive" : "dead"); } } internal class Program { private static void Main() { string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\objects.dat"; var n = new List<Animal> { new Animal(1, "Fido"), new Animal(2, "Lupo"), new Animal(7, "Wanda"), new Animal(3, "Kiki", alive: false) }; foreach(Animal animal in n) animal.Print(); using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write)) new BinaryFormatter().Serialize(stream, n); n.Clear(); Console.WriteLine("---------------"); List<Animal> m; using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) m = (List<Animal>) new BinaryFormatter().Deserialize(stream); foreach(Animal animal in m) animal.Print(); } } }
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); } } }
Preserve the algorithm and functionality while converting the code from C# to Java.
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
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); } } }
Convert this C# block to Java, preserving its control flow and logic.
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
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); } } }
Translate the given C# code snippet into Java without altering its behavior.
using static System.Console; using System.Collections.Generic; using System.Linq; using System.Globalization; public static class Program { public static void Main() { WriteLine("Long years in the 21st century:"); WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53))); } public static IEnumerable<int> To(this int start, int end) { for (int i = start; i < end; i++) yield return i; } }
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; } }
Keep all operations the same but rewrite the snippet in Java.
using System; using System.Collections.Generic; using System.Linq; namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.Add(i); if (i != j) { divs.Add(j); } } } return divs; } static bool IsPartSum(List<int> divs, int sum) { if (sum == 0) { return true; } var le = divs.Count; if (le == 0) { return false; } var last = divs[le - 1]; List<int> newDivs = new List<int>(); for (int i = 0; i < le - 1; i++) { newDivs.Add(divs[i]); } if (last > sum) { return IsPartSum(newDivs, sum); } return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last); } static bool IsZumkeller(int n) { var divs = GetDivisors(n); var sum = divs.Sum(); if (sum % 2 == 1) { return false; } if (n % 2 == 1) { var abundance = sum - 2 * n; return abundance > 0 && abundance % 2 == 0; } return IsPartSum(divs, sum / 2); } static void Main() { Console.WriteLine("The first 220 Zumkeller numbers are:"); int i = 2; for (int count = 0; count < 220; i++) { if (IsZumkeller(i)) { Console.Write("{0,3} ", i); count++; if (count % 20 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (IsZumkeller(i)) { Console.Write("{0,5} ", i); count++; if (count % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (i % 10 != 5 && IsZumkeller(i)) { Console.Write("{0,7} ", i); count++; if (count % 8 == 0) { Console.WriteLine(); } } } } } }
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; } }
Generate an equivalent Java version of this C# code.
using System; using System.Collections.Generic; using System.Linq; namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.Add(i); if (i != j) { divs.Add(j); } } } return divs; } static bool IsPartSum(List<int> divs, int sum) { if (sum == 0) { return true; } var le = divs.Count; if (le == 0) { return false; } var last = divs[le - 1]; List<int> newDivs = new List<int>(); for (int i = 0; i < le - 1; i++) { newDivs.Add(divs[i]); } if (last > sum) { return IsPartSum(newDivs, sum); } return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last); } static bool IsZumkeller(int n) { var divs = GetDivisors(n); var sum = divs.Sum(); if (sum % 2 == 1) { return false; } if (n % 2 == 1) { var abundance = sum - 2 * n; return abundance > 0 && abundance % 2 == 0; } return IsPartSum(divs, sum / 2); } static void Main() { Console.WriteLine("The first 220 Zumkeller numbers are:"); int i = 2; for (int count = 0; count < 220; i++) { if (IsZumkeller(i)) { Console.Write("{0,3} ", i); count++; if (count % 20 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (IsZumkeller(i)) { Console.Write("{0,5} ", i); count++; if (count % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (i % 10 != 5 && IsZumkeller(i)) { Console.Write("{0,7} ", i); count++; if (count % 8 == 0) { Console.WriteLine(); } } } } } }
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; } }
Generate a Java translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var baseData = new Dictionary<string, object> { ["name"] = "Rocket Skates", ["price"] = 12.75, ["color"] = "yellow" }; var updateData = new Dictionary<string, object> { ["price"] = 15.25, ["color"] = "red", ["year"] = 1974 }; var mergedData = new Dictionary<string, object>(); foreach (var entry in baseData.Concat(updateData)) { mergedData[entry.Key] = entry.Value; } foreach (var entry in mergedData) { Console.WriteLine(entry); } } }
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); } }
Convert this C# snippet to Java and keep its semantics consistent.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var baseData = new Dictionary<string, object> { ["name"] = "Rocket Skates", ["price"] = 12.75, ["color"] = "yellow" }; var updateData = new Dictionary<string, object> { ["price"] = 15.25, ["color"] = "red", ["year"] = 1974 }; var mergedData = new Dictionary<string, object>(); foreach (var entry in baseData.Concat(updateData)) { mergedData[entry.Key] = entry.Value; } foreach (var entry in mergedData) { Console.WriteLine(entry); } } }
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); } }
Rewrite this program in Java while keeping its functionality equivalent to the C# version.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(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 C# block to Java, preserving its control flow and logic.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(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; } }
Please provide an equivalent version of this C# code in Java.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(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; } }
Rewrite this program in Java while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MarkovChainTextGenerator { class Program { static string Join(string a, string b) { return a + " " + b; } static string Markov(string filePath, int keySize, int outputSize) { if (keySize < 1) throw new ArgumentException("Key size can't be less than 1"); string body; using (StreamReader sr = new StreamReader(filePath)) { body = sr.ReadToEnd(); } var words = body.Split(); if (outputSize < keySize || words.Length < outputSize) { throw new ArgumentException("Output size is out of range"); } Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); for (int i = 0; i < words.Length - keySize; i++) { var key = words.Skip(i).Take(keySize).Aggregate(Join); string value; if (i + keySize < words.Length) { value = words[i + keySize]; } else { value = ""; } if (dict.ContainsKey(key)) { dict[key].Add(value); } else { dict.Add(key, new List<string>() { value }); } } Random rand = new Random(); List<string> output = new List<string>(); int n = 0; int rn = rand.Next(dict.Count); string prefix = dict.Keys.Skip(rn).Take(1).Single(); output.AddRange(prefix.Split()); while (true) { var suffix = dict[prefix]; if (suffix.Count == 1) { if (suffix[0] == "") { return output.Aggregate(Join); } output.Add(suffix[0]); } else { rn = rand.Next(suffix.Count); output.Add(suffix[rn]); } if (output.Count >= outputSize) { return output.Take(outputSize).Aggregate(Join); } n++; prefix = output.Skip(n).Take(keySize).Aggregate(Join); } } static void Main(string[] args) { Console.WriteLine(Markov("alice_oz.txt", 3, 200)); } } }
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)); } }
Keep all operations the same but rewrite the snippet in Java.
using static System.Linq.Enumerable; using static System.String; using static System.Console; using System.Collections.Generic; using System; using EdgeList = System.Collections.Generic.List<(int node, double weight)>; public static class Dijkstra { public static void Main() { Graph graph = new Graph(6); Func<char, int> id = c => c - 'a'; Func<int , char> name = i => (char)(i + 'a'); foreach (var (start, end, cost) in new [] { ('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), }) { graph.AddEdge(id(start), id(end), cost); } var path = graph.FindPath(id('a')); for (int d = id('b'); d <= id('f'); d++) { WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse())); } IEnumerable<(double distance, int node)> Path(int start, int destination) { yield return (path[destination].distance, destination); for (int i = destination; i != start; i = path[i].prev) { yield return (path[path[i].prev].distance, path[i].prev); } } } } sealed class Graph { private readonly List<EdgeList> adjacency; public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList(); public int Count => adjacency.Count; public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e); public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0; public bool AddEdge(int s, int e, double weight) { if (HasEdge(s, e)) return false; adjacency[s].Add((e, weight)); return true; } public (double distance, int prev)[] FindPath(int start) { var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray(); info[start].distance = 0; var visited = new System.Collections.BitArray(adjacency.Count); var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance)); heap.Push((start, 0)); while (heap.Count > 0) { var current = heap.Pop(); if (visited[current.node]) continue; var edges = adjacency[current.node]; for (int n = 0; n < edges.Count; n++) { int v = edges[n].node; if (visited[v]) continue; double alt = info[current.node].distance + edges[n].weight; if (alt < info[v].distance) { info[v] = (alt, current.node); heap.Push((v, alt)); } } visited[current.node] = true; } return info; } } sealed class Heap<T> { private readonly IComparer<T> comparer; private readonly List<T> list = new List<T> { default }; public Heap() : this(default(IComparer<T>)) { } public Heap(IComparer<T> comparer) { this.comparer = comparer ?? Comparer<T>.Default; } public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { } public int Count => list.Count - 1; public void Push(T element) { list.Add(element); SiftUp(list.Count - 1); } public T Pop() { T result = list[1]; list[1] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); SiftDown(1); return result; } private static int Parent(int i) => i / 2; private static int Left(int i) => i * 2; private static int Right(int i) => i * 2 + 1; private void SiftUp(int i) { while (i > 1) { int parent = Parent(i); if (comparer.Compare(list[i], list[parent]) > 0) return; (list[parent], list[i]) = (list[i], list[parent]); i = parent; } } private void SiftDown(int i) { for (int left = Left(i); left < list.Count; left = Left(i)) { int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i; int right = Right(i); if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right; if (smallest == i) return; (list[i], list[smallest]) = (list[smallest], list[i]); i = smallest; } } }
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(); } } }
Preserve the algorithm and functionality while converting the code from C# to Java.
using System; using System.Text; namespace GeometricAlgebra { struct Vector { private readonly double[] dims; public Vector(double[] da) { dims = da; } public static Vector operator -(Vector v) { return v * -1.0; } public static Vector operator +(Vector lhs, Vector rhs) { var result = new double[32]; Array.Copy(lhs.dims, 0, result, 0, lhs.Length); for (int i = 0; i < result.Length; i++) { result[i] = lhs[i] + rhs[i]; } return new Vector(result); } public static Vector operator *(Vector lhs, Vector rhs) { var result = new double[32]; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != 0.0) { for (int j = 0; j < lhs.Length; j++) { if (rhs[j] != 0.0) { var s = ReorderingSign(i, j) * lhs[i] * rhs[j]; var k = i ^ j; result[k] += s; } } } } return new Vector(result); } public static Vector operator *(Vector v, double scale) { var result = (double[])v.dims.Clone(); for (int i = 0; i < result.Length; i++) { result[i] *= scale; } return new Vector(result); } public double this[int key] { get { return dims[key]; } set { dims[key] = value; } } public int Length { get { return dims.Length; } } public Vector Dot(Vector rhs) { return (this * rhs + rhs * this) * 0.5; } 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 >>= 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } public override string ToString() { var it = dims.GetEnumerator(); StringBuilder sb = new StringBuilder("["); if (it.MoveNext()) { sb.Append(it.Current); } while (it.MoveNext()) { sb.Append(", "); sb.Append(it.Current); } sb.Append(']'); return sb.ToString(); } } class Program { static double[] DoubleArray(uint size) { double[] result = new double[size]; for (int i = 0; i < size; i++) { result[i] = 0.0; } return result; } static Vector E(int n) { if (n > 4) { throw new ArgumentException("n must be less than 5"); } var result = new Vector(DoubleArray(32)); result[1 << n] = 1.0; return result; } static readonly Random r = new Random(); static Vector RandomVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < 5; i++) { var singleton = new double[] { r.NextDouble() }; result += new Vector(singleton) * E(i); } return result; } static Vector RandomMultiVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < result.Length; i++) { result[i] = r.NextDouble(); } return result; } static void Main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (E(i).Dot(E(j))[0] != 0.0) { Console.WriteLine("Unexpected non-null sclar product."); return; } } else if (i == j) { if ((E(i).Dot(E(j)))[0] == 0.0) { Console.WriteLine("Unexpected null sclar product."); } } } } var a = RandomMultiVector(); var b = RandomMultiVector(); var c = RandomMultiVector(); var x = RandomVector(); Console.WriteLine((a * b) * c); Console.WriteLine(a * (b * c)); Console.WriteLine(); Console.WriteLine(a * (b + c)); Console.WriteLine(a * b + a * c); Console.WriteLine(); Console.WriteLine((a + b) * c); Console.WriteLine(a * c + b * c); Console.WriteLine(); Console.WriteLine(x * x); } } }
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)); } }
Write the same code in Java as shown below in C#.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new 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 the following code from C# to Java, ensuring the logic remains intact.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new 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(); } }
Can you help me rewrite this code in Java instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; namespace AssocArrays { class Program { static void Main(string[] args) { Dictionary<string,int> assocArray = new Dictionary<string,int>(); assocArray["Hello"] = 1; assocArray.Add("World", 2); assocArray["!"] = 3; foreach (KeyValuePair<string, int> kvp in assocArray) { Console.WriteLine(kvp.Key + " : " + kvp.Value); } foreach (string key in assocArray.Keys) { Console.WriteLine(key); } foreach (int val in assocArray.Values) { Console.WriteLine(val.ToString()); } } } }
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); }
Port the following code from C# to Java with equivalent syntax and logic.
using System; using System.Globalization; struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable { const int MIN_VALUE = 1; const int MAX_VALUE = 10; public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE); public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE); static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE; readonly int _value; public int Value => this._value == 0 ? MIN_VALUE : this._value; public LimitedInt(int value) { if (!IsValidValue(value)) throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}."); this._value = value; } #region IComparable public int CompareTo(object obj) { if (obj is LimitedInt l) return this.Value.CompareTo(l); throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj)); } #endregion #region IComparable<LimitedInt> public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value); #endregion #region IConvertible public TypeCode GetTypeCode() => this.Value.GetTypeCode(); bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider); byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider); char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider); DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider); decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider); double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider); short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider); int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider); long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider); sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider); float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider); string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider); object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider); ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider); uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider); ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider); #endregion #region IEquatable<LimitedInt> public bool Equals(LimitedInt other) => this == other; #endregion #region IFormattable public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider); #endregion #region operators public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value; public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value; public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value; public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value; public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value; public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value; public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1); public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1); public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value); public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value); public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value); public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value); public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value); public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value); public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value); public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value); public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value; public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right); public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right); public static implicit operator int(LimitedInt value) => value.Value; public static explicit operator LimitedInt(int value) { if (!IsValidValue(value)) throw new OverflowException(); return new LimitedInt(value); } #endregion public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) => this.Value.TryFormat(destination, out charsWritten, format, provider); public override int GetHashCode() => this.Value.GetHashCode(); public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l); public override string ToString() => this.Value.ToString(); #region static methods public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider); public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s) => int.Parse(s); public static int Parse(string s, NumberStyles style) => int.Parse(s, style); public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider); public static bool TryParse(string s, ref int result) => int.TryParse(s, out result); #endregion }
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()); } } }
Port the provided C# code into Java while preserving the original functionality.
using System; using System.Globalization; struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable { const int MIN_VALUE = 1; const int MAX_VALUE = 10; public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE); public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE); static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE; readonly int _value; public int Value => this._value == 0 ? MIN_VALUE : this._value; public LimitedInt(int value) { if (!IsValidValue(value)) throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}."); this._value = value; } #region IComparable public int CompareTo(object obj) { if (obj is LimitedInt l) return this.Value.CompareTo(l); throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj)); } #endregion #region IComparable<LimitedInt> public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value); #endregion #region IConvertible public TypeCode GetTypeCode() => this.Value.GetTypeCode(); bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider); byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider); char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider); DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider); decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider); double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider); short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider); int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider); long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider); sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider); float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider); string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider); object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider); ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider); uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider); ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider); #endregion #region IEquatable<LimitedInt> public bool Equals(LimitedInt other) => this == other; #endregion #region IFormattable public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider); #endregion #region operators public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value; public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value; public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value; public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value; public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value; public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value; public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1); public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1); public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value); public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value); public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value); public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value); public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value); public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value); public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value); public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value); public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value; public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right); public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right); public static implicit operator int(LimitedInt value) => value.Value; public static explicit operator LimitedInt(int value) { if (!IsValidValue(value)) throw new OverflowException(); return new LimitedInt(value); } #endregion public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) => this.Value.TryFormat(destination, out charsWritten, format, provider); public override int GetHashCode() => this.Value.GetHashCode(); public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l); public override string ToString() => this.Value.ToString(); #region static methods public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider); public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s) => int.Parse(s); public static int Parse(string s, NumberStyles style) => int.Parse(s, style); public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider); public static bool TryParse(string s, ref int result) => int.TryParse(s, out result); #endregion }
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()); } } }
Port the following code from C# to Java with equivalent syntax and logic.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
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(); } } }
Write the same algorithm in Java as shown in this C# implementation.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
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(); } } }
Produce a language-to-language conversion: from C# to Java, same semantics.
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; private set; } } public class NameNemesis { public NameNemesis(string name, string nemesis) { Name = name; Nemesis = nemesis; } public string Name { get; private set; } public string Nemesis { get; private set; } } public class DataContext { public DataContext() { AgeName = new List<AgeName>(); NameNemesis = new List<NameNemesis>(); } public List<AgeName> AgeName { get; set; } public List<NameNemesis> NameNemesis { get; set; } } public class AgeNameNemesis { public AgeNameNemesis(byte age, string name, string nemesis) { Age = age; Name = name; Nemesis = nemesis; } public byte Age { get; private set; } public string Name { get; private set; } public string Nemesis { get; private set; } } class Program { public static void Main() { var data = GetData(); var result = ExecuteHashJoin(data); WriteResultToConsole(result); } private static void WriteResultToConsole(List<AgeNameNemesis> result) { result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); } private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data) { return (data.AgeName.Join(data.NameNemesis, ageName => ageName.Name, nameNemesis => nameNemesis.Name, (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) .ToList(); } private static DataContext GetData() { var context = new DataContext(); context.AgeName.AddRange(new [] { new AgeName(27, "Jonah"), new AgeName(18, "Alan"), new AgeName(28, "Glory"), new AgeName(18, "Popeye"), new AgeName(28, "Alan") }); context.NameNemesis.AddRange(new[] { new NameNemesis("Jonah", "Whales"), new NameNemesis("Jonah", "Spiders"), new NameNemesis("Alan", "Ghosts"), new NameNemesis("Alan", "Zombies"), new NameNemesis("Glory", "Buffy") }); return context; } } }
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; } }
Preserve the algorithm and functionality while converting the code from C# to Java.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
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) }; } }
Transform the following C# implementation into Java, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
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 C# to Java, same semantics.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
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) }; } }
Port the following code from C# to Java with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; matrix r = new matrix(); void recurse(int last) { if (last == first) { for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; } } var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", 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; } } }
Preserve the algorithm and functionality while converting the code from C# to Java.
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; } public readonly PointF P1; public readonly PointF P2; public float Length() { return (float)Math.Sqrt(LengthSquared()); } public float LengthSquared() { return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y); } }
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"); } }
Translate this program into Java but keep the logic exactly as in C#.
class Animal { } class Dog : Animal { } class Lab : Dog { } class Collie : Dog { } class Cat : Animal { }
public class Animal{ }
Maintain the same structure and functionality when rewriting this code in Java.
System.Collections.HashTable map = new System.Collections.HashTable(); map["key1"] = "foo";
Map<String, Int> map = new HashMap(); map["foo"] = 5; map["bar"] = 10; map["baz"] = 15; map["foo"] = 6;
Write a version of this C# function in Java with identical behavior.
System.Collections.HashTable map = new System.Collections.HashTable(); map["key1"] = "foo";
Map<String, Int> map = new HashMap(); map["foo"] = 5; map["bar"] = 10; map["baz"] = 15; map["foo"] = 6;
Convert this C# snippet to Java and keep its semantics consistent.
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality); imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null); DrawHue(100); } void DrawHue(int saturation) { var bmp = (WriteableBitmap)imgMain.Source; int centerX = (int)bmp.Width / 2; int centerY = (int)bmp.Height / 2; int radius = Math.Min(centerX, centerY); int radius2 = radius - 40; bmp.Lock(); unsafe{ var buf = bmp.BackBuffer; IntPtr pixLineStart; for(int y=0; y < bmp.Height; y++){ pixLineStart = buf + bmp.BackBufferStride * y; double dy = (y - centerY); for(int x=0; x < bmp.Width; x++){ double dx = (x - centerX); double dist = Math.Sqrt(dx * dx + dy * dy); if (radius2 <= dist && dist <= radius) { double theta = Math.Atan2(dy, dx); double hue = (theta + Math.PI) / (2.0 * Math.PI); *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100); } } } } bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480)); bmp.Unlock(); } static int HSB_to_RGB(int h, int s, int v) { var rgb = new int[3]; var baseColor = (h + 60) % 360 / 120; var shift = (h + 60) % 360 - (120 * baseColor + 60 ); var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3; rgb[baseColor] = 255; rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f); for (var i = 0; i < 3; i++) rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f)); for (var i = 0; i < 3; i++) rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f); return RGB2int(rgb[0], rgb[1], rgb[2]); } public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
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)); } }