Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the provided Java code into C# while preserving the original functionality. | class StripChars {
public static String stripChars(String inString, String toStrip) {
return inString.replaceAll("[" + toStrip + "]", "");
}
public static void main(String[] args) {
String sentence = "She was a soul stripper. She took my heart!";
String chars = "aei";
System.out.println("sentence: " + sentence);
System.out.println("to strip: " + chars);
System.out.println("stripped: " + stripChars(sentence, chars));
}
}
| using System;
public static string RemoveCharactersFromString(string testString, string removeChars)
{
char[] charAry = removeChars.ToCharArray();
string returnString = testString;
foreach (char c in charAry)
{
while (returnString.IndexOf(c) > -1)
{
returnString = returnString.Remove(returnString.IndexOf(c), 1);
}
}
return returnString;
}
|
Translate this program into C# but keep the logic exactly as in Java. | public static double avg(double... arr) {
double sum = 0.0;
for (double x : arr) {
sum += x;
}
return sum / arr.length;
}
| using System;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine(new[] { 1, 2, 3 }.Average());
}
}
|
Change the following Java code into C# without altering its purpose. | import java.lang.Math;
import java.util.Map;
import java.util.HashMap;
public class REntropy {
@SuppressWarnings("boxing")
public static double getShannonEntropy(String s) {
int n = 0;
Map<Character, Integer> occ = new HashMap<>();
for (int c_ = 0; c_ < s.length(); ++c_) {
char cx = s.charAt(c_);
if (occ.containsKey(cx)) {
occ.put(cx, occ.get(cx) + 1);
} else {
occ.put(cx, 1);
}
++n;
}
double e = 0.0;
for (Map.Entry<Character, Integer> entry : occ.entrySet()) {
char cx = entry.getKey();
double p = (double) entry.getValue() / n;
e += p * log2(p);
}
return -e;
}
private static double log2(double a) {
return Math.log(a) / Math.log(2);
}
public static void main(String[] args) {
String[] sstr = {
"1223334444",
"1223334444555555555",
"122333",
"1227774444",
"aaBBcccDDDD",
"1234567890abcdefghijklmnopqrstuvwxyz",
"Rosetta Code",
};
for (String ss : sstr) {
double entropy = REntropy.getShannonEntropy(ss);
System.out.printf("Shannon entropy of %40s: %.12f%n", "\"" + ss + "\"", entropy);
}
return;
}
}
| using System;
using System.Collections.Generic;
namespace Entropy
{
class Program
{
public static double logtwo(double num)
{
return Math.Log(num)/Math.Log(2);
}
public static void Main(string[] args)
{
label1:
string input = Console.ReadLine();
double infoC=0;
Dictionary<char,double> table = new Dictionary<char, double>();
foreach (char c in input)
{
if (table.ContainsKey(c))
table[c]++;
else
table.Add(c,1);
}
double freq;
foreach (KeyValuePair<char,double> letter in table)
{
freq=letter.Value/input.Length;
infoC+=freq*logtwo(freq);
}
infoC*=-1;
Console.WriteLine("The Entropy of {0} is {1}",input,infoC);
goto label1;
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | import java.util.*;
public class TokenizeStringWithEscaping {
public static void main(String[] args) {
String sample = "one^|uno||three^^^^|four^^^|^cuatro|";
char separator = '|';
char escape = '^';
System.out.println(sample);
try {
System.out.println(tokenizeString(sample, separator, escape));
} catch (Exception e) {
System.out.println(e);
}
}
public static List<String> tokenizeString(String s, char sep, char escape)
throws Exception {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean inEscape = false;
for (char c : s.toCharArray()) {
if (inEscape) {
inEscape = false;
} else if (c == escape) {
inEscape = true;
continue;
} else if (c == sep) {
tokens.add(sb.toString());
sb.setLength(0);
continue;
}
sb.append(c);
}
if (inEscape)
throw new Exception("Invalid terminal escape");
tokens.add(sb.toString());
return tokens;
}
}
| using System;
using System.Text;
using System.Collections.Generic;
public class TokenizeAStringWithEscaping
{
public static void Main() {
string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
Console.WriteLine(": " + token);
}
}
}
public static class Extensions
{
public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
if (input == null) yield break;
var buffer = new StringBuilder();
bool escaping = false;
foreach (char c in input) {
if (escaping) {
buffer.Append(c);
escaping = false;
} else if (c == escape) {
escaping = true;
} else if (c == separator) {
yield return buffer.Flush();
} else {
buffer.Append(c);
}
}
if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
}
public static string Flush(this StringBuilder stringBuilder) {
string result = stringBuilder.ToString();
stringBuilder.Clear();
return result;
}
}
|
Change the programming language of this snippet from Java to C# without modifying what it does. | module HelloWorld
{
void run()
{
@Inject Console console;
console.print("Hello World!");
}
}
| Using System;
namespace HelloWorld {
class Program
{
static void Main()
{
Console.Writeln("Hello World!");
}
}
}
|
Write the same code in C# as shown below in Java. | import java.util.Arrays;
public class FD {
public static void main(String args[]) {
double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
System.out.println(Arrays.toString(dif(a, 1)));
System.out.println(Arrays.toString(dif(a, 2)));
System.out.println(Arrays.toString(dif(a, 9)));
System.out.println(Arrays.toString(dif(a, 10)));
System.out.println(Arrays.toString(dif(a, 11)));
System.out.println(Arrays.toString(dif(a, -1)));
System.out.println(Arrays.toString(dif(a, 0)));
}
public static double[] dif(double[] a, int n) {
if (n < 0)
return null;
for (int i = 0; i < n && a.length > 0; i++) {
double[] b = new double[a.length - 1];
for (int j = 0; j < b.length; j++){
b[j] = a[j+1] - a[j];
}
a = b;
}
return a;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)
{
switch (order)
{
case 0u:
return sequence;
case 1u:
return sequence.Skip(1).Zip(sequence, (next, current) => next - current);
default:
return ForwardDifference(ForwardDifference(sequence), order - 1u);
}
}
static void Main()
{
IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };
do
{
Console.WriteLine(string.Join(", ", sequence));
} while ((sequence = ForwardDifference(sequence)).Any());
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | public static boolean prime(long a){
if(a == 2){
return true;
}else if(a <= 1 || a % 2 == 0){
return false;
}
long max = (long)Math.sqrt(a);
for(long n= 3; n <= max; n+= 2){
if(a % n == 0){ return false; }
}
return true;
}
| static bool isPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
|
Preserve the algorithm and functionality while converting the code from Java to C#. | public class Binomial {
private static long binomialInt(int n, int k) {
if (k > n - k)
k = n - k;
long binom = 1;
for (int i = 1; i <= k; i++)
binom = binom * (n + 1 - i) / i;
return binom;
}
private static Object binomialIntReliable(int n, int k) {
if (k > n - k)
k = n - k;
long binom = 1;
for (int i = 1; i <= k; i++) {
try {
binom = Math.multiplyExact(binom, n + 1 - i) / i;
} catch (ArithmeticException e) {
return "overflow";
}
}
return binom;
}
private static double binomialFloat(int n, int k) {
if (k > n - k)
k = n - k;
double binom = 1.0;
for (int i = 1; i <= k; i++)
binom = binom * (n + 1 - i) / i;
return binom;
}
private static BigInteger binomialBigInt(int n, int k) {
if (k > n - k)
k = n - k;
BigInteger binom = BigInteger.ONE;
for (int i = 1; i <= k; i++) {
binom = binom.multiply(BigInteger.valueOf(n + 1 - i));
binom = binom.divide(BigInteger.valueOf(i));
}
return binom;
}
private static void demo(int n, int k) {
List<Object> data = Arrays.asList(
n,
k,
binomialInt(n, k),
binomialIntReliable(n, k),
binomialFloat(n, k),
binomialBigInt(n, k));
System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t")));
}
public static void main(String[] args) {
demo(5, 3);
demo(1000, 300);
}
}
| using System;
namespace BinomialCoefficients
{
class Program
{
static void Main(string[] args)
{
ulong n = 1000000, k = 3;
ulong result = biCoefficient(n, k);
Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result);
Console.ReadLine();
}
static int fact(int n)
{
if (n == 0) return 1;
else return n * fact(n - 1);
}
static ulong biCoefficient(ulong n, ulong k)
{
if (k > n - k)
{
k = n - k;
}
ulong c = 1;
for (uint i = 0; i < k; i++)
{
c = c * (n - i);
c = c / (i + 1);
}
return c;
}
}
}
|
Write a version of this Java function in C# with identical behavior. | List arrayList = new ArrayList();
arrayList.add(new Integer(0));
arrayList.add(0);
List<Integer> myarrlist = new ArrayList<Integer>();
int sum;
for(int i = 0; i < 10; i++) {
myarrlist.add(i);
}
|
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };
int[] intArray = new int[]{ 1, 2, 3, 4, 5 };
int[] intArray = { 1, 2, 3, 4, 5 };
string[] stringArr = new string[5];
stringArr[0] = "string";
|
Convert the following code from Java to C#, ensuring the logic remains intact. | LinkedList<Type> list = new LinkedList<Type>();
for(Type i: list){
System.out.println(i);
}
| var current = [head of list to traverse]
while(current != null)
{
current = current.Next;
}
|
Change the programming language of this snippet from Java to C# without modifying what it does. | import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class PPMWriter {
public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {
file.delete();
try (var os = new FileOutputStream(file, true);
var bw = new BufferedOutputStream(os)) {
var header = String.format("P6\n%d %d\n255\n",
bitmap.getWidth(), bitmap.getHeight());
bw.write(header.getBytes(StandardCharsets.US_ASCII));
for (var y = 0; y < bitmap.getHeight(); y++) {
for (var x = 0; x < bitmap.getWidth(); x++) {
var pixel = bitmap.getPixel(x, y);
bw.write(pixel.getRed());
bw.write(pixel.getGreen());
bw.write(pixel.getBlue());
}
}
}
}
}
| using System;
using System.IO;
class PPMWriter
{
public static void WriteBitmapToPPM(string file, Bitmap bitmap)
{
var writer = new StreamWriter(file);
writer.WriteLine("P6");
writer.WriteLine($"{bitmap.Width} {bitmap.Height}");
writer.WriteLine("255");
writer.Close();
var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));
for (int x = 0; x < bitmap.Height; x++)
for (int y = 0; y < bitmap.Width; y++)
{
Color color = bitmap.GetPixel(y, x);
writerB.Write(color.R);
writerB.Write(color.G);
writerB.Write(color.B);
}
writerB.Close();
}
}
|
Generate an equivalent C# version of this Java code. | import java.io.File;
public class FileDeleteTest {
public static boolean deleteFile(String filename) {
boolean exists = new File(filename).delete();
return exists;
}
public static void test(String type, String filename) {
System.out.println("The following " + type + " called " + filename +
(deleteFile(filename) ? " was deleted." : " could not be deleted.")
);
}
public static void main(String args[]) {
test("file", "input.txt");
test("file", File.seperator + "input.txt");
test("directory", "docs");
test("directory", File.seperator + "docs" + File.seperator);
}
}
| using System;
using System.IO;
namespace DeleteFile {
class Program {
static void Main() {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete("/input.txt");
Directory.Delete("/docs");
}
}
}
|
Convert the following code from Java to C#, ensuring the logic remains intact. | import java.io.File;
public class FileDeleteTest {
public static boolean deleteFile(String filename) {
boolean exists = new File(filename).delete();
return exists;
}
public static void test(String type, String filename) {
System.out.println("The following " + type + " called " + filename +
(deleteFile(filename) ? " was deleted." : " could not be deleted.")
);
}
public static void main(String args[]) {
test("file", "input.txt");
test("file", File.seperator + "input.txt");
test("directory", "docs");
test("directory", File.seperator + "docs" + File.seperator);
}
}
| using System;
using System.IO;
namespace DeleteFile {
class Program {
static void Main() {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete("/input.txt");
Directory.Delete("/docs");
}
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | import java.util.Calendar;
import java.util.GregorianCalendar;
public class DiscordianDate {
final static String[] seasons = {"Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"};
final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"};
final static String[] apostle = {"Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"};
final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"};
public static String discordianDate(final GregorianCalendar date) {
int y = date.get(Calendar.YEAR);
int yold = y + 1166;
int dayOfYear = date.get(Calendar.DAY_OF_YEAR);
if (date.isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold;
else if (dayOfYear > 60)
dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
if (seasonDay == 5)
return apostle[dayOfYear / 73] + ", in the YOLD " + yold;
if (seasonDay == 50)
return holiday[dayOfYear / 73] + ", in the YOLD " + yold;
String season = seasons[dayOfYear / 73];
String dayOfWeek = weekday[dayOfYear % 5];
return String.format("%s, day %s of %s in the YOLD %s",
dayOfWeek, seasonDay, season, yold);
}
public static void main(String[] args) {
System.out.println(discordianDate(new GregorianCalendar()));
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176");
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178");
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178");
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178");
test(2010, 0, 5, "Mungday, in the YOLD 3176");
test(2011, 4, 3, "Discoflux, in the YOLD 3177");
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181");
}
private static void test(int y, int m, int d, final String result) {
assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));
}
}
| using System;
public static class DiscordianDate
{
static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" };
static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" };
static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" };
static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" };
public static string Discordian(this DateTime date) {
string yold = $" in the YOLD {date.Year + 1166}.";
int dayOfYear = date.DayOfYear;
if (DateTime.IsLeapYear(date.Year)) {
if (dayOfYear == 60) return "St. Tib's day" + yold;
else if (dayOfYear > 60) dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
int seasonNr = dayOfYear / 73;
int weekdayNr = dayOfYear % 5;
string holyday = "";
if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!";
else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!";
return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}";
}
public static void Main() {
foreach (var (day, month, year) in new [] {
(1, 1, 2010),
(5, 1, 2010),
(19, 2, 2011),
(28, 2, 2012),
(29, 2, 2012),
(1, 3, 2012),
(19, 3, 2013),
(3, 5, 2014),
(31, 5, 2015),
(22, 6, 2016),
(15, 7, 2016),
(12, 8, 2017),
(19, 9, 2018),
(26, 9, 2018),
(24, 10, 2019),
(8, 12, 2020),
(31, 12, 2020)
})
{
Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}");
}
}
}
|
Translate the given Java code snippet into C# without altering its behavior. | import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
}
| public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.Next(n);
}
var seen = new HashSet<double>(n);
int current = 0;
int length = 0;
while (seen.Add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void Main(string[] args) {
Console.WriteLine(" N average analytical (error)");
Console.WriteLine("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
var average = AverageLoopLength.average(i);
var analytical = AverageLoopLength.analytical(i);
Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
}
}
}
|
Produce a functionally identical C# code for the snippet given in Java. | import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
}
| public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.Next(n);
}
var seen = new HashSet<double>(n);
int current = 0;
int length = 0;
while (seen.Add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void Main(string[] args) {
Console.WriteLine(" N average analytical (error)");
Console.WriteLine("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
var average = AverageLoopLength.average(i);
var analytical = AverageLoopLength.analytical(i);
Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
}
}
}
|
Port the provided Java code into C# while preserving the original functionality. | String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little);
System.out.println(replaced);
System.out.printf("Mary had a %s lamb.", little);
String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);
| class Program
{
static void Main()
{
string extra = "little";
string formatted = $"Mary had a {extra} lamb.";
System.Console.WriteLine(formatted);
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | import java.math.BigInteger;
public class PartitionFunction {
public static void main(String[] args) {
long start = System.currentTimeMillis();
BigInteger result = partitions(6666);
long end = System.currentTimeMillis();
System.out.println("P(6666) = " + result);
System.out.printf("elapsed time: %d milliseconds\n", end - start);
}
private static BigInteger partitions(int n) {
BigInteger[] p = new BigInteger[n + 1];
p[0] = BigInteger.ONE;
for (int i = 1; i <= n; ++i) {
p[i] = BigInteger.ZERO;
for (int k = 1; ; ++k) {
int j = (k * (3 * k - 1))/2;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
j += k;
if (j > i)
break;
if ((k & 1) != 0)
p[i] = p[i].add(p[i - j]);
else
p[i] = p[i].subtract(p[i - j]);
}
}
return p[n];
}
}
| using System;
class Program {
const long Lm = (long)1e18;
const string Fm = "D18";
struct LI { public long lo, ml, mh, hi, tp; }
static void inc(ref LI d, LI s) {
if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
d.tp += s.tp;
}
static void dec(ref LI d, LI s) {
if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
d.tp -= s.tp;
}
static LI set(long s) { LI d;
d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }
static string fmt(LI x) {
if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
return x.lo.ToString();
}
static LI partcount(int n) {
var P = new LI[n + 1]; P[0] = set(1);
for (int i = 1; i <= n; i++) {
int k = 0, d = -2, j = i;
LI x = set(0);
while (true) {
if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
if ((j -= ++k) >= 0) inc(ref x, P[j]); else break;
if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
if ((j -= ++k) >= 0) dec(ref x, P[j]); else break;
}
P[i] = x;
}
return P[n];
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew ();
var res = partcount(6666); sw.Stop();
Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
}
}
|
Translate this program into C# but keep the logic exactly as in Java. | public class PrimeDigits {
private static boolean primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
public static void main(String[] args) {
int c = 0;
for (int i = 1; i < 1_000_000; i++) {
if (primeDigitsSum13(i)) {
System.out.printf("%6d ", i);
if (c++ == 10) {
c = 0;
System.out.println();
}
}
}
System.out.println();
}
}
| using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
|
Convert this Java block to C#, preserving its control flow and logic. | public class PrimeDigits {
private static boolean primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
public static void main(String[] args) {
int c = 0;
for (int i = 1; i < 1_000_000; i++) {
if (primeDigitsSum13(i)) {
System.out.printf("%6d ", i);
if (c++ == 10) {
c = 0;
System.out.println();
}
}
}
System.out.println();
}
}
| using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
|
Write the same code in C# as shown below in Java. | import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.close();
}
}
}
| using System;
using System.IO;
using System.Text;
namespace RosettaCode
{
internal class Program
{
private const string FileName = "NOTES.TXT";
private static void Main(string[] args)
{
if (args.Length==0)
{
string txt = File.ReadAllText(FileName);
Console.WriteLine(txt);
}
else
{
var sb = new StringBuilder();
sb.Append(DateTime.Now).Append("\n\t");
foreach (string s in args)
sb.Append(s).Append(" ");
sb.Append("\n");
if (File.Exists(FileName))
File.AppendAllText(FileName, sb.ToString());
else
File.WriteAllText(FileName, sb.ToString());
}
}
}
}
|
Translate the given Java code snippet into C# without altering its behavior. | import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.close();
}
}
}
| using System;
using System.IO;
using System.Text;
namespace RosettaCode
{
internal class Program
{
private const string FileName = "NOTES.TXT";
private static void Main(string[] args)
{
if (args.Length==0)
{
string txt = File.ReadAllText(FileName);
Console.WriteLine(txt);
}
else
{
var sb = new StringBuilder();
sb.Append(DateTime.Now).Append("\n\t");
foreach (string s in args)
sb.Append(s).Append(" ");
sb.Append("\n");
if (File.Exists(FileName))
File.AppendAllText(FileName, sb.ToString());
else
File.WriteAllText(FileName, sb.ToString());
}
}
}
}
|
Produce a language-to-language conversion: from Java to C#, same semantics. | import java.text.DecimalFormat;
public class AnglesNormalizationAndConversion {
public static void main(String[] args) {
DecimalFormat formatAngle = new DecimalFormat("######0.000000");
DecimalFormat formatConv = new DecimalFormat("###0.0000");
System.out.printf(" degrees gradiens mils radians%n");
for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {
for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) {
double d = 0, g = 0, m = 0, r = 0;
switch (units) {
case "degrees":
d = d2d(angle);
g = d2g(d);
m = d2m(d);
r = d2r(d);
break;
case "gradiens":
g = g2g(angle);
d = g2d(g);
m = g2m(g);
r = g2r(g);
break;
case "mils":
m = m2m(angle);
d = m2d(m);
g = m2g(m);
r = m2r(m);
break;
case "radians":
r = r2r(angle);
d = r2d(r);
g = r2g(r);
m = r2m(r);
break;
}
System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));
}
}
}
private static final double DEGREE = 360D;
private static final double GRADIAN = 400D;
private static final double MIL = 6400D;
private static final double RADIAN = (2 * Math.PI);
private static double d2d(double a) {
return a % DEGREE;
}
private static double d2g(double a) {
return a * (GRADIAN / DEGREE);
}
private static double d2m(double a) {
return a * (MIL / DEGREE);
}
private static double d2r(double a) {
return a * (RADIAN / 360);
}
private static double g2d(double a) {
return a * (DEGREE / GRADIAN);
}
private static double g2g(double a) {
return a % GRADIAN;
}
private static double g2m(double a) {
return a * (MIL / GRADIAN);
}
private static double g2r(double a) {
return a * (RADIAN / GRADIAN);
}
private static double m2d(double a) {
return a * (DEGREE / MIL);
}
private static double m2g(double a) {
return a * (GRADIAN / MIL);
}
private static double m2m(double a) {
return a % MIL;
}
private static double m2r(double a) {
return a * (RADIAN / MIL);
}
private static double r2d(double a) {
return a * (DEGREE / RADIAN);
}
private static double r2g(double a) {
return a * (GRADIAN / RADIAN);
}
private static double r2m(double a) {
return a * (MIL / RADIAN);
}
private static double r2r(double a) {
return a % RADIAN;
}
}
| using System;
public static class Angles
{
public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);
public static void Print(params double[] angles) {
string[] names = { "Degrees", "Gradians", "Mils", "Radians" };
Func<double, double> rnd = a => Math.Round(a, 4);
Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };
Func<double, double>[,] convert = {
{ a => a, DegToGrad, DegToMil, DegToRad },
{ GradToDeg, a => a, GradToMil, GradToRad },
{ MilToDeg, MilToGrad, a => a, MilToRad },
{ RadToDeg, RadToGrad, RadToMil, a => a }
};
Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{
"Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}");
foreach (double angle in angles) {
for (int i = 0; i < 4; i++) {
double nAngle = normal[i](angle);
Console.WriteLine($@"{
rnd(angle),-12}{
rnd(nAngle),-12}{
names[i],-12}{
rnd(convert[i, 0](nAngle)),-12}{
rnd(convert[i, 1](nAngle)),-12}{
rnd(convert[i, 2](nAngle)),-12}{
rnd(convert[i, 3](nAngle)),-12}");
}
}
}
public static double NormalizeDeg(double angle) => Normalize(angle, 360);
public static double NormalizeGrad(double angle) => Normalize(angle, 400);
public static double NormalizeMil(double angle) => Normalize(angle, 6400);
public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);
private static double Normalize(double angle, double N) {
while (angle <= -N) angle += N;
while (angle >= N) angle -= N;
return angle;
}
public static double DegToGrad(double angle) => angle * 10 / 9;
public static double DegToMil(double angle) => angle * 160 / 9;
public static double DegToRad(double angle) => angle * Math.PI / 180;
public static double GradToDeg(double angle) => angle * 9 / 10;
public static double GradToMil(double angle) => angle * 16;
public static double GradToRad(double angle) => angle * Math.PI / 200;
public static double MilToDeg(double angle) => angle * 9 / 160;
public static double MilToGrad(double angle) => angle / 16;
public static double MilToRad(double angle) => angle * Math.PI / 3200;
public static double RadToDeg(double angle) => angle * 180 / Math.PI;
public static double RadToGrad(double angle) => angle * 200 / Math.PI;
public static double RadToMil(double angle) => angle * 3200 / Math.PI;
}
|
Rewrite the snippet below in C# so it works the same as the original Java code. | public class CommonPath {
public static String commonPath(String... paths){
String commonPath = "";
String[][] folders = new String[paths.length][];
for(int i = 0; i < paths.length; i++){
folders[i] = paths[i].split("/");
}
for(int j = 0; j < folders[0].length; j++){
String thisFolder = folders[0][j];
boolean allMatched = true;
for(int i = 1; i < folders.length && allMatched; i++){
if(folders[i].length < j){
allMatched = false;
break;
}
allMatched &= folders[i][j].equals(thisFolder);
}
if(allMatched){
commonPath += thisFolder + "/";
}else{
break;
}
}
return commonPath;
}
public static void main(String[] args){
String[] paths = { "/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths));
String[] paths2 = { "/hame/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"};
System.out.println(commonPath(paths2));
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks
{
class Program
{
static void Main ( string[ ] args )
{
FindCommonDirectoryPath.Test ( );
}
}
class FindCommonDirectoryPath
{
public static void Test ( )
{
Console.WriteLine ( "Find Common Directory Path" );
Console.WriteLine ( );
List<string> PathSet1 = new List<string> ( );
PathSet1.Add ( "/home/user1/tmp/coverage/test" );
PathSet1.Add ( "/home/user1/tmp/covert/operator" );
PathSet1.Add ( "/home/user1/tmp/coven/members" );
Console.WriteLine("Path Set 1 (All Absolute Paths):");
foreach ( string path in PathSet1 )
{
Console.WriteLine ( path );
}
Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) );
}
public static string FindCommonPath ( string Separator, List<string> Paths )
{
string CommonPath = String.Empty;
List<string> SeparatedPath = Paths
.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )
.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )
.ToList ( );
foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )
{
if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )
{
CommonPath = PathSegment;
}
else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )
{
CommonPath += Separator + PathSegment;
}
else
{
break;
}
}
return CommonPath;
}
}
}
|
Generate an equivalent C# version of this Java code. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Write a version of this Java function in C# with identical behavior. | import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecamanSequence {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
a.add(0);
Set<Integer> used = new HashSet<>();
used.add(0);
Set<Integer> used1000 = new HashSet<>();
used1000.add(0);
boolean foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a.get(n - 1) - n;
if (next < 1 || used.contains(next)) {
next += 2 * n;
}
boolean alreadyUsed = used.contains(next);
a.add(next);
if (!alreadyUsed) {
used.add(next);
if (0 <= next && next <= 1000) {
used1000.add(next);
}
}
if (n == 14) {
System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
}
if (!foundDup && alreadyUsed) {
System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
foundDup = true;
}
if (used1000.size() == 1001) {
System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
n++;
}
}
}
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Produce a functionally identical C# code for the snippet given in Java. |
Object foo = new Object();
int[] fooArray = new int[size];
int x = 0;
| using System;
using System.Runtime.InteropServices;
public unsafe class Program
{
public static unsafe void HeapMemory()
{
const int HEAP_ZERO_MEMORY = 0x00000008;
const int size = 1000;
int ph = GetProcessHeap();
void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
if (pointer == null)
throw new OutOfMemoryException();
Console.WriteLine(HeapSize(ph, 0, pointer));
HeapFree(ph, 0, pointer);
}
public static unsafe void StackMemory()
{
byte* buffer = stackalloc byte[1000];
}
public static void Main(string[] args)
{
HeapMemory();
StackMemory();
}
[DllImport("kernel32")]
static extern void* HeapAlloc(int hHeap, int flags, int size);
[DllImport("kernel32")]
static extern bool HeapFree(int hHeap, int flags, void* block);
[DllImport("kernel32")]
static extern int GetProcessHeap();
[DllImport("kernel32")]
static extern int HeapSize(int hHeap, int flags, void* block);
}
|
Write a version of this Java function in C# with identical behavior. | public class Count{
public static void main(String[] args){
for(long i = 1; ;i++) System.out.println(i);
}
}
| using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
|
Generate an equivalent C# version of this Java code. | public class Count{
public static void main(String[] args){
for(long i = 1; ;i++) System.out.println(i);
}
}
| using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original Java code. | import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
class DnsQuery {
public static void main(String[] args) {
try {
InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net");
for(int i=0; i < ipAddr.length ; i++) {
if (ipAddr[i] instanceof Inet4Address) {
System.out.println("IPv4 : " + ipAddr[i].getHostAddress());
} else if (ipAddr[i] instanceof Inet6Address) {
System.out.println("IPv6 : " + ipAddr[i].getHostAddress());
}
}
} catch (UnknownHostException uhe) {
System.err.println("unknown host");
}
}
}
| private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result += ", " + ip.AddressList[i].ToString();
return result;
}
catch (System.Net.Sockets.SocketException se)
{
return se.Message;
}
}
|
Write the same algorithm in C# as shown in this Java implementation. | import java.util.Random;
public class SevenSidedDice
{
private static final Random rnd = new Random();
public static void main(String[] args)
{
SevenSidedDice now=new SevenSidedDice();
System.out.println("Random number from 1 to 7: "+now.seven());
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1+rnd.nextInt(5);
}
}
| using System;
public class SevenSidedDice
{
Random random = new Random();
static void Main(string[] args)
{
SevenSidedDice sevenDice = new SevenSidedDice();
Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
Console.Read();
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1 + random.Next(5);
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Java version. | import java.util.ArrayList;
import java.util.List;
public class MagnanimousNumbers {
public static void main(String[] args) {
runTask("Find and display the first 45 magnanimous numbers.", 1, 45);
runTask("241st through 250th magnanimous numbers.", 241, 250);
runTask("391st through 400th magnanimous numbers.", 391, 400);
}
private static void runTask(String message, int startN, int endN) {
int count = 0;
List<Integer> nums = new ArrayList<>();
for ( int n = 0 ; count < endN ; n++ ) {
if ( isMagnanimous(n) ) {
nums.add(n);
count++;
}
}
System.out.printf("%s%n", message);
System.out.printf("%s%n%n", nums.subList(startN-1, endN));
}
private static boolean isMagnanimous(long n) {
if ( n >= 0 && n <= 9 ) {
return true;
}
long q = 11;
for ( long div = 10 ; q >= 10 ; div *= 10 ) {
q = n / div;
long r = n % div;
if ( ! isPrime(q+r) ) {
return false;
}
}
return true;
}
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
public static final boolean isPrime(long testValue) {
if ( testValue == 2 ) return true;
if ( testValue % 2 == 0 ) return false;
if ( testValue <= MAX ) return isPrimeTrivial(testValue);
long d = testValue-1;
int s = 0;
while ( d % 2 == 0 ) {
s += 1;
d /= 2;
}
if ( testValue < 1373565L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 4759123141L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(7, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 10000000000000000L ) {
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
if ( ! aSrp(24251, s, d, testValue) ) {
return false;
}
return true;
}
if ( ! aSrp(37, s, d, testValue) ) {
return false;
}
if ( ! aSrp(47, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
if ( ! aSrp(73, s, d, testValue) ) {
return false;
}
if ( ! aSrp(83, s, d, testValue) ) {
return false;
}
return true;
}
private static final boolean aSrp(int a, int s, long d, long n) {
long modPow = modPow(a, d, n);
if ( modPow == 1 ) {
return true;
}
int twoExpR = 1;
for ( int r = 0 ; r < s ; r++ ) {
if ( modPow(modPow, twoExpR, n) == n-1 ) {
return true;
}
twoExpR *= 2;
}
return false;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long modPow(long base, long exponent, long modulus) {
long result = 1;
while ( exponent > 0 ) {
if ( exponent % 2 == 1 ) {
if ( result > SQRT || base > SQRT ) {
result = multiply(result, base, modulus);
}
else {
result = (result * base) % modulus;
}
}
exponent >>= 1;
if ( base > SQRT ) {
base = multiply(base, base, modulus);
}
else {
base = (base * base) % modulus;
}
}
return result;
}
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
}
| using System; using static System.Console;
class Program {
static bool[] np;
static void ms(long lmt) {
np = new bool[lmt]; np[0] = np[1] = true;
for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])
for (long k = n * n; k < lmt; k += n) np[k] = true; }
static bool is_Mag(long n) { long res, rem;
for (long p = 10; n >= p; p *= 10) {
res = Math.DivRem (n, p, out rem);
if (np[res + rem]) return false; } return true; }
static void Main(string[] args) { ms(100_009); string mn;
WriteLine("First 45{0}", mn = " magnanimous numbers:");
for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {
if (c++ < 45 || (c > 240 && c <= 250) || c > 390)
Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l);
if (c < 45 && c % 15 == 0) WriteLine();
if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn);
if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } }
}
|
Maintain the same structure and functionality when rewriting this code in C#. | import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func bitwise(a, b int16) {
fmt.Printf("a: %016b\n", uint16(a))
fmt.Printf("b: %016b\n", uint16(b))
fmt.Printf("and: %016b\n", uint16(a&b))
fmt.Printf("or: %016b\n", uint16(a|b))
fmt.Printf("xor: %016b\n", uint16(a^b))
fmt.Printf("not: %016b\n", uint16(^a))
if b < 0 {
fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).")
return
}
ua := uint16(a)
ub := uint32(b)
fmt.Printf("shl: %016b\n", uint16(ua<<ub))
fmt.Printf("shr: %016b\n", uint16(ua>>ub))
fmt.Printf("las: %016b\n", uint16(a<<ub))
fmt.Printf("ras: %016b\n", uint16(a>>ub))
fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub))))
fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))
}
func main() {
var a, b int16 = -460, 6
bitwise(a, b)
}
| module BitwiseOps
{
@Inject Console console;
void run()
{
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])
{
static String hex(Int64 n)
{
return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
}
console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
| {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
| {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
| {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
| NOT {hex(n1)} = {hex(~n1)}
| left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
| right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
| right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
| left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
| right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
| leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
| rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
| leading zero count of {hex(n1)} = {n1.leadingZeroCount}
| trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
| bit count (aka "population") of {hex(n1)} = {n1.bitCount}
| reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
| reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
|
);
}
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
)
const sep = 512
const depth = 14
var s = math.Sqrt2 / 2
var sin = []float64{0, s, 1, s, 0, -s, -1, -s}
var cos = []float64{1, s, 0, -s, -1, -s, 0, s}
var p = color.NRGBA{64, 192, 96, 255}
var b *image.NRGBA
func main() {
width := sep * 11 / 6
height := sep * 4 / 3
bounds := image.Rect(0, 0, width, height)
b = image.NewNRGBA(bounds)
draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)
dragon(14, 0, 1, sep, sep/2, sep*5/6)
f, err := os.Create("dragon.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, b); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
func dragon(n, a, t int, d, x, y float64) {
if n <= 1 {
x1 := int(x + .5)
y1 := int(y + .5)
x2 := int(x + d*cos[a] + .5)
y2 := int(y + d*sin[a] + .5)
xInc := 1
if x1 > x2 {
xInc = -1
}
yInc := 1
if y1 > y2 {
yInc = -1
}
for x, y := x1, y1; ; x, y = x+xInc, y+yInc {
b.Set(x, y, p)
if x == x2 {
break
}
}
return
}
d *= s
a1 := (a - t) & 7
a2 := (a + t) & 7
dragon(n-1, a1, 1, d, x, y)
dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])
}
| import java.awt.Color;
import java.awt.Graphics;
import java.util.*;
import javax.swing.JFrame;
public class DragonCurve extends JFrame {
private List<Integer> turns;
private double startingAngle, side;
public DragonCurve(int iter) {
super("Dragon Curve");
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
turns = getSequence(iter);
startingAngle = -iter * (Math.PI / 4);
side = 400 / Math.pow(2, iter / 2.);
}
public List<Integer> getSequence(int iterations) {
List<Integer> turnSequence = new ArrayList<Integer>();
for (int i = 0; i < iterations; i++) {
List<Integer> copy = new ArrayList<Integer>(turnSequence);
Collections.reverse(copy);
turnSequence.add(1);
for (Integer turn : copy) {
turnSequence.add(-turn);
}
}
return turnSequence;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
double angle = startingAngle;
int x1 = 230, y1 = 350;
int x2 = x1 + (int) (Math.cos(angle) * side);
int y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
for (Integer turn : turns) {
angle += turn * (Math.PI / 2);
x2 = x1 + (int) (Math.cos(angle) * side);
y2 = y1 + (int) (Math.sin(angle) * side);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}
}
public static void main(String[] args) {
new DragonCurve(14).setVisible(true);
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"bufio"
"fmt"
"log"
"os"
)
func init() {
log.SetFlags(log.Lshortfile)
}
func main() {
inputFile, err := os.Open("byline.go")
if err != nil {
log.Fatal("Error opening input file:", err)
}
defer inputFile.Close()
scanner := bufio.NewScanner(inputFile)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(scanner.Err())
}
}
| import java.io.BufferedReader;
import java.io.FileReader;
public class ReadFileByLines {
private static void processLine(int lineNo, String line) {
}
public static void main(String[] args) {
for (String filename : args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line;
int lineNo = 0;
while ((line = br.readLine()) != null) {
processLine(++lineNo, line);
}
}
catch (Exception x) {
x.printStackTrace();
}
finally {
if (fr != null) {
try {br.close();} catch (Exception ignoreMe) {}
try {fr.close();} catch (Exception ignoreMe) {}
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import "fmt"
type dlNode struct {
string
next, prev *dlNode
}
type dlList struct {
head, tail *dlNode
}
func (list *dlList) String() string {
if list.head == nil {
return fmt.Sprint(list.head)
}
r := "[" + list.head.string
for p := list.head.next; p != nil; p = p.next {
r += " " + p.string
}
return r + "]"
}
func (list *dlList) insertTail(node *dlNode) {
if list.tail == nil {
list.head = node
} else {
list.tail.next = node
}
node.next = nil
node.prev = list.tail
list.tail = node
}
func (list *dlList) insertAfter(existing, insert *dlNode) {
insert.prev = existing
insert.next = existing.next
existing.next.prev = insert
existing.next = insert
if existing == list.tail {
list.tail = insert
}
}
func main() {
dll := &dlList{}
fmt.Println(dll)
a := &dlNode{string: "A"}
dll.insertTail(a)
dll.insertTail(&dlNode{string: "B"})
fmt.Println(dll)
dll.insertAfter(a, &dlNode{string: "C"})
fmt.Println(dll)
}
| import java.util.LinkedList;
@SuppressWarnings("serial")
public class DoublyLinkedListInsertion<T> extends LinkedList<T> {
public static void main(String[] args) {
DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();
list.addFirst("Add First 1");
list.addFirst("Add First 2");
list.addFirst("Add First 3");
list.addFirst("Add First 4");
list.addFirst("Add First 5");
traverseList(list);
list.addAfter("Add First 3", "Add New");
traverseList(list);
}
public void addAfter(T after, T element) {
int index = indexOf(after);
if ( index >= 0 ) {
add(index + 1, element);
}
else {
addLast(element);
}
}
private static void traverseList(LinkedList<String> list) {
System.out.println("Traverse List:");
for ( int i = 0 ; i < list.size() ; i++ ) {
System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
}
System.out.println();
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"math/big"
)
var b = new(big.Int)
func isSPDSPrime(n uint64) bool {
nn := n
for nn > 0 {
r := nn % 10
if r != 2 && r != 3 && r != 5 && r != 7 {
return false
}
nn /= 10
}
b.SetUint64(n)
if b.ProbablyPrime(0) {
return true
}
return false
}
func listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {
count := countFrom
for n := startFrom; ; n += 2 {
if isSPDSPrime(n) {
count++
if !printOne {
fmt.Printf("%2d. %d\n", count, n)
}
if count == countTo {
if printOne {
fmt.Println(n)
}
return n
}
}
}
}
func main() {
fmt.Println("The first 25 terms of the Smarandache prime-digital sequence are:")
fmt.Println(" 1. 2")
n := listSPDSPrimes(3, 1, 25, false)
fmt.Println("\nHigher terms:")
indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}
for i := 1; i < len(indices); i++ {
fmt.Printf("%6d. ", indices[i])
n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)
}
}
| public class SmarandachePrimeDigitalSequence {
public static void main(String[] args) {
long s = getNextSmarandache(7);
System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
if ( isPrime(s) ) {
System.out.printf("%d ", s);
count++;
}
}
System.out.printf("%n%n");
for (int i = 2 ; i <=5 ; i++ ) {
long n = (long) Math.pow(10, i);
System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n));
}
}
private static final long getSmarandachePrime(long n) {
if ( n < 10 ) {
switch ((int) n) {
case 1: return 2;
case 2: return 3;
case 3: return 5;
case 4: return 7;
}
}
long s = getNextSmarandache(7);
long result = 0;
for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {
if ( isPrime(s) ) {
count++;
result = s;
}
}
return result;
}
private static final boolean isPrime(long test) {
if ( test % 2 == 0 ) return false;
for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
if ( test % i == 0 ) {
return false;
}
}
return true;
}
private static long getNextSmarandache(long n) {
if ( n % 10 == 3 ) {
return n+4;
}
long retVal = n-4;
int k = 0;
while ( n % 10 == 7 ) {
k++;
n /= 10;
}
long digit = n % 10;
long coeff = (digit == 2 ? 1 : 2);
retVal += coeff * Math.pow(10, k);
while ( k > 1 ) {
retVal -= 5 * Math.pow(10, k-1);
k--;
}
return retVal;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import "fmt"
func quickselect(list []int, k int) int {
for {
px := len(list) / 2
pv := list[px]
last := len(list) - 1
list[px], list[last] = list[last], list[px]
i := 0
for j := 0; j < last; j++ {
if list[j] < pv {
list[i], list[j] = list[j], list[i]
i++
}
}
if i == k {
return pv
}
if k < i {
list = list[:i]
} else {
list[i], list[last] = list[last], list[i]
list = list[i+1:]
k -= i + 1
}
}
}
func main() {
for i := 0; ; i++ {
v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
if i == len(v) {
return
}
fmt.Println(quickselect(v, i))
}
}
| import java.util.Random;
public class QuickSelect {
private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
E pivotVal = arr[pivot];
swap(arr, pivot, right);
int storeIndex = left;
for (int i = left; i < right; i++) {
if (arr[i].compareTo(pivotVal) < 0) {
swap(arr, i, storeIndex);
storeIndex++;
}
}
swap(arr, right, storeIndex);
return storeIndex;
}
private static <E extends Comparable<? super E>> E select(E[] arr, int n) {
int left = 0;
int right = arr.length - 1;
Random rand = new Random();
while (right >= left) {
int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
if (pivotIndex == n) {
return arr[pivotIndex];
} else if (pivotIndex < n) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return null;
}
private static void swap(Object[] arr, int i1, int i2) {
if (i1 != i2) {
Object temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
System.out.print(select(input, i));
if (i < 9) System.out.print(", ");
}
System.out.println();
}
}
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import (
"fmt"
"math/big"
"strconv"
)
func main () {
s := strconv.FormatInt(26, 16)
fmt.Println(s)
i, err := strconv.ParseInt("1a", 16, 64)
if err == nil {
fmt.Println(i)
}
b, ok := new(big.Int).SetString("1a", 16)
if ok {
fmt.Println(b)
}
}
| public static long backToTen(String num, int oldBase){
return Long.parseLong(num, oldBase);
}
public static String tenToBase(long num, int newBase){
return Long.toString(num, newBase);
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import (
"fmt"
"unicode"
)
var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"}
func main() {
play(states)
play(append(states,
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"))
}
func play(states []string) {
fmt.Println(len(states), "states:")
set := make(map[string]bool, len(states))
for _, s := range states {
set[s] = true
}
s := make([]string, len(set))
h := make([][26]byte, len(set))
var i int
for us := range set {
s[i] = us
for _, c := range us {
if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {
h[i][u]++
}
}
i++
}
type pair struct {
i1, i2 int
}
m := make(map[string][]pair)
b := make([]byte, 26)
for i1, h1 := range h {
for i2 := i1 + 1; i2 < len(h); i2++ {
for i := range b {
b[i] = h1[i] + h[i2][i]
}
k := string(b)
for _, x := range m[k] {
if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {
fmt.Printf("%s, %s = %s, %s\n", s[i1], s[i2],
s[x.i1], s[x.i2])
}
}
m[k] = append(m[k], pair{i1, i2})
}
}
}
| import java.util.*;
import java.util.stream.*;
public class StateNamePuzzle {
static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "Florida",
"Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
"Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
"New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma",
"Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming",
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory",};
public static void main(String[] args) {
solve(Arrays.asList(states));
}
static void solve(List<String> input) {
Map<String, String> orig = input.stream().collect(Collectors.toMap(
s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s));
input = new ArrayList<>(orig.keySet());
Map<String, List<String[]>> map = new HashMap<>();
for (int i = 0; i < input.size() - 1; i++) {
String pair0 = input.get(i);
for (int j = i + 1; j < input.size(); j++) {
String[] pair = {pair0, input.get(j)};
String s = pair0 + pair[1];
String key = Arrays.toString(s.chars().sorted().toArray());
List<String[]> val = map.getOrDefault(key, new ArrayList<>());
val.add(pair);
map.put(key, val);
}
}
map.forEach((key, list) -> {
for (int i = 0; i < list.size() - 1; i++) {
String[] a = list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String[] b = list.get(j);
if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)
continue;
System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]),
orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));
}
}
});
}
}
|
Transform the following Go implementation into Java, maintaining the same output and logic. | package main
import (
"fmt"
"hash/crc32"
)
func main() {
s := []byte("The quick brown fox jumps over the lazy dog")
result := crc32.ChecksumIEEE(s)
fmt.Printf("%X\n", result)
}
| import java.util.zip.* ;
public class CRCMaker {
public static void main( String[ ] args ) {
String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ;
CRC32 myCRC = new CRC32( ) ;
myCRC.update( toBeEncoded.getBytes( ) ) ;
System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ;
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import (
"bytes"
"encoding/csv"
"fmt"
"html/template"
"strings"
)
var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`
func main() {
if h, err := csvToHtml(c); err != nil {
fmt.Println(err)
} else {
fmt.Print(h)
}
}
func csvToHtml(c string) (string, error) {
data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
if err != nil {
return "", err
}
var b strings.Builder
err = template.Must(template.New("").Parse(`<table>
{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
return b.String(), err
}
|
grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row : field ',' field '\r'? '\n';
field : Field{System.out.println("<TD>" + $Field.text.replace("<","<").replace(">",">") + "</TD>");};
Field : ~[,\n\r]+;
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"bytes"
"encoding/csv"
"fmt"
"html/template"
"strings"
)
var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`
func main() {
if h, err := csvToHtml(c); err != nil {
fmt.Println(err)
} else {
fmt.Print(h)
}
}
func csvToHtml(c string) (string, error) {
data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
if err != nil {
return "", err
}
var b strings.Builder
err = template.Must(template.New("").Parse(`<table>
{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
return b.String(), err
}
|
grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row : field ',' field '\r'? '\n';
field : Field{System.out.println("<TD>" + $Field.text.replace("<","<").replace(">",">") + "</TD>");};
Field : ~[,\n\r]+;
|
Change the programming language of this snippet from Go to Java without modifying what it does. | package main
import "fmt"
type picnicBasket struct {
nServings int
corkscrew bool
}
func (b *picnicBasket) happy() bool {
return b.nServings > 1 && b.corkscrew
}
func newPicnicBasket(nPeople int) *picnicBasket {
return &picnicBasket{nPeople, nPeople > 0}
}
func main() {
var pb picnicBasket
pbl := picnicBasket{}
pbp := &picnicBasket{}
pbn := new(picnicBasket)
forTwo := newPicnicBasket(2)
forToo := &picnicBasket{nServings: 2, corkscrew: true}
fmt.Println(pb.nServings, pb.corkscrew)
fmt.Println(pbl.nServings, pbl.corkscrew)
fmt.Println(pbp)
fmt.Println(pbn)
fmt.Println(forTwo)
fmt.Println(forToo)
}
| public class MyClass{
private int variable;
public MyClass(){
}
public void someMethod(){
this.variable = 1;
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"strconv"
)
func kaprekar(n uint64, base uint64) (bool, int) {
order := 0
if n == 1 {
return true, -1
}
nn, power := n*n, uint64(1)
for power <= nn {
power *= base
order++
}
power /= base
order--
for ; power > 1; power /= base {
q, r := nn/power, nn%power
if q >= n {
return false, -1
}
if q+r == n {
return true, order
}
order--
}
return false, -1
}
func main() {
max := uint64(10000)
fmt.Printf("Kaprekar numbers < %d:\n", max)
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
fmt.Println(" ", m)
}
}
max = 1e6
var count int
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
count++
}
}
fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max)
const base = 17
maxB := "1000000"
fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base)
max, _ = strconv.ParseUint(maxB, base, 64)
fmt.Printf("\n Base 10 Base %d Square Split\n", base)
for m := uint64(2); m < max; m++ {
is, pos := kaprekar(m, base)
if !is {
continue
}
sq := strconv.FormatUint(m*m, base)
str := strconv.FormatUint(m, base)
split := len(sq)-pos
fmt.Printf("%8d %7s %12s %6s + %s\n", m,
str, sq, sq[:split], sq[split:])
}
}
| public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
ans[0] = str.substring(0, idx);
if(ans[0].equals("")) ans[0] = "0";
ans[1] = str.substring(idx);
return ans;
}
public static void main(String[] args){
int count = 0;
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
for(long i = 1; i <= 1000000; i++){
String sqrStr = Long.toString(i * i, base);
for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
String[] parts = splitAt(sqrStr, j);
long firstNum = Long.parseLong(parts[0], base);
long secNum = Long.parseLong(parts[1], base);
if(secNum == 0) break;
if(firstNum + secNum == i){
System.out.println(i + "\t" + Long.toString(i, base) +
"\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
count++;
break;
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"fmt"
"strconv"
)
func kaprekar(n uint64, base uint64) (bool, int) {
order := 0
if n == 1 {
return true, -1
}
nn, power := n*n, uint64(1)
for power <= nn {
power *= base
order++
}
power /= base
order--
for ; power > 1; power /= base {
q, r := nn/power, nn%power
if q >= n {
return false, -1
}
if q+r == n {
return true, order
}
order--
}
return false, -1
}
func main() {
max := uint64(10000)
fmt.Printf("Kaprekar numbers < %d:\n", max)
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
fmt.Println(" ", m)
}
}
max = 1e6
var count int
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
count++
}
}
fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max)
const base = 17
maxB := "1000000"
fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base)
max, _ = strconv.ParseUint(maxB, base, 64)
fmt.Printf("\n Base 10 Base %d Square Split\n", base)
for m := uint64(2); m < max; m++ {
is, pos := kaprekar(m, base)
if !is {
continue
}
sq := strconv.FormatUint(m*m, base)
str := strconv.FormatUint(m, base)
split := len(sq)-pos
fmt.Printf("%8d %7s %12s %6s + %s\n", m,
str, sq, sq[:split], sq[split:])
}
}
| public class Kaprekar {
private static String[] splitAt(String str, int idx){
String[] ans = new String[2];
ans[0] = str.substring(0, idx);
if(ans[0].equals("")) ans[0] = "0";
ans[1] = str.substring(idx);
return ans;
}
public static void main(String[] args){
int count = 0;
int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
for(long i = 1; i <= 1000000; i++){
String sqrStr = Long.toString(i * i, base);
for(int j = 0; j < sqrStr.length() / 2 + 1; j++){
String[] parts = splitAt(sqrStr, j);
long firstNum = Long.parseLong(parts[0], base);
long secNum = Long.parseLong(parts[1], base);
if(secNum == 0) break;
if(firstNum + secNum == i){
System.out.println(i + "\t" + Long.toString(i, base) +
"\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]);
count++;
break;
}
}
}
System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base);
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"fmt"
"log"
"strings"
)
func compress(uncompressed string) []int {
dictSize := 256
dictionary := make(map[string]int, dictSize)
for i := 0; i < dictSize; i++ {
dictionary[string([]byte{byte(i)})] = i
}
var result []int
var w []byte
for i := 0; i < len(uncompressed); i++ {
c := uncompressed[i]
wc := append(w, c)
if _, ok := dictionary[string(wc)]; ok {
w = wc
} else {
result = append(result, dictionary[string(w)])
dictionary[string(wc)] = dictSize
dictSize++
wc[0] = c
w = wc[:1]
}
}
if len(w) > 0 {
result = append(result, dictionary[string(w)])
}
return result
}
type BadSymbolError int
func (e BadSymbolError) Error() string {
return fmt.Sprint("Bad compressed symbol ", int(e))
}
func decompress(compressed []int) (string, error) {
dictSize := 256
dictionary := make(map[int][]byte, dictSize)
for i := 0; i < dictSize; i++ {
dictionary[i] = []byte{byte(i)}
}
var result strings.Builder
var w []byte
for _, k := range compressed {
var entry []byte
if x, ok := dictionary[k]; ok {
entry = x[:len(x):len(x)]
} else if k == dictSize && len(w) > 0 {
entry = append(w, w[0])
} else {
return result.String(), BadSymbolError(k)
}
result.Write(entry)
if len(w) > 0 {
w = append(w, entry[0])
dictionary[dictSize] = w
dictSize++
}
w = entry
}
return result.String(), nil
}
func main() {
compressed := compress("TOBEORNOTTOBEORTOBEORNOT")
fmt.Println(compressed)
decompressed, err := decompress(compressed)
if err != nil {
log.Fatal(err)
}
fmt.Println(decompressed)
}
| import java.util.*;
public class LZW {
public static List<Integer> compress(String uncompressed) {
int dictSize = 256;
Map<String,Integer> dictionary = new HashMap<String,Integer>();
for (int i = 0; i < 256; i++)
dictionary.put("" + (char)i, i);
String w = "";
List<Integer> result = new ArrayList<Integer>();
for (char c : uncompressed.toCharArray()) {
String wc = w + c;
if (dictionary.containsKey(wc))
w = wc;
else {
result.add(dictionary.get(w));
dictionary.put(wc, dictSize++);
w = "" + c;
}
}
if (!w.equals(""))
result.add(dictionary.get(w));
return result;
}
public static String decompress(List<Integer> compressed) {
int dictSize = 256;
Map<Integer,String> dictionary = new HashMap<Integer,String>();
for (int i = 0; i < 256; i++)
dictionary.put(i, "" + (char)i);
String w = "" + (char)(int)compressed.remove(0);
StringBuffer result = new StringBuffer(w);
for (int k : compressed) {
String entry;
if (dictionary.containsKey(k))
entry = dictionary.get(k);
else if (k == dictSize)
entry = w + w.charAt(0);
else
throw new IllegalArgumentException("Bad compressed k: " + k);
result.append(entry);
dictionary.put(dictSize++, w + entry.charAt(0));
w = entry;
}
return result.toString();
}
public static void main(String[] args) {
List<Integer> compressed = compress("TOBEORNOTTOBEORTOBEORNOT");
System.out.println(compressed);
String decompressed = decompress(compressed);
System.out.println(decompressed);
}
}
|
Generate an equivalent Java version of this Go code. | package main
import "fmt"
var ffr, ffs func(int) int
func init() {
r := []int{0, 1}
s := []int{0, 2}
ffr = func(n int) int {
for len(r) <= n {
nrk := len(r) - 1
rNxt := r[nrk] + s[nrk]
r = append(r, rNxt)
for sn := r[nrk] + 2; sn < rNxt; sn++ {
s = append(s, sn)
}
s = append(s, rNxt+1)
}
return r[n]
}
ffs = func(n int) int {
for len(s) <= n {
ffr(len(r))
}
return s[n]
}
}
func main() {
for n := 1; n <= 10; n++ {
fmt.Printf("r(%d): %d\n", n, ffr(n))
}
var found [1001]int
for n := 1; n <= 40; n++ {
found[ffr(n)]++
}
for n := 1; n <= 960; n++ {
found[ffs(n)]++
}
for i := 1; i <= 1000; i++ {
if found[i] != 1 {
fmt.Println("task 4: FAIL")
return
}
}
fmt.Println("task 4: PASS")
}
| import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
var ffr, ffs func(int) int
func init() {
r := []int{0, 1}
s := []int{0, 2}
ffr = func(n int) int {
for len(r) <= n {
nrk := len(r) - 1
rNxt := r[nrk] + s[nrk]
r = append(r, rNxt)
for sn := r[nrk] + 2; sn < rNxt; sn++ {
s = append(s, sn)
}
s = append(s, rNxt+1)
}
return r[n]
}
ffs = func(n int) int {
for len(s) <= n {
ffr(len(r))
}
return s[n]
}
}
func main() {
for n := 1; n <= 10; n++ {
fmt.Printf("r(%d): %d\n", n, ffr(n))
}
var found [1001]int
for n := 1; n <= 40; n++ {
found[ffr(n)]++
}
for n := 1; n <= 960; n++ {
found[ffs(n)]++
}
for i := 1; i <= 1000; i++ {
if found[i] != 1 {
fmt.Println("task 4: FAIL")
return
}
}
fmt.Println("task 4: PASS")
}
| import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import "fmt"
var ffr, ffs func(int) int
func init() {
r := []int{0, 1}
s := []int{0, 2}
ffr = func(n int) int {
for len(r) <= n {
nrk := len(r) - 1
rNxt := r[nrk] + s[nrk]
r = append(r, rNxt)
for sn := r[nrk] + 2; sn < rNxt; sn++ {
s = append(s, sn)
}
s = append(s, rNxt+1)
}
return r[n]
}
ffs = func(n int) int {
for len(s) <= n {
ffr(len(r))
}
return s[n]
}
}
func main() {
for n := 1; n <= 10; n++ {
fmt.Printf("r(%d): %d\n", n, ffr(n))
}
var found [1001]int
for n := 1; n <= 40; n++ {
found[ffr(n)]++
}
for n := 1; n <= 960; n++ {
found[ffs(n)]++
}
for i := 1; i <= 1000; i++ {
if found[i] != 1 {
fmt.Println("task 4: FAIL")
return
}
}
fmt.Println("task 4: PASS")
}
| import java.util.*;
class Hofstadter
{
private static List<Integer> getSequence(int rlistSize, int slistSize)
{
List<Integer> rlist = new ArrayList<Integer>();
List<Integer> slist = new ArrayList<Integer>();
Collections.addAll(rlist, 1, 3, 7);
Collections.addAll(slist, 2, 4, 5, 6);
List<Integer> list = (rlistSize > 0) ? rlist : slist;
int targetSize = (rlistSize > 0) ? rlistSize : slistSize;
while (list.size() > targetSize)
list.remove(list.size() - 1);
while (list.size() < targetSize)
{
int lastIndex = rlist.size() - 1;
int lastr = rlist.get(lastIndex).intValue();
int r = lastr + slist.get(lastIndex).intValue();
rlist.add(Integer.valueOf(r));
for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++)
slist.add(Integer.valueOf(s));
}
return list;
}
public static int ffr(int n)
{ return getSequence(n, 0).get(n - 1).intValue(); }
public static int ffs(int n)
{ return getSequence(0, n).get(n - 1).intValue(); }
public static void main(String[] args)
{
System.out.print("R():");
for (int n = 1; n <= 10; n++)
System.out.print(" " + ffr(n));
System.out.println();
Set<Integer> first40R = new HashSet<Integer>();
for (int n = 1; n <= 40; n++)
first40R.add(Integer.valueOf(ffr(n)));
Set<Integer> first960S = new HashSet<Integer>();
for (int n = 1; n <= 960; n++)
first960S.add(Integer.valueOf(ffs(n)));
for (int i = 1; i <= 1000; i++)
{
Integer n = Integer.valueOf(i);
if (first40R.contains(n) == first960S.contains(n))
System.out.println("Integer " + i + " either in both or neither set");
}
System.out.println("Done");
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"log"
)
func ms(n int) (int, []int) {
M := func(x int) int { return (x + n - 1) % n }
if n <= 0 || n&1 == 0 {
n = 5
log.Println("forcing size", n)
}
m := make([]int, n*n)
i, j := 0, n/2
for k := 1; k <= n*n; k++ {
m[i*n+j] = k
if m[M(i)*n+M(j)] != 0 {
i = (i + 1) % n
} else {
i, j = M(i), M(j)
}
}
return n, m
}
func main() {
n, m := ms(5)
i := 2
for j := 1; j <= n*n; j *= 10 {
i++
}
f := fmt.Sprintf("%%%dd", i)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Printf(f, m[i*n+j])
}
fmt.Println()
}
}
| public class MagicSquare {
public static void main(String[] args) {
int n = 5;
for (int[] row : magicSquareOdd(n)) {
for (int x : row)
System.out.format("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int base) {
if (base % 2 == 0 || base < 3)
throw new IllegalArgumentException("base must be odd and > 2");
int[][] grid = new int[base][base];
int r = 0, number = 0;
int size = base * base;
int c = base / 2;
while (number++ < size) {
grid[r][c] = number;
if (r == 0) {
if (c == base - 1) {
r++;
} else {
r = base - 1;
c++;
}
} else {
if (c == base - 1) {
r--;
c = 0;
} else {
if (grid[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
}
}
return grid;
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"log"
)
func ms(n int) (int, []int) {
M := func(x int) int { return (x + n - 1) % n }
if n <= 0 || n&1 == 0 {
n = 5
log.Println("forcing size", n)
}
m := make([]int, n*n)
i, j := 0, n/2
for k := 1; k <= n*n; k++ {
m[i*n+j] = k
if m[M(i)*n+M(j)] != 0 {
i = (i + 1) % n
} else {
i, j = M(i), M(j)
}
}
return n, m
}
func main() {
n, m := ms(5)
i := 2
for j := 1; j <= n*n; j *= 10 {
i++
}
f := fmt.Sprintf("%%%dd", i)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Printf(f, m[i*n+j])
}
fmt.Println()
}
}
| public class MagicSquare {
public static void main(String[] args) {
int n = 5;
for (int[] row : magicSquareOdd(n)) {
for (int x : row)
System.out.format("%2s ", x);
System.out.println();
}
System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
}
public static int[][] magicSquareOdd(final int base) {
if (base % 2 == 0 || base < 3)
throw new IllegalArgumentException("base must be odd and > 2");
int[][] grid = new int[base][base];
int r = 0, number = 0;
int size = base * base;
int c = base / 2;
while (number++ < size) {
grid[r][c] = number;
if (r == 0) {
if (c == base - 1) {
r++;
} else {
r = base - 1;
c++;
}
} else {
if (c == base - 1) {
r--;
c = 0;
} else {
if (grid[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
}
}
return grid;
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import (
"fmt"
"log"
"os/exec"
)
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
func yellowstone(n int) []int {
m := make(map[int]bool)
a := make([]int, n+1)
for i := 1; i < 4; i++ {
a[i] = i
m[i] = true
}
min := 4
for c := 4; c <= n; c++ {
for i := min; ; i++ {
if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
a[c] = i
m[i] = true
if i == min {
min++
}
break
}
}
}
return a[1:]
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
x := make([]int, 100)
for i := 0; i < 100; i++ {
x[i] = i + 1
}
y := yellowstone(100)
fmt.Println("The first 30 Yellowstone numbers are:")
fmt.Println(y[:30])
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
check(err)
check(g.Start())
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %d\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| import java.util.ArrayList;
import java.util.List;
public class YellowstoneSequence {
public static void main(String[] args) {
System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30));
}
private static List<Integer> yellowstoneSequence(int sequenceCount) {
List<Integer> yellowstoneList = new ArrayList<Integer>();
yellowstoneList.add(1);
yellowstoneList.add(2);
yellowstoneList.add(3);
int num = 4;
List<Integer> notYellowstoneList = new ArrayList<Integer>();
int yellowSize = 3;
while ( yellowSize < sequenceCount ) {
int found = -1;
for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {
int test = notYellowstoneList.get(index);
if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {
found = index;
break;
}
}
if ( found >= 0 ) {
yellowstoneList.add(notYellowstoneList.remove(found));
yellowSize++;
}
else {
while ( true ) {
if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {
yellowstoneList.add(num);
yellowSize++;
num++;
break;
}
notYellowstoneList.add(num);
num++;
}
}
}
return yellowstoneList;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import (
"fmt"
"log"
"os/exec"
)
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
func yellowstone(n int) []int {
m := make(map[int]bool)
a := make([]int, n+1)
for i := 1; i < 4; i++ {
a[i] = i
m[i] = true
}
min := 4
for c := 4; c <= n; c++ {
for i := min; ; i++ {
if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
a[c] = i
m[i] = true
if i == min {
min++
}
break
}
}
}
return a[1:]
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
x := make([]int, 100)
for i := 0; i < 100; i++ {
x[i] = i + 1
}
y := yellowstone(100)
fmt.Println("The first 30 Yellowstone numbers are:")
fmt.Println(y[:30])
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
check(err)
check(g.Start())
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %d\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| import java.util.ArrayList;
import java.util.List;
public class YellowstoneSequence {
public static void main(String[] args) {
System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30));
}
private static List<Integer> yellowstoneSequence(int sequenceCount) {
List<Integer> yellowstoneList = new ArrayList<Integer>();
yellowstoneList.add(1);
yellowstoneList.add(2);
yellowstoneList.add(3);
int num = 4;
List<Integer> notYellowstoneList = new ArrayList<Integer>();
int yellowSize = 3;
while ( yellowSize < sequenceCount ) {
int found = -1;
for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) {
int test = notYellowstoneList.get(index);
if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) {
found = index;
break;
}
}
if ( found >= 0 ) {
yellowstoneList.add(notYellowstoneList.remove(found));
yellowSize++;
}
else {
while ( true ) {
if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) {
yellowstoneList.add(num);
yellowSize++;
num++;
break;
}
notYellowstoneList.add(num);
num++;
}
}
}
return yellowstoneList;
}
private static final int gcd(int a, int b) {
if ( b == 0 ) {
return a;
}
return gcd(b, a%b);
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
}
}
}
}
| import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
}
}
}
}
| import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
func mertens(to int) ([]int, int, int) {
if to < 1 {
to = 1
}
merts := make([]int, to+1)
primes := []int{2}
var sum, zeros, crosses int
for i := 1; i <= to; i++ {
j := i
cp := 0
spf := false
for _, p := range primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes = append(primes, i)
}
if !spf {
if cp%2 == 0 {
sum++
} else {
sum--
}
}
merts[i] = sum
if sum == 0 {
zeros++
if i > 1 && merts[i-1] != 0 {
crosses++
}
}
}
return merts, zeros, crosses
}
func main() {
merts, zeros, crosses := mertens(1000)
fmt.Println("Mertens sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
fmt.Print(" ")
continue
}
if i%20 == 0 {
fmt.Println()
}
fmt.Printf(" % d", merts[i])
}
fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000")
fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000")
}
| public class MertensFunction {
public static void main(String[] args) {
System.out.printf("First 199 terms of the merten function are as follows:%n ");
for ( int n = 1 ; n < 200 ; n++ ) {
System.out.printf("%2d ", mertenFunction(n));
if ( (n+1) % 20 == 0 ) {
System.out.printf("%n");
}
}
for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) {
int zeroCount = 0;
int zeroCrossingCount = 0;
int positiveCount = 0;
int negativeCount = 0;
int mSum = 0;
int mMin = Integer.MAX_VALUE;
int mMinIndex = 0;
int mMax = Integer.MIN_VALUE;
int mMaxIndex = 0;
int nMax = (int) Math.pow(10, exponent);
for ( int n = 1 ; n <= nMax ; n++ ) {
int m = mertenFunction(n);
mSum += m;
if ( m < mMin ) {
mMin = m;
mMinIndex = n;
}
if ( m > mMax ) {
mMax = m;
mMaxIndex = n;
}
if ( m > 0 ) {
positiveCount++;
}
if ( m < 0 ) {
negativeCount++;
}
if ( m == 0 ) {
zeroCount++;
}
if ( m == 0 && mertenFunction(n - 1) != 0 ) {
zeroCrossingCount++;
}
}
System.out.printf("%nFor M(x) with x from 1 to %,d%n", nMax);
System.out.printf("The maximum of M(x) is M(%,d) = %,d.%n", mMaxIndex, mMax);
System.out.printf("The minimum of M(x) is M(%,d) = %,d.%n", mMinIndex, mMin);
System.out.printf("The sum of M(x) is %,d.%n", mSum);
System.out.printf("The count of positive M(x) is %,d, count of negative M(x) is %,d.%n", positiveCount, negativeCount);
System.out.printf("M(x) has %,d zeroes in the interval.%n", zeroCount);
System.out.printf("M(x) has %,d crossings in the interval.%n", zeroCrossingCount);
}
}
private static int MU_MAX = 100_000_000;
private static int[] MU = null;
private static int[] MERTEN = null;
private static int mertenFunction(int n) {
if ( MERTEN != null ) {
return MERTEN[n];
}
MU = new int[MU_MAX+1];
MERTEN = new int[MU_MAX+1];
MERTEN[1] = 1;
int sqrt = (int) Math.sqrt(MU_MAX);
for ( int i = 0 ; i < MU_MAX ; i++ ) {
MU[i] = 1;
}
for ( int i = 2 ; i <= sqrt ; i++ ) {
if ( MU[i] == 1 ) {
for ( int j = i ; j <= MU_MAX ; j += i ) {
MU[j] *= -i;
}
for ( int j = i*i ; j <= MU_MAX ; j += i*i ) {
MU[j] = 0;
}
}
}
int sum = 1;
for ( int i = 2 ; i <= MU_MAX ; i++ ) {
if ( MU[i] == i ) {
MU[i] = 1;
}
else if ( MU[i] == -i ) {
MU[i] = -1;
}
else if ( MU[i] < 0 ) {
MU[i] = 1;
}
else if ( MU[i] > 0 ) {
MU[i] = -1;
}
sum += MU[i];
MERTEN[i] = sum;
}
return MERTEN[n];
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import (
"fmt"
"sort"
"strings"
)
var count int = 0
func interactiveCompare(s1, s2 string) bool {
count++
fmt.Printf("(%d) Is %s < %s? ", count, s1, s2)
var response string
_, err := fmt.Scanln(&response)
return err == nil && strings.HasPrefix(response, "y")
}
func main() {
items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"}
var sortedItems []string
for _, item := range items {
fmt.Printf("Inserting '%s' into %s\n", item, sortedItems)
spotToInsert := sort.Search(len(sortedItems), func(i int) bool {
return interactiveCompare(item, sortedItems[i])
})
sortedItems = append(sortedItems[:spotToInsert],
append([]string{item}, sortedItems[spotToInsert:]...)...)
}
fmt.Println(sortedItems)
}
| import java.util.*;
public class SortComp1 {
public static void main(String[] args) {
List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
List<String> sortedItems = new ArrayList<>();
Comparator<String> interactiveCompare = new Comparator<String>() {
int count = 0;
Scanner s = new Scanner(System.in);
public int compare(String s1, String s2) {
System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2);
return s.nextInt();
}
};
for (String item : items) {
System.out.printf("Inserting '%s' into %s\n", item, sortedItems);
int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);
if (spotToInsert < 0) spotToInsert = ~spotToInsert;
sortedItems.add(spotToInsert, item);
}
System.out.println(sortedItems);
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math"
)
func Fib1000() []float64 {
a, b, r := 0., 1., [1000]float64{}
for i := range r {
r[i], a, b = b, b, b+a
}
return r[:]
}
func main() {
show(Fib1000(), "First 1000 Fibonacci numbers")
}
func show(c []float64, title string) {
var f [9]int
for _, v := range c {
f[fmt.Sprintf("%g", v)[0]-'1']++
}
fmt.Println(title)
fmt.Println("Digit Observed Predicted")
for i, n := range f {
fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)),
math.Log10(1+1/float64(i+1)))
}
}
| import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import (
"fmt"
"math"
)
func Fib1000() []float64 {
a, b, r := 0., 1., [1000]float64{}
for i := range r {
r[i], a, b = b, b, b+a
}
return r[:]
}
func main() {
show(Fib1000(), "First 1000 Fibonacci numbers")
}
func show(c []float64, title string) {
var f [9]int
for _, v := range c {
f[fmt.Sprintf("%g", v)[0]-'1']++
}
fmt.Println(title)
fmt.Println("Digit Observed Predicted")
for i, n := range f {
fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)),
math.Log10(1+1/float64(i+1)))
}
}
| import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"strings"
"time"
)
func main() {
watches := []string{
"First", "Middle", "Morning", "Forenoon",
"Afternoon", "Dog", "First",
}
for {
t := time.Now()
h := t.Hour()
m := t.Minute()
s := t.Second()
if (m == 0 || m == 30) && s == 0 {
bell := 0
if m == 30 {
bell = 1
}
bells := (h*2 + bell) % 8
watch := h/4 + 1
if bells == 0 {
bells = 8
watch--
}
sound := strings.Repeat("\a", bells)
pl := "s"
if bells == 1 {
pl = " "
}
w := watches[watch] + " watch"
if watch == 5 {
if bells < 5 {
w = "First " + w
} else {
w = "Last " + w
}
}
fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w)
}
time.Sleep(1 * time.Second)
}
}
| import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000));
while (next < time) {
next += 30 * 60 * 1000;
numBells = 1 + (numBells % 8);
}
while (true) {
long wait = 100L;
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
return;
}
}
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"strings"
"time"
)
func main() {
watches := []string{
"First", "Middle", "Morning", "Forenoon",
"Afternoon", "Dog", "First",
}
for {
t := time.Now()
h := t.Hour()
m := t.Minute()
s := t.Second()
if (m == 0 || m == 30) && s == 0 {
bell := 0
if m == 30 {
bell = 1
}
bells := (h*2 + bell) % 8
watch := h/4 + 1
if bells == 0 {
bells = 8
watch--
}
sound := strings.Repeat("\a", bells)
pl := "s"
if bells == 1 {
pl = " "
}
w := watches[watch] + " watch"
if watch == 5 {
if bells < 5 {
w = "First " + w
} else {
w = "Last " + w
}
}
fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w)
}
time.Sleep(1 * time.Second)
}
}
| import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class NauticalBell extends Thread {
public static void main(String[] args) {
NauticalBell bells = new NauticalBell();
bells.setDaemon(true);
bells.start();
try {
bells.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
@Override
public void run() {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
int numBells = 0;
long time = System.currentTimeMillis();
long next = time - (time % (24 * 60 * 60 * 1000));
while (next < time) {
next += 30 * 60 * 1000;
numBells = 1 + (numBells % 8);
}
while (true) {
long wait = 100L;
time = System.currentTimeMillis();
if (time - next >= 0) {
String bells = numBells == 1 ? "bell" : "bells";
String timeString = sdf.format(time);
System.out.printf("%s : %d %s\n", timeString, numBells, bells);
next += 30 * 60 * 1000;
wait = next - time;
numBells = 1 + (numBells % 8);
}
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
return;
}
}
}
}
|
Convert this Go snippet to Java and keep its semantics consistent. | package main
import "fmt"
func main() {
for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
f, ok := arFib(n)
if ok {
fmt.Printf("fib %d = %d\n", n, f)
} else {
fmt.Println("fib undefined for negative numbers")
}
}
}
func arFib(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n < 2:
return n, true
}
return yc(func(recurse fn) fn {
return func(left, term1, term2 int) int {
if left == 0 {
return term1+term2
}
return recurse(left-1, term1+term2, term1)
}
})(n-2, 1, 0), true
}
type fn func(int, int, int) int
type ff func(fn) fn
type fx func(fx) fn
func yc(f ff) fn {
return func(x fx) fn {
return x(x)
}(func(x fx) fn {
return f(func(a1, a2, a3 int) int {
return x(x)(a1, a2, a3)
})
})
}
| public static long fib(int n) {
if (n < 0)
throw new IllegalArgumentException("n can not be a negative number");
return new Object() {
private long fibInner(int n) {
return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2));
}
}.fibInner(n);
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
| String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
| String strOrig = 'brooms';
String str1 = strOrig.substring(1, strOrig.length());
system.debug(str1);
String str2 = strOrig.substring(0, strOrig.length()-1);
system.debug(str2);
String str3 = strOrig.substring(1, strOrig.length()-1);
system.debug(str3);
String strOrig = 'brooms';
String str1 = strOrig.replaceAll( '^.', '' );
system.debug(str1);
String str2 = strOrig.replaceAll( '.$', '' ) ;
system.debug(str2);
String str3 = strOrig.replaceAll( '^.|.$', '' );
system.debug(str3);
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import (
"fmt"
"log"
"math"
"rcu"
)
func cantorPair(x, y int) int {
if x < 0 || y < 0 {
log.Fatal("Arguments must be non-negative integers.")
}
return (x*x + 3*x + 2*x*y + y + y*y) / 2
}
func pi(n int) int {
if n < 2 {
return 0
}
if n == 2 {
return 1
}
primes := rcu.Primes(int(math.Sqrt(float64(n))))
a := len(primes)
memoPhi := make(map[int]int)
var phi func(x, a int) int
phi = func(x, a int) int {
if a < 1 {
return x
}
if a == 1 {
return x - (x >> 1)
}
pa := primes[a-1]
if x <= pa {
return 1
}
key := cantorPair(x, a)
if v, ok := memoPhi[key]; ok {
return v
}
memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)
return memoPhi[key]
}
return phi(n, a) + a - 1
}
func main() {
for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {
fmt.Printf("10^%d %d\n", i, pi(n))
}
}
| import java.util.*;
public class LegendrePrimeCounter {
public static void main(String[] args) {
LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
System.out.printf("10^%d\t%d\n", i, counter.primeCount((n)));
}
private List<Integer> primes;
public LegendrePrimeCounter(int limit) {
primes = generatePrimes((int)Math.sqrt((double)limit));
}
public int primeCount(int n) {
if (n < 2)
return 0;
int a = primeCount((int)Math.sqrt((double)n));
return phi(n, a) + a - 1;
}
private int phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes.get(a - 1);
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
private static List<Integer> generatePrimes(int limit) {
boolean[] sieve = new boolean[limit >> 1];
Arrays.fill(sieve, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
List<Integer> primes = new ArrayList<>();
if (limit > 2)
primes.add(2);
for (int i = 1; i < sieve.length; ++i) {
if (sieve[i])
primes.add((i << 1) + 1);
}
return primes;
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "C"
import "unsafe"
func main() {
C.Run()
}
const msg = "Here am I"
func Query(cbuf *C.char, csiz *C.size_t) C.int {
if int(*csiz) <= len(msg) {
return 0
}
pbuf := uintptr(unsafe.Pointer(cbuf))
for i := 0; i < len(msg); i++ {
*((*byte)(unsafe.Pointer(pbuf))) = msg[i]
pbuf++
}
*((*byte)(unsafe.Pointer(pbuf))) = 0
*csiz = C.size_t(len(msg) + 1)
return 1
}
|
public class Query {
public static boolean call(byte[] data, int[] length)
throws java.io.UnsupportedEncodingException
{
String message = "Here am I";
byte[] mb = message.getBytes("utf-8");
if (length[0] < mb.length)
return false;
length[0] = mb.length;
System.arraycopy(mb, 0, data, 0, mb.length);
return true;
}
}
|
Port the provided Go code into Java while preserving the original functionality. | package main
import (
"bufio"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
var blankLine = "\n"
var printLongest func(string) string
printLongest = func(candidate string) (longest string) {
longest = candidate
s, err := in.ReadString('\n')
defer func() {
recover()
defer func() {
recover()
}()
_ = blankLine[0]
func() {
defer func() {
recover()
}()
_ = s[len(longest)]
longest = s
}()
longest = printLongest(longest)
func() {
defer func() {
recover()
os.Stdout.WriteString(s)
}()
_ = longest[len(s)]
s = ""
}()
}()
_ = err.(error)
os.Stdout.WriteString(blankLine)
blankLine = ""
return
}
printLongest("")
}
| import java.io.File;
import java.util.Scanner;
public class LongestStringChallenge {
public static void main(String[] args) throws Exception {
String lines = "", longest = "";
try (Scanner sc = new Scanner(new File("lines.txt"))) {
while(sc.hasNext()) {
String line = sc.nextLine();
if (longer(longest, line))
lines = longest = line;
else if (!longer(line, longest))
lines = lines.concat("\n").concat(line);
}
}
System.out.println(lines);
}
static boolean longer(String a, String b) {
try {
String dummy = a.substring(b.length());
} catch (StringIndexOutOfBoundsException e) {
return true;
}
return false;
}
}
|
Ensure the translated Java code behaves exactly like the original Go snippet. | package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{})
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
}
| import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction;
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) {
tape = input;
}
public void initializeTape(String input) {
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() {
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) {
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol);
tsp.state = trans.to.state;
if (trans.direction == -1) {
if (!head.hasPrevious()) {
head.add(blankSymbol);
}
tsp.tapeSymbol = head.previous();
} else if (trans.direction == 1) {
head.next();
if (!head.hasNext()) {
head.add(blankSymbol);
head.previous();
}
tsp.tapeSymbol = head.next();
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
}
|
Port the following code from Go to Java with equivalent syntax and logic. | package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{})
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
}
| import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t : transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((state == null) ? 0 : state.hashCode());
result = prime
* result
+ ((tapeSymbol == null) ? 0 : tapeSymbol
.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StateTapeSymbolPair other = (StateTapeSymbolPair) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (tapeSymbol == null) {
if (other.tapeSymbol != null)
return false;
} else if (!tapeSymbol.equals(other.tapeSymbol))
return false;
return true;
}
@Override
public String toString() {
return "(" + state + "," + tapeSymbol + ")";
}
}
public static class Transition {
private StateTapeSymbolPair from;
private StateTapeSymbolPair to;
private int direction;
public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) {
this.from = from;
this.to = to;
this.direction = direction;
}
@Override
public String toString() {
return from + "=>" + to + "/" + direction;
}
}
public void initializeTape(List<String> input) {
tape = input;
}
public void initializeTape(String input) {
tape = new LinkedList<String>();
for (int i = 0; i < input.length(); i++) {
tape.add(input.charAt(i) + "");
}
}
public List<String> runTM() {
if (tape.size() == 0) {
tape.add(blankSymbol);
}
head = tape.listIterator();
head.next();
head.previous();
StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0));
while (transitions.containsKey(tsp)) {
System.out.println(this + " --- " + transitions.get(tsp));
Transition trans = transitions.get(tsp);
head.set(trans.to.tapeSymbol);
tsp.state = trans.to.state;
if (trans.direction == -1) {
if (!head.hasPrevious()) {
head.add(blankSymbol);
}
tsp.tapeSymbol = head.previous();
} else if (trans.direction == 1) {
head.next();
if (!head.hasNext()) {
head.add(blankSymbol);
head.previous();
}
tsp.tapeSymbol = head.next();
head.previous();
} else {
tsp.tapeSymbol = trans.to.tapeSymbol;
}
}
System.out.println(this + " --- " + tsp);
if (terminalStates.contains(tsp.state)) {
return tape;
} else {
return null;
}
}
@Override
public String toString() {
try {
int headPos = head.previousIndex();
String s = "[ ";
for (int i = 0; i <= headPos; i++) {
s += tape.get(i) + " ";
}
s += "[H] ";
for (int i = headPos + 1; i < tape.size(); i++) {
s += tape.get(i) + " ";
}
return s + "]";
} catch (Exception e) {
return "";
}
}
public static void main(String[] args) {
String init = "q0";
String blank = "b";
Set<String> term = new HashSet<String>();
term.add("qf");
Set<Transition> trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0));
UTM machine = new UTM(trans, term, init, blank);
machine.initializeTape("111");
System.out.println("Output (si): " + machine.runTM() + "\n");
init = "a";
term.clear();
term.add("halt");
blank = "0";
trans.clear();
trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1));
trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1));
trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("");
System.out.println("Output (bb): " + machine.runTM());
init = "s0";
blank = "*";
term = new HashSet<String>();
term.add("see");
trans = new HashSet<Transition>();
trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1));
trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1));
trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1));
trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1));
trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1));
machine = new UTM(trans, term, init, blank);
machine.initializeTape("babbababaa");
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"os"
)
func createFile(fn string) {
f, err := os.Create(fn)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("file", fn, "created!")
f.Close()
}
func createDir(dn string) {
err := os.Mkdir(dn, 0666)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("directory", dn, "created!")
}
func main() {
createFile("input.txt")
createFile("/input.txt")
createDir("docs")
createDir("/docs")
}
| import java.io.*;
public class CreateFileTest {
public static void main(String args[]) {
try {
new File("output.txt").createNewFile();
new File(File.separator + "output.txt").createNewFile();
new File("docs").mkdir();
new File(File.separator + "docs").mkdir();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"strconv"
)
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("The first 35 unprimeable numbers are:")
count := 0
var firstNum [10]int
outer:
for i, countFirst := 100, 0; countFirst < 10; i++ {
if isPrime(i) {
continue
}
s := strconv.Itoa(i)
le := len(s)
b := []byte(s)
for j := 0; j < le; j++ {
for k := byte('0'); k <= '9'; k++ {
if s[j] == k {
continue
}
b[j] = k
n, _ := strconv.Atoi(string(b))
if isPrime(n) {
continue outer
}
}
b[j] = s[j]
}
lastDigit := s[le-1] - '0'
if firstNum[lastDigit] == 0 {
firstNum[lastDigit] = i
countFirst++
}
count++
if count <= 35 {
fmt.Printf("%d ", i)
}
if count == 35 {
fmt.Print("\n\nThe 600th unprimeable number is: ")
}
if count == 600 {
fmt.Printf("%s\n\n", commatize(i))
}
}
fmt.Println("The first unprimeable number that ends in:")
for i := 0; i < 10; i++ {
fmt.Printf(" %d is: %9s\n", i, commatize(firstNum[i]))
}
}
| public class UnprimeableNumbers {
private static int MAX = 10_000_000;
private static boolean[] primes = new boolean[MAX];
public static void main(String[] args) {
sieve();
System.out.println("First 35 unprimeable numbers:");
displayUnprimeableNumbers(35);
int n = 600;
System.out.printf("%nThe %dth unprimeable number = %,d%n%n", n, nthUnprimeableNumber(n));
int[] lowest = genLowest();
System.out.println("Least unprimeable number that ends in:");
for ( int i = 0 ; i <= 9 ; i++ ) {
System.out.printf(" %d is %,d%n", i, lowest[i]);
}
}
private static int[] genLowest() {
int[] lowest = new int[10];
int count = 0;
int test = 1;
while ( count < 10 ) {
test++;
if ( unPrimable(test) && lowest[test % 10] == 0 ) {
lowest[test % 10] = test;
count++;
}
}
return lowest;
}
private static int nthUnprimeableNumber(int maxCount) {
int test = 1;
int count = 0;
int result = 0;
while ( count < maxCount ) {
test++;
if ( unPrimable(test) ) {
count++;
result = test;
}
}
return result;
}
private static void displayUnprimeableNumbers(int maxCount) {
int test = 1;
int count = 0;
while ( count < maxCount ) {
test++;
if ( unPrimable(test) ) {
count++;
System.out.printf("%d ", test);
}
}
System.out.println();
}
private static boolean unPrimable(int test) {
if ( primes[test] ) {
return false;
}
String s = test + "";
for ( int i = 0 ; i < s.length() ; i++ ) {
for ( int j = 0 ; j <= 9 ; j++ ) {
if ( primes[Integer.parseInt(replace(s, i, j))] ) {
return false;
}
}
}
return true;
}
private static String replace(String str, int position, int value) {
char[] sChar = str.toCharArray();
sChar[position] = (char) value;
return str.substring(0, position) + value + str.substring(position + 1);
}
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalsTrianglePuzzle {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d),
Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),
Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),
Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));
List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);
List<Double> solution = cramersRule(mat, b);
System.out.println("Solution = " + cramersRule(mat, b));
System.out.printf("X = %.2f%n", solution.get(8));
System.out.printf("Y = %.2f%n", solution.get(9));
System.out.printf("Z = %.2f%n", solution.get(10));
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant();
List<Double> result = new ArrayList<>();
for ( int i = 0 ; i < b.size() ; i++ ) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator);
}
return result;
}
private static class Matrix {
private List<List<Double>> matrix;
@Override
public String toString() {
return matrix.toString();
}
@SafeVarargs
public Matrix(List<Double> ... lists) {
matrix = new ArrayList<>();
for ( List<Double> list : lists) {
matrix.add(list);
}
}
public Matrix(List<List<Double>> mat) {
matrix = mat;
}
public double determinant() {
if ( matrix.size() == 1 ) {
return get(0, 0);
}
if ( matrix.size() == 2 ) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);
}
double sum = 0;
double sign = 1;
for ( int i = 0 ; i < matrix.size() ; i++ ) {
sum += sign * get(0, i) * coFactor(0, i).determinant();
sign *= -1;
}
return sum;
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>();
for ( int i = 0 ; i < matrix.size() ; i++ ) {
if ( i == row ) {
continue;
}
List<Double> list = new ArrayList<>();
for ( int j = 0 ; j < matrix.size() ; j++ ) {
if ( j == col ) {
continue;
}
list.add(get(i, j));
}
mat.add(list);
}
return new Matrix(mat);
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>();
for ( int row = 0 ; row < matrix.size() ; row++ ) {
List<Double> list = new ArrayList<>();
for ( int col = 0 ; col < matrix.size() ; col++ ) {
double value = get(row, col);
if ( col == column ) {
value = b.get(row);
}
list.add(value);
}
mat.add(list);
}
return new Matrix(mat);
}
private double get(int row, int col) {
return matrix.get(row).get(col);
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalsTrianglePuzzle {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d),
Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),
Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),
Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));
List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);
List<Double> solution = cramersRule(mat, b);
System.out.println("Solution = " + cramersRule(mat, b));
System.out.printf("X = %.2f%n", solution.get(8));
System.out.printf("Y = %.2f%n", solution.get(9));
System.out.printf("Z = %.2f%n", solution.get(10));
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant();
List<Double> result = new ArrayList<>();
for ( int i = 0 ; i < b.size() ; i++ ) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator);
}
return result;
}
private static class Matrix {
private List<List<Double>> matrix;
@Override
public String toString() {
return matrix.toString();
}
@SafeVarargs
public Matrix(List<Double> ... lists) {
matrix = new ArrayList<>();
for ( List<Double> list : lists) {
matrix.add(list);
}
}
public Matrix(List<List<Double>> mat) {
matrix = mat;
}
public double determinant() {
if ( matrix.size() == 1 ) {
return get(0, 0);
}
if ( matrix.size() == 2 ) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);
}
double sum = 0;
double sign = 1;
for ( int i = 0 ; i < matrix.size() ; i++ ) {
sum += sign * get(0, i) * coFactor(0, i).determinant();
sign *= -1;
}
return sum;
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>();
for ( int i = 0 ; i < matrix.size() ; i++ ) {
if ( i == row ) {
continue;
}
List<Double> list = new ArrayList<>();
for ( int j = 0 ; j < matrix.size() ; j++ ) {
if ( j == col ) {
continue;
}
list.add(get(i, j));
}
mat.add(list);
}
return new Matrix(mat);
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>();
for ( int row = 0 ; row < matrix.size() ; row++ ) {
List<Double> list = new ArrayList<>();
for ( int col = 0 ; col < matrix.size() ; col++ ) {
double value = get(row, col);
if ( col == column ) {
value = b.get(row);
}
list.add(value);
}
mat.add(list);
}
return new Matrix(mat);
}
private double get(int row, int col) {
return matrix.get(row).get(col);
}
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math/big"
)
var (
zero = new(big.Int)
prod = new(big.Int)
fact = new(big.Int)
)
func ccFactors(n, m uint64) (*big.Int, bool) {
prod.SetUint64(6*m + 1)
if !prod.ProbablyPrime(0) {
return zero, false
}
fact.SetUint64(12*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
for i := uint64(1); i <= n-2; i++ {
fact.SetUint64((1<<i)*9*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
}
return prod, true
}
func ccNumbers(start, end uint64) {
for n := start; n <= end; n++ {
m := uint64(1)
if n > 4 {
m = 1 << (n - 4)
}
for {
num, ok := ccFactors(n, m)
if ok {
fmt.Printf("a(%d) = %d\n", n, num)
break
}
if n <= 4 {
m++
} else {
m += 1 << (n - 4)
}
}
}
}
func main() {
ccNumbers(3, 9)
}
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class ChernicksCarmichaelNumbers {
public static void main(String[] args) {
for ( long n = 3 ; n < 10 ; n++ ) {
long m = 0;
boolean foundComposite = true;
List<Long> factors = null;
while ( foundComposite ) {
m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5);
factors = U(n, m);
foundComposite = false;
for ( long factor : factors ) {
if ( ! isPrime(factor) ) {
foundComposite = true;
break;
}
}
}
System.out.printf("U(%d, %d) = %s = %s %n", n, m, display(factors), multiply(factors));
}
}
private static String display(List<Long> factors) {
return factors.toString().replace("[", "").replace("]", "").replaceAll(", ", " * ");
}
private static BigInteger multiply(List<Long> factors) {
BigInteger result = BigInteger.ONE;
for ( long factor : factors ) {
result = result.multiply(BigInteger.valueOf(factor));
}
return result;
}
private static List<Long> U(long n, long m) {
List<Long> factors = new ArrayList<>();
factors.add(6*m + 1);
factors.add(12*m + 1);
for ( int i = 1 ; i <= n-2 ; i++ ) {
factors.add(((long)Math.pow(2, i)) * 9 * m + 1);
}
return factors;
}
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
private static final void sieve() {
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
public static final boolean isPrime(long testValue) {
if ( testValue == 2 ) return true;
if ( testValue % 2 == 0 ) return false;
if ( testValue <= MAX ) return isPrimeTrivial(testValue);
long d = testValue-1;
int s = 0;
while ( d % 2 == 0 ) {
s += 1;
d /= 2;
}
if ( testValue < 1373565L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 4759123141L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(7, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 10000000000000000L ) {
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
if ( ! aSrp(24251, s, d, testValue) ) {
return false;
}
return true;
}
if ( ! aSrp(37, s, d, testValue) ) {
return false;
}
if ( ! aSrp(47, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
if ( ! aSrp(73, s, d, testValue) ) {
return false;
}
if ( ! aSrp(83, s, d, testValue) ) {
return false;
}
return true;
}
private static final boolean aSrp(int a, int s, long d, long n) {
long modPow = modPow(a, d, n);
if ( modPow == 1 ) {
return true;
}
int twoExpR = 1;
for ( int r = 0 ; r < s ; r++ ) {
if ( modPow(modPow, twoExpR, n) == n-1 ) {
return true;
}
twoExpR *= 2;
}
return false;
}
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
public static final long modPow(long base, long exponent, long modulus) {
long result = 1;
while ( exponent > 0 ) {
if ( exponent % 2 == 1 ) {
if ( result > SQRT || base > SQRT ) {
result = multiply(result, base, modulus);
}
else {
result = (result * base) % modulus;
}
}
exponent >>= 1;
if ( base > SQRT ) {
base = multiply(base, base, modulus);
}
else {
base = (base * base) % modulus;
}
}
return result;
}
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
}
|
Write the same code in Java as shown below in Go. | package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
| import java.util.Objects;
public class FindTriangle {
private static final double EPS = 0.001;
private static final double EPS_SQUARE = EPS * EPS;
public static class Point {
private final double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return String.format("(%f, %f)", x, y);
}
}
public static class Triangle {
private final Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = Objects.requireNonNull(p1);
this.p2 = Objects.requireNonNull(p2);
this.p3 = Objects.requireNonNull(p3);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public Point getP3() {
return p3;
}
private boolean pointInTriangleBoundingBox(Point p) {
var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;
var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;
var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;
var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;
return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());
}
private static double side(Point p1, Point p2, Point p) {
return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());
}
private boolean nativePointInTriangle(Point p) {
boolean checkSide1 = side(p1, p2, p) >= 0;
boolean checkSide2 = side(p2, p3, p) >= 0;
boolean checkSide3 = side(p3, p1, p) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {
double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());
double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;
if (dotProduct < 0) {
return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());
}
if (dotProduct <= 1) {
double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
}
return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());
}
private boolean accuratePointInTriangle(Point p) {
if (!pointInTriangleBoundingBox(p)) {
return false;
}
if (nativePointInTriangle(p)) {
return true;
}
if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
return true;
}
return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;
}
public boolean within(Point p) {
Objects.requireNonNull(p);
return accuratePointInTriangle(p);
}
@Override
public String toString() {
return String.format("Triangle[%s, %s, %s]", p1, p2, p3);
}
}
private static void test(Triangle t, Point p) {
System.out.println(t);
System.out.printf("Point %s is within triangle? %s\n", p, t.within(p));
}
public static void main(String[] args) {
var p1 = new Point(1.5, 2.4);
var p2 = new Point(5.1, -3.1);
var p3 = new Point(-3.8, 1.2);
var tri = new Triangle(p1, p2, p3);
test(tri, new Point(0, 0));
test(tri, new Point(0, 1));
test(tri, new Point(3, 1));
System.out.println();
p1 = new Point(1.0 / 10, 1.0 / 9);
p2 = new Point(100.0 / 8, 100.0 / 3);
p3 = new Point(100.0 / 4, 100.0 / 9);
tri = new Triangle(p1, p2, p3);
var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));
test(tri, pt);
System.out.println();
p3 = new Point(-100.0 / 8, 100.0 / 6);
tri = new Triangle(p1, p2, p3);
test(tri, pt);
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
| import java.util.Objects;
public class FindTriangle {
private static final double EPS = 0.001;
private static final double EPS_SQUARE = EPS * EPS;
public static class Point {
private final double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return String.format("(%f, %f)", x, y);
}
}
public static class Triangle {
private final Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = Objects.requireNonNull(p1);
this.p2 = Objects.requireNonNull(p2);
this.p3 = Objects.requireNonNull(p3);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public Point getP3() {
return p3;
}
private boolean pointInTriangleBoundingBox(Point p) {
var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;
var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;
var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;
var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;
return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());
}
private static double side(Point p1, Point p2, Point p) {
return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());
}
private boolean nativePointInTriangle(Point p) {
boolean checkSide1 = side(p1, p2, p) >= 0;
boolean checkSide2 = side(p2, p3, p) >= 0;
boolean checkSide3 = side(p3, p1, p) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {
double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());
double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;
if (dotProduct < 0) {
return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());
}
if (dotProduct <= 1) {
double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
}
return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());
}
private boolean accuratePointInTriangle(Point p) {
if (!pointInTriangleBoundingBox(p)) {
return false;
}
if (nativePointInTriangle(p)) {
return true;
}
if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
return true;
}
return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;
}
public boolean within(Point p) {
Objects.requireNonNull(p);
return accuratePointInTriangle(p);
}
@Override
public String toString() {
return String.format("Triangle[%s, %s, %s]", p1, p2, p3);
}
}
private static void test(Triangle t, Point p) {
System.out.println(t);
System.out.printf("Point %s is within triangle? %s\n", p, t.within(p));
}
public static void main(String[] args) {
var p1 = new Point(1.5, 2.4);
var p2 = new Point(5.1, -3.1);
var p3 = new Point(-3.8, 1.2);
var tri = new Triangle(p1, p2, p3);
test(tri, new Point(0, 0));
test(tri, new Point(0, 1));
test(tri, new Point(3, 1));
System.out.println();
p1 = new Point(1.0 / 10, 1.0 / 9);
p2 = new Point(100.0 / 8, 100.0 / 3);
p3 = new Point(100.0 / 4, 100.0 / 9);
tri = new Triangle(p1, p2, p3);
var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));
test(tri, pt);
System.out.println();
p3 = new Point(-100.0 / 8, 100.0 / 6);
tri = new Triangle(p1, p2, p3);
test(tri, pt);
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
| import java.util.Objects;
public class FindTriangle {
private static final double EPS = 0.001;
private static final double EPS_SQUARE = EPS * EPS;
public static class Point {
private final double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return String.format("(%f, %f)", x, y);
}
}
public static class Triangle {
private final Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = Objects.requireNonNull(p1);
this.p2 = Objects.requireNonNull(p2);
this.p3 = Objects.requireNonNull(p3);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public Point getP3() {
return p3;
}
private boolean pointInTriangleBoundingBox(Point p) {
var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;
var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;
var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;
var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;
return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());
}
private static double side(Point p1, Point p2, Point p) {
return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());
}
private boolean nativePointInTriangle(Point p) {
boolean checkSide1 = side(p1, p2, p) >= 0;
boolean checkSide2 = side(p2, p3, p) >= 0;
boolean checkSide3 = side(p3, p1, p) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {
double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());
double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;
if (dotProduct < 0) {
return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());
}
if (dotProduct <= 1) {
double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
}
return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());
}
private boolean accuratePointInTriangle(Point p) {
if (!pointInTriangleBoundingBox(p)) {
return false;
}
if (nativePointInTriangle(p)) {
return true;
}
if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
return true;
}
return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;
}
public boolean within(Point p) {
Objects.requireNonNull(p);
return accuratePointInTriangle(p);
}
@Override
public String toString() {
return String.format("Triangle[%s, %s, %s]", p1, p2, p3);
}
}
private static void test(Triangle t, Point p) {
System.out.println(t);
System.out.printf("Point %s is within triangle? %s\n", p, t.within(p));
}
public static void main(String[] args) {
var p1 = new Point(1.5, 2.4);
var p2 = new Point(5.1, -3.1);
var p3 = new Point(-3.8, 1.2);
var tri = new Triangle(p1, p2, p3);
test(tri, new Point(0, 0));
test(tri, new Point(0, 1));
test(tri, new Point(3, 1));
System.out.println();
p1 = new Point(1.0 / 10, 1.0 / 9);
p2 = new Point(100.0 / 8, 100.0 / 3);
p3 = new Point(100.0 / 4, 100.0 / 9);
tri = new Triangle(p1, p2, p3);
var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));
test(tri, pt);
System.out.println();
p3 = new Point(-100.0 / 8, 100.0 / 6);
tri = new Triangle(p1, p2, p3);
test(tri, pt);
}
}
|
Can you help me rewrite this code in Java instead of Go, keeping it the same logically? | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
| public class TauFunction {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
public static void main(String[] args) {
final int limit = 100;
System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%3d", divisorCount(n));
if (n % 20 == 0) {
System.out.println();
}
}
}
}
|
Translate the given Go code snippet into Java without altering its behavior. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
| public class TauFunction {
private static long divisorCount(long n) {
long total = 1;
for (; (n & 1) == 0; n >>= 1) {
++total;
}
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
if (n > 1) {
total *= 2;
}
return total;
}
public static void main(String[] args) {
final int limit = 100;
System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%3d", divisorCount(n));
if (n % 20 == 0) {
System.out.println();
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
pm := big.NewInt(1)
var px, nx int
var pb big.Int
primes(4000, func(p int64) bool {
pm.Mul(pm, pb.SetInt64(p))
px++
if pb.Add(pm, one).ProbablyPrime(0) ||
pb.Sub(pm, one).ProbablyPrime(0) {
fmt.Print(px, " ")
nx++
if nx == 20 {
fmt.Println()
return false
}
}
return true
})
}
func primes(limit int, f func(int64) bool) {
c := make([]bool, limit)
c[0] = true
c[1] = true
lm := int64(limit)
p := int64(2)
for {
f(p)
p2 := p * p
if p2 >= lm {
break
}
for i := p2; i < lm; i += p {
c[i] = true
}
for {
p++
if !c[p] {
break
}
}
}
for p++; p < lm; p++ {
if !c[p] && !f(p) {
break
}
}
}
| import java.math.BigInteger;
public class PrimorialPrimes {
final static int sieveLimit = 1550_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
int count = 0;
for (int i = 1; i < 1000_000 && count < 20; i++) {
BigInteger b = primorial(i);
if (b.add(BigInteger.ONE).isProbablePrime(1)
|| b.subtract(BigInteger.ONE).isProbablePrime(1)) {
System.out.printf("%d ", i);
count++;
}
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}
|
Write the same algorithm in Java as shown in this Go implementation. | package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
| import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
gene.runSequence();
}
}
public class Sequence {
private final String seq;
public Sequence(String sq) {
this.seq = sq;
}
public void prettyPrint() {
System.out.println("Sequence:");
int i = 0;
for ( ; i < seq.length() - 50 ; i += 50) {
System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
}
System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
}
public void displayCount() {
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0 ; i < seq.length() ; ++i) {
counter.merge(seq.charAt(i), 1, Integer::sum);
}
System.out.println("Base vs. Count:");
counter.forEach(
key, value -> System.out.printf("%5s : %s\n", key, value));
System.out.printf("%5s: %s\n", "SUM", seq.length());
}
public void runSequence() {
this.prettyPrint();
this.displayCount();
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import (
"fmt"
"sort"
)
func main() {
dna := "" +
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"
fmt.Println("SEQUENCE:")
le := len(dna)
for i := 0; i < le; i += 50 {
k := i + 50
if k > le {
k = le
}
fmt.Printf("%5d: %s\n", i, dna[i:k])
}
baseMap := make(map[byte]int)
for i := 0; i < le; i++ {
baseMap[dna[i]]++
}
var bases []byte
for k := range baseMap {
bases = append(bases, k)
}
sort.Slice(bases, func(i, j int) bool {
return bases[i] < bases[j]
})
fmt.Println("\nBASE COUNT:")
for _, base := range bases {
fmt.Printf(" %c: %3d\n", base, baseMap[base])
}
fmt.Println(" ------")
fmt.Println(" Σ:", le)
fmt.Println(" ======")
}
| import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
gene.runSequence();
}
}
public class Sequence {
private final String seq;
public Sequence(String sq) {
this.seq = sq;
}
public void prettyPrint() {
System.out.println("Sequence:");
int i = 0;
for ( ; i < seq.length() - 50 ; i += 50) {
System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
}
System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
}
public void displayCount() {
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0 ; i < seq.length() ; ++i) {
counter.merge(seq.charAt(i), 1, Integer::sum);
}
System.out.println("Base vs. Count:");
counter.forEach(
key, value -> System.out.printf("%5s : %s\n", key, value));
System.out.printf("%5s: %s\n", "SUM", seq.length());
}
public void runSequence() {
this.prettyPrint();
this.displayCount();
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import (
"hash/fnv"
"log"
"math/rand"
"os"
"time"
)
var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
const hunger = 3
const think = time.Second / 100
const eat = time.Second / 100
var fmt = log.New(os.Stdout, "", 0)
var done = make(chan bool)
type fork byte
func philosopher(phName string,
dominantHand, otherHand chan fork, done chan bool) {
fmt.Println(phName, "seated")
h := fnv.New64a()
h.Write([]byte(phName))
rg := rand.New(rand.NewSource(int64(h.Sum64())))
rSleep := func(t time.Duration) {
time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))
}
for h := hunger; h > 0; h-- {
fmt.Println(phName, "hungry")
<-dominantHand
<-otherHand
fmt.Println(phName, "eating")
rSleep(eat)
dominantHand <- 'f'
otherHand <- 'f'
fmt.Println(phName, "thinking")
rSleep(think)
}
fmt.Println(phName, "satisfied")
done <- true
fmt.Println(phName, "left the table")
}
func main() {
fmt.Println("table empty")
place0 := make(chan fork, 1)
place0 <- 'f'
placeLeft := place0
for i := 1; i < len(ph); i++ {
placeRight := make(chan fork, 1)
placeRight <- 'f'
go philosopher(ph[i], placeLeft, placeRight, done)
placeLeft = placeRight
}
go philosopher(ph[0], place0, placeLeft, done)
for range ph {
<-done
}
fmt.Println("table empty")
}
| package diningphilosophers;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
enum PhilosopherState { Get, Eat, Pon }
class Fork {
public static final int ON_TABLE = -1;
static int instances = 0;
public int id;
public AtomicInteger holder = new AtomicInteger(ON_TABLE);
Fork() { id = instances++; }
}
class Philosopher implements Runnable {
static final int maxWaitMs = 100;
static AtomicInteger token = new AtomicInteger(0);
static int instances = 0;
static Random rand = new Random();
AtomicBoolean end = new AtomicBoolean(false);
int id;
PhilosopherState state = PhilosopherState.Get;
Fork left;
Fork right;
int timesEaten = 0;
Philosopher() {
id = instances++;
left = Main.forks.get(id);
right = Main.forks.get((id+1)%Main.philosopherCount);
}
void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }
catch (InterruptedException ex) {} }
void waitForFork(Fork fork) {
do {
if (fork.holder.get() == Fork.ON_TABLE) {
fork.holder.set(id);
return;
} else {
sleep();
}
} while (true);
}
public void run() {
do {
if (state == PhilosopherState.Pon) {
state = PhilosopherState.Get;
} else {
if (token.get() == id) {
waitForFork(left);
waitForFork(right);
token.set((id+2)% Main.philosopherCount);
state = PhilosopherState.Eat;
timesEaten++;
sleep();
left.holder.set(Fork.ON_TABLE);
right.holder.set(Fork.ON_TABLE);
state = PhilosopherState.Pon;
sleep();
} else {
sleep();
}
}
} while (!end.get());
}
}
public class Main {
static final int philosopherCount = 5;
static final int runSeconds = 15;
static ArrayList<Fork> forks = new ArrayList<Fork>();
static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();
public static void main(String[] args) {
for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());
for (int i = 0 ; i < philosopherCount ; i++)
philosophers.add(new Philosopher());
for (Philosopher p : philosophers) new Thread(p).start();
long endTime = System.currentTimeMillis() + (runSeconds * 1000);
do {
StringBuilder sb = new StringBuilder("|");
for (Philosopher p : philosophers) {
sb.append(p.state.toString());
sb.append("|");
}
sb.append(" |");
for (Fork f : forks) {
int holder = f.holder.get();
sb.append(holder==-1?" ":String.format("P%02d",holder));
sb.append("|");
}
System.out.println(sb.toString());
try {Thread.sleep(1000);} catch (Exception ex) {}
} while (System.currentTimeMillis() < endTime);
for (Philosopher p : philosophers) p.end.set(true);
for (Philosopher p : philosophers)
System.out.printf("P%02d: ate %,d times, %,d/sec\n",
p.id, p.timesEaten, p.timesEaten/runSeconds);
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"hash/fnv"
"log"
"math/rand"
"os"
"time"
)
var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
const hunger = 3
const think = time.Second / 100
const eat = time.Second / 100
var fmt = log.New(os.Stdout, "", 0)
var done = make(chan bool)
type fork byte
func philosopher(phName string,
dominantHand, otherHand chan fork, done chan bool) {
fmt.Println(phName, "seated")
h := fnv.New64a()
h.Write([]byte(phName))
rg := rand.New(rand.NewSource(int64(h.Sum64())))
rSleep := func(t time.Duration) {
time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))
}
for h := hunger; h > 0; h-- {
fmt.Println(phName, "hungry")
<-dominantHand
<-otherHand
fmt.Println(phName, "eating")
rSleep(eat)
dominantHand <- 'f'
otherHand <- 'f'
fmt.Println(phName, "thinking")
rSleep(think)
}
fmt.Println(phName, "satisfied")
done <- true
fmt.Println(phName, "left the table")
}
func main() {
fmt.Println("table empty")
place0 := make(chan fork, 1)
place0 <- 'f'
placeLeft := place0
for i := 1; i < len(ph); i++ {
placeRight := make(chan fork, 1)
placeRight <- 'f'
go philosopher(ph[i], placeLeft, placeRight, done)
placeLeft = placeRight
}
go philosopher(ph[0], place0, placeLeft, done)
for range ph {
<-done
}
fmt.Println("table empty")
}
| package diningphilosophers;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
enum PhilosopherState { Get, Eat, Pon }
class Fork {
public static final int ON_TABLE = -1;
static int instances = 0;
public int id;
public AtomicInteger holder = new AtomicInteger(ON_TABLE);
Fork() { id = instances++; }
}
class Philosopher implements Runnable {
static final int maxWaitMs = 100;
static AtomicInteger token = new AtomicInteger(0);
static int instances = 0;
static Random rand = new Random();
AtomicBoolean end = new AtomicBoolean(false);
int id;
PhilosopherState state = PhilosopherState.Get;
Fork left;
Fork right;
int timesEaten = 0;
Philosopher() {
id = instances++;
left = Main.forks.get(id);
right = Main.forks.get((id+1)%Main.philosopherCount);
}
void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }
catch (InterruptedException ex) {} }
void waitForFork(Fork fork) {
do {
if (fork.holder.get() == Fork.ON_TABLE) {
fork.holder.set(id);
return;
} else {
sleep();
}
} while (true);
}
public void run() {
do {
if (state == PhilosopherState.Pon) {
state = PhilosopherState.Get;
} else {
if (token.get() == id) {
waitForFork(left);
waitForFork(right);
token.set((id+2)% Main.philosopherCount);
state = PhilosopherState.Eat;
timesEaten++;
sleep();
left.holder.set(Fork.ON_TABLE);
right.holder.set(Fork.ON_TABLE);
state = PhilosopherState.Pon;
sleep();
} else {
sleep();
}
}
} while (!end.get());
}
}
public class Main {
static final int philosopherCount = 5;
static final int runSeconds = 15;
static ArrayList<Fork> forks = new ArrayList<Fork>();
static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();
public static void main(String[] args) {
for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());
for (int i = 0 ; i < philosopherCount ; i++)
philosophers.add(new Philosopher());
for (Philosopher p : philosophers) new Thread(p).start();
long endTime = System.currentTimeMillis() + (runSeconds * 1000);
do {
StringBuilder sb = new StringBuilder("|");
for (Philosopher p : philosophers) {
sb.append(p.state.toString());
sb.append("|");
}
sb.append(" |");
for (Fork f : forks) {
int holder = f.holder.get();
sb.append(holder==-1?" ":String.format("P%02d",holder));
sb.append("|");
}
System.out.println(sb.toString());
try {Thread.sleep(1000);} catch (Exception ex) {}
} while (System.currentTimeMillis() < endTime);
for (Philosopher p : philosophers) p.end.set(true);
for (Philosopher p : philosophers)
System.out.printf("P%02d: ate %,d times, %,d/sec\n",
p.id, p.timesEaten, p.timesEaten/runSeconds);
}
}
|
Change the following Go code into Java without altering its purpose. | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
| public class Factorion {
public static void main(String [] args){
System.out.println("Base 9:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,9);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 10:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,10);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 11:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,11);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 12:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,12);
if(multiplied == i){
System.out.print(i + "\t");
}
}
}
public static int factorialRec(int n){
int result = 1;
return n == 0 ? result : result * n * factorialRec(n-1);
}
public static int operate(String s, int base){
int sum = 0;
String strx = fromDeci(base, Integer.parseInt(s));
for(int i = 0; i < strx.length(); i++){
if(strx.charAt(i) == 'A'){
sum += factorialRec(10);
}else if(strx.charAt(i) == 'B') {
sum += factorialRec(11);
}else if(strx.charAt(i) == 'C') {
sum += factorialRec(12);
}else {
sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
}
}
return sum;
}
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
static String fromDeci(int base, int num){
StringBuilder s = new StringBuilder();
while (num > 0) {
s.append(reVal(num % base));
num /= base;
}
return new String(new StringBuilder(s).reverse());
}
}
|
Keep all operations the same but rewrite the snippet in Java. | package main
import (
"fmt"
"strconv"
)
func main() {
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
}
| public class Factorion {
public static void main(String [] args){
System.out.println("Base 9:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,9);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 10:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,10);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 11:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,11);
if(multiplied == i){
System.out.print(i + "\t");
}
}
System.out.println("\nBase 12:");
for(int i = 1; i <= 1499999; i++){
String iStri = String.valueOf(i);
int multiplied = operate(iStri,12);
if(multiplied == i){
System.out.print(i + "\t");
}
}
}
public static int factorialRec(int n){
int result = 1;
return n == 0 ? result : result * n * factorialRec(n-1);
}
public static int operate(String s, int base){
int sum = 0;
String strx = fromDeci(base, Integer.parseInt(s));
for(int i = 0; i < strx.length(); i++){
if(strx.charAt(i) == 'A'){
sum += factorialRec(10);
}else if(strx.charAt(i) == 'B') {
sum += factorialRec(11);
}else if(strx.charAt(i) == 'C') {
sum += factorialRec(12);
}else {
sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
}
}
return sum;
}
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char)(num + 48);
else
return (char)(num - 10 + 65);
}
static String fromDeci(int base, int num){
StringBuilder s = new StringBuilder();
while (num > 0) {
s.append(reVal(num % base));
num /= base;
}
return new String(new StringBuilder(s).reverse());
}
}
|
Rewrite the snippet below in Java so it works the same as the original Go code. | package main
import (
"fmt"
"github.com/maorshutman/lm"
"log"
"math"
)
const (
K = 7_800_000_000
n0 = 27
)
var y = []float64{
27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60,
61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023,
2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615,
24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177,
60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723,
76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365,
85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133,
105824, 109695, 114232, 118610, 125497, 133852, 143227,
151367, 167418, 180096, 194836, 213150, 242364, 271106,
305117, 338133, 377918, 416845, 468049, 527767, 591704,
656866, 715353, 777796, 851308, 928436, 1000249, 1082054,
1174652,
}
func f(dst, p []float64) {
for i := 0; i < len(y); i++ {
t := float64(i)
dst[i] = (n0*math.Exp(p[0]*t))/(1+n0*(math.Exp(p[0]*t)-1)/K) - y[i]
}
}
func main() {
j := lm.NumJac{Func: f}
prob := lm.LMProblem{
Dim: 1,
Size: len(y),
Func: f,
Jac: j.Jac,
InitParams: []float64{0.5},
Tau: 1e-6,
Eps1: 1e-8,
Eps2: 1e-8,
}
res, err := lm.LM(prob, &lm.Settings{Iterations: 100, ObjectiveTol: 1e-16})
if err != nil {
log.Fatal(err)
}
r := res.X[0]
fmt.Printf("The logistic curve r for the world data is %.8f\n", r)
fmt.Printf("R0 is then approximately equal to %.7f\n", math.Exp(12*r))
}
| import java.util.List;
import java.util.function.Function;
public class LogisticCurveFitting {
private static final double K = 7.8e9;
private static final int N0 = 27;
private static final List<Double> ACTUAL = List.of(
27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0,
61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0,
4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0,
31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0,
69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0,
80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0,
95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0,
133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0,
271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0,
656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0
);
private static double f(double r) {
var sq = 0.0;
var len = ACTUAL.size();
for (int i = 0; i < len; i++) {
var eri = Math.exp(r * i);
var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K);
var diff = guess - ACTUAL.get(i);
sq += diff * diff;
}
return sq;
}
private static double solve(Function<Double, Double> fn) {
return solve(fn, 0.5, 0.0);
}
private static double solve(Function<Double, Double> fn, double guess, double epsilon) {
double delta;
if (guess != 0.0) {
delta = guess;
} else {
delta = 1.0;
}
var f0 = fn.apply(guess);
var factor = 2.0;
while (delta > epsilon && guess != guess - delta) {
var nf = fn.apply(guess - delta);
if (nf < f0) {
f0 = nf;
guess -= delta;
} else {
nf = fn.apply(guess + delta);
if (nf < f0) {
f0 = nf;
guess += delta;
} else {
factor = 0.5;
}
}
delta *= factor;
}
return guess;
}
public static void main(String[] args) {
var r = solve(LogisticCurveFitting::f);
var r0 = Math.exp(12.0 * r);
System.out.printf("r = %.16f, R0 = %.16f\n", r, r0);
}
}
|
Generate an equivalent Java version of this Go code. | package main
import "fmt"
type link struct {
int
next *link
}
func linkInts(s []int) *link {
if len(s) == 0 {
return nil
}
return &link{s[0], linkInts(s[1:])}
}
func (l *link) String() string {
if l == nil {
return "nil"
}
r := fmt.Sprintf("[%d", l.int)
for l = l.next; l != nil; l = l.next {
r = fmt.Sprintf("%s %d", r, l.int)
}
return r + "]"
}
func main() {
a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66})
fmt.Println("before:", a)
b := strandSort(a)
fmt.Println("after: ", b)
}
func strandSort(a *link) (result *link) {
for a != nil {
sublist := a
a = a.next
sTail := sublist
for p, pPrev := a, a; p != nil; p = p.next {
if p.int > sTail.int {
sTail.next = p
sTail = p
if p == a {
a = p.next
} else {
pPrev.next = p.next
}
} else {
pPrev = p
}
}
sTail.next = nil
if result == nil {
result = sublist
continue
}
var m, rr *link
if sublist.int < result.int {
m = sublist
sublist = m.next
rr = result
} else {
m = result
rr = m.next
}
result = m
for {
if sublist == nil {
m.next = rr
break
}
if rr == nil {
m.next = sublist
break
}
if sublist.int < rr.int {
m.next = sublist
m = sublist
sublist = m.next
} else {
m.next = rr
m = rr
rr = m.next
}
}
}
return
}
| import java.util.Arrays;
import java.util.LinkedList;
public class Strand{
public static <E extends Comparable<? super E>>
LinkedList<E> strandSort(LinkedList<E> list){
if(list.size() <= 1) return list;
LinkedList<E> result = new LinkedList<E>();
while(list.size() > 0){
LinkedList<E> sorted = new LinkedList<E>();
sorted.add(list.removeFirst());
for(Iterator<E> it = list.iterator(); it.hasNext(); ){
E elem = it.next();
if(sorted.peekLast().compareTo(elem) <= 0){
sorted.addLast(elem);
it.remove();
}
}
result = merge(sorted, result);
}
return result;
}
private static <E extends Comparable<? super E>>
LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){
LinkedList<E> result = new LinkedList<E>();
while(!left.isEmpty() && !right.isEmpty()){
if(left.peek().compareTo(right.peek()) <= 0)
result.add(left.remove());
else
result.add(right.remove());
}
result.addAll(left);
result.addAll(right);
return result;
}
public static void main(String[] args){
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));
System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));
}
}
|
Preserve the algorithm and functionality while converting the code from Go to Java. | package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func sumDigits(n int) int {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func main() {
fmt.Println("Additive primes less than 500:")
i := 2
count := 0
for {
if isPrime(i) && isPrime(sumDigits(i)) {
count++
fmt.Printf("%3d ", i)
if count%10 == 0 {
fmt.Println()
}
}
if i > 2 {
i += 2
} else {
i++
}
if i > 499 {
break
}
}
fmt.Printf("\n\n%d additive primes found.\n", count)
}
| public class additivePrimes {
public static void main(String[] args) {
int additive_primes = 0;
for (int i = 2; i < 500; i++) {
if(isPrime(i) && isPrime(digitSum(i))){
additive_primes++;
System.out.print(i + " ");
}
}
System.out.print("\nFound " + additive_primes + " additive primes less than 500");
}
static boolean isPrime(int n) {
int counter = 1;
if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {
return false;
}
while (counter * 6 - 1 <= Math.sqrt(n)) {
if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {
return false;
} else {
counter++;
}
}
return true;
}
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
|
Convert the following code from Go to Java, ensuring the logic remains intact. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Integer> perfectTotient(int n) {
int test = 2;
List<Integer> results = new ArrayList<Integer>();
for ( int i = 0 ; i < n ; test++ ) {
int phiLoop = test;
int sum = 0;
do {
phiLoop = phi[phiLoop];
sum += phiLoop;
} while ( phiLoop > 1);
if ( sum == test ) {
i++;
results.add(test);
}
}
return results;
}
private static final int max = 100000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
}
|
Convert this Go block to Java, preserving its control flow and logic. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Integer> perfectTotient(int n) {
int test = 2;
List<Integer> results = new ArrayList<Integer>();
for ( int i = 0 ; i < n ; test++ ) {
int phiLoop = test;
int sum = 0;
do {
phiLoop = phi[phiLoop];
sum += phiLoop;
} while ( phiLoop > 1);
if ( sum == test ) {
i++;
results.add(test);
}
}
return results;
}
private static final int max = 100000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
}
|
Produce a language-to-language conversion: from Go to Java, same semantics. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}
| import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Integer> perfectTotient(int n) {
int test = 2;
List<Integer> results = new ArrayList<Integer>();
for ( int i = 0 ; i < n ; test++ ) {
int phiLoop = test;
int sum = 0;
do {
phiLoop = phi[phiLoop];
sum += phiLoop;
} while ( phiLoop > 1);
if ( sum == test ) {
i++;
results.add(test);
}
}
return results;
}
private static final int max = 100000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
type Delegator struct {
delegate interface{}
}
type Thingable interface {
thing() string
}
func (self Delegator) operation() string {
if v, ok := self.delegate.(Thingable); ok {
return v.thing()
}
return "default implementation"
}
type Delegate int
func (Delegate) thing() string {
return "delegate implementation"
}
func main() {
a := Delegator{}
fmt.Println(a.operation())
a.delegate = "A delegate may be any object"
fmt.Println(a.operation())
var d Delegate
a.delegate = d
fmt.Println(a.operation())
}
| interface Thingable {
String thing();
}
class Delegator {
public Thingable delegate;
public String operation() {
if (delegate == null)
return "default implementation";
else
return delegate.thing();
}
}
class Delegate implements Thingable {
public String thing() {
return "delegate implementation";
}
}
public class DelegateExample {
public static void main(String[] args) {
Delegator a = new Delegator();
assert a.operation().equals("default implementation");
Delegate d = new Delegate();
a.delegate = d;
assert a.operation().equals("delegate implementation");
a.delegate = new Thingable() {
public String thing() {
return "anonymous delegate implementation";
}
};
assert a.operation().equals("anonymous delegate implementation");
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
| public class DivisorSum {
private static long divisorSum(long n) {
var total = 1L;
var power = 2L;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (long p = 3; p * p <= n; p += 2) {
long sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%4d", divisorSum(n));
if (n % 10 == 0) {
System.out.println();
}
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import "fmt"
func sumDivisors(n int) int {
sum := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
sum += i
j := n / i
if j != i {
sum += j
}
}
i += k
}
return sum
}
func main() {
fmt.Println("The sums of positive divisors for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%3d ", sumDivisors(i))
if i%10 == 0 {
fmt.Println()
}
}
}
| public class DivisorSum {
private static long divisorSum(long n) {
var total = 1L;
var power = 2L;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (long p = 3; p * p <= n; p += 2) {
long sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
for (long n = 1; n <= limit; ++n) {
System.out.printf("%4d", divisorSum(n));
if (n % 10 == 0) {
System.out.println();
}
}
}
}
|
Please provide an equivalent version of this Go code in Java. | package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
| import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Produce a functionally identical Java code for the snippet given in Go. | package main
import (
"fmt"
"strings"
)
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " +
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " +
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " +
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " +
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " +
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up "
func validate(commands, words []string, minLens []int) []string {
results := make([]string, 0)
if len(words) == 0 {
return results
}
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func main() {
table = strings.TrimSpace(table)
commands := strings.Fields(table)
clen := len(commands)
minLens := make([]int, clen)
for i := 0; i < clen; i++ {
count := 0
for _, c := range commands[i] {
if c >= 'A' && c <= 'Z' {
count++
}
}
minLens[i] = count
}
sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin"
words := strings.Fields(sentence)
results := validate(commands, words, minLens)
fmt.Print("user words: ")
for j := 0; j < len(words); j++ {
fmt.Printf("%-*s ", len(results[j]), words[j])
}
fmt.Print("\nfull words: ")
fmt.Println(strings.Join(results, " "))
}
| import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) {
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false;
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) {
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.