Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into Mathematica but keep the logic exactly as in PHP.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
varname = InputString["Enter a variable name"]; varvalue = InputString["Enter a value"]; ReleaseHold[ Hold[Set["nameholder", "value"]] /. {"nameholder" -> Symbol[varname], "value" -> varvalue}]; Print[varname, " is now set to ", Symbol[varname]]
Port the following code from PHP to Mathematica with equivalent syntax and logic.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
Input source code is "10 x" , X is locally bound to 3 & 2 and the resulting expressions evaluated. (10 x /. x -> 3 ) - (10 x /. x -> 2 ) -> 10
Translate the given PHP code snippet into Mathematica without altering its behavior.
<?php function eval_with_x($code, $a, $b) { $x = $a; $first = eval($code); $x = $b; $second = eval($code); return $second - $first; } echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15". ?>
Input source code is "10 x" , X is locally bound to 3 & 2 and the resulting expressions evaluated. (10 x /. x -> 3 ) - (10 x /. x -> 2 ) -> 10
Port the following code from PHP to Mathematica with equivalent syntax and logic.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Print[ToExpression["1 + 1"]]; Print[ToExpression["Print[\"Hello, world!\"]; 10!"]]; x = 5; Print[ToExpression["x!"]]; Print[ToExpression["Module[{x = 8}, x!]"]]; Print[MemoryConstrained[ToExpression["Range[5]"], 10000, {}]]; Print[MemoryConstrained[ToExpression["Range[10^5]"], 10000, {}]]; Print[TimeConstrained[ToExpre...
Convert this PHP block to Mathematica, preserving its control flow and logic.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
Print[ToExpression["1 + 1"]]; Print[ToExpression["Print[\"Hello, world!\"]; 10!"]]; x = 5; Print[ToExpression["x!"]]; Print[ToExpression["Module[{x = 8}, x!]"]]; Print[MemoryConstrained[ToExpression["Range[5]"], 10000, {}]]; Print[MemoryConstrained[ToExpression["Range[10^5]"], 10000, {}]]; Print[TimeConstrained[ToExpre...
Generate a Mathematica translation of this PHP snippet without changing its computational steps.
function getitem($s,$depth=0) { $out = ['']; while ($s) { $c = $s[0]; if ($depth && ($c == ',' || $c == '}')) { return [$out, $s]; } if ($c == '{') { $x = getgroup(substr($s, 1), $depth + 1); if($x) { $tmp = []; ...
EscapeToken="\\"; LeftBraceToken="{"; RightBraceToken="}"; CaptureEscapes[exp:{___String}]:=SequenceReplace[exp,{EscapeToken,x_}:>EscapeToken<>x]; CaptureBraces[exp:{___String}]:=ReplaceAll[exp,{LeftBraceToken->LeftBrace,RightBraceToken->RightBrace}]; CaptureBraceTrees[exp:{(_String|LeftBrace|RightBrace)...}]:...
Translate the given PHP code snippet into Mathematica without altering its behavior.
$img = imagegrabscreen(); $color = imagecolorat($im, 10, 50); imagedestroy($im);
getPixel[{x_?NumberQ, y_?NumberQ}, screenNumber_Integer: 1] := ImageValue[CurrentScreenImage[n], {x, y}]
Please provide an equivalent version of this PHP code in Mathematica.
<?php $client = new SoapClient("http://example.com/soap/definition.wsdl"); $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234); $client = new SoapClient("http://example.com/soap/definition.wsdl"); print_r($client->__getTypes()); print_r($client->__getFunctions()); ?>
InstallService["http://example.com/soap/wsdl"]; soapFunc["Hello"]; anotherSoapFunc[12345];
Port the provided PHP code into Mathematica while preserving the original functionality.
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList();...
StrandSort[ input_ ] := Module[ {results = {}, A = input}, While[Length@A > 0, sublist = {A[[1]]}; A = A[[2;;All]]; For[i = 1, i < Length@A, i++, If[ A[[i]] > Last@sublist, AppendTo[sublist, A[[i]]]; A = Delete[A, i];] ]; results = #[[Ordering@#]]&@Join[sublist, results];]; results ] StrandSort[{2, 3, 7, 5, 1...
Generate a Mathematica translation of this PHP snippet without changing its computational steps.
<?php $doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>'); $xpath = new DOMXPath($doc); $nodelist = $xpath->query('//item'); $result = $nodelist->item(0); $nodelist = $xpath->query('//price'); for($i = 0; $i < $nodelist->length; $i++) { print $doc->saveXML($nodelist->item($i...
example = Import["test.txt", "XML"]; Cases[example, XMLElement["item", _ , _] , Infinity] // First Cases[example, XMLElement["price", _, List[n_]] -> n, Infinity] // Column Cases[example, XMLElement["name", _, List[n_]] -> n, Infinity] // Column
Port the following code from PHP to Mathematica with equivalent syntax and logic.
<?php class Example { function foo() { echo "this is foo\n"; } function bar() { echo "this is bar\n"; } function __call($name, $args) { echo "tried to handle unknown method $name\n"; if ($args) echo "it had arguments: ", implode(', ', $args), "\n"; } } $example = new Example(); $exam...
obj[foo] = "This is foo."; obj[bar] = "This is bar."; obj[f_Symbol] := "What is " <> SymbolName[f] <> "?"; Print[obj@foo]; Print[obj@bar]; Print[obj@baz];
Write the same code in Mathematica as shown below in PHP.
<?php function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return fal...
MersennePrimeExponent /@ Range[40]
Generate a Mathematica translation of this PHP snippet without changing its computational steps.
<?php function is_prime($n) { if ($n <= 3) { return $n > 1; } elseif (($n % 2 == 0) or ($n % 3 == 0)) { return false; } $i = 5; while ($i * $i <= $n) { if ($n % $i == 0) { return false; } $i += 2; if ($n % $i == 0) { return fal...
MersennePrimeExponent /@ Range[40]
Convert the following code from PHP to Mathematica, ensuring the logic remains intact.
<?php function hashJoin($table1, $index1, $table2, $index2) { foreach ($table1 as $s) $h[$s[$index1]][] = $s; foreach ($table2 as $r) foreach ($h[$r[$index2]] as $s) $result[] = array($s, $r); return $result; } $table1 = array(array(27, "Jonah"), array(18, "Alan"), ...
hashJoin[table1_List,table1colindex_Integer,table2_List,table2colindex_Integer]:=Module[{h,f,t1,t2,tmp}, t1=If[table1colindex != 1,table1[[All,Prepend[Delete[Range@Length@table1[[1]],table1colindex],table1colindex]]],table1]; t2=If[table2colindex != 1, table2[[All,Prepend[Delete[Range@Length@table2[[1]],table2colindex]...
Convert the following code from PHP to Mathematica, ensuring the logic remains intact.
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array...
Tuples[{1, 2, 3}, 2]
Rewrite this program in Mathematica while keeping its functionality equivalent to the PHP version.
<?php function permutate($values, $size, $offset) { $count = count($values); $array = array(); for ($i = 0; $i < $size; $i++) { $selector = ($offset / pow($count,$i)) % $count; $array[$i] = $values[$selector]; } return $array; } function permutations($values, $size) { $a = array...
Tuples[{1, 2, 3}, 2]
Rewrite the snippet below in Mathematica so it works the same as the original PHP code.
<?php <?php $mac_use_espeak = false; $voice = "espeak"; $statement = 'Hello World!'; $save_file_args = '-w HelloWorld.wav'; // eSpeak args $OS = strtoupper(substr(PHP_OS, 0, 3)); elseif($OS === 'DAR' && $mac_use_espeak == false) { $voice = "say -v 'Victoria'"; $save_file_args = '-o HelloWorl...
Speak["This is an example of speech synthesis."]
Port the following code from PHP to Mathematica with equivalent syntax and logic.
<?php define('MINEGRID_WIDTH', 6); define('MINEGRID_HEIGHT', 4); define('MINESWEEPER_NOT_EXPLORED', -1); define('MINESWEEPER_MINE', -2); define('MINESWEEPER_FLAGGED', -3); define('MINESWEEPER_FLAGGED_MINE', -4); define('ACTIVATED_MINE', -5); function check_field($field) { if ($field === MI...
DynamicModule[{m = 6, n = 4, minecount, grid, win, reset, clear, checkwin}, reset[] := Module[{minesdata, adjacentmines}, minecount = RandomInteger[Round[{.1, .2} m*n]]; minesdata = Normal@SparseArray[# -> 1 & /@ RandomSample[Tuples[Range /@ {m, n}], minecount], {m, n}]; adjacentmines = ...
Transform the following PHP implementation into Mathematica, maintaining the same output and logic.
function RGBtoHSV($r, $g, $b) { $r = $r/255.; // convert to range 0..1 $g = $g/255.; $b = $b/255.; $cols = array("r" => $r, "g" => $g, "b" => $b); asort($cols, SORT_NUMERIC); $min = key(array_slice($cols, 1)); // "r", "g" or "b" $max = key(array_slice($cols, -1)); // "r", "g" or "b" if($cols[$min] == $cols[$m...
Export["out.bmp", EdgeDetect[Import[InputString[]]]];
Convert the following code from PHP to Mathematica, ensuring the logic remains intact.
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled t...
TextCases[" this URI contains an illegal character, parentheses and a misplaced full stop: http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/). and another one just to confuse the parser: http://en.wikipedia.org/wiki/-) \")\" is handled the wrong way by the me...
Can you help me rewrite this code in Mathematica instead of PHP, keeping it the same logically?
$tests = array( 'this URI contains an illegal character, parentheses and a misplaced full stop:', 'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).', 'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)', '")" is handled t...
TextCases[" this URI contains an illegal character, parentheses and a misplaced full stop: http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/). and another one just to confuse the parser: http://en.wikipedia.org/wiki/-) \")\" is handled the wrong way by the me...
Preserve the algorithm and functionality while converting the code from PHP to Mathematica.
<?php class PeriodicTable { private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104); private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7); public function rowAndColumn($n) { $i = 7; while ($this->aArray[$i] > $n) $i--; $m = $n + $this->bArray[$i]; ...
ClearAll[FindPeriodGroup] FindPeriodGroup[n_Integer] := Which[57 <= n <= 70, {8, n - 53} , 89 <= n <= 102, {9, n - 85} , 1 <= n <= 118, {ElementData[n, "Period"], ElementData[n, "Group"]} , True, Missing["Element does not exist"] ] Row[{"Element ", #, " -> ", FindPeriodGroup[#]}] & /@ {1, 2, 29, 42,...
Produce a language-to-language conversion: from PHP to Mathematica, same semantics.
function connect_db($database, $db_user, $db_password, $host = 'localhost', $port = NULL, $die = false) { if(!$db_handle = @mysql_connect($host.($port ? ':'.$port : ''), $db_user, $db_password)) { if($die) die("Can't connect to MySQL server:\r\n".mysql_error()); else return false; } if(!@mysql_select_...
Needs["DatabaseLink`"]; connectDb[dbUser_, dbPass_, dbUrl_] := OpenSQLConnection[JDBC["mysql", dbUrl], "Username" -> dbUser, "Password" -> dbPass]; createUser::nameTaken = "The username '`1`' is already taken."; createUser[dbUser_, dbPass_, dbUrl_, user_, pass_] := Module[{db = connectDb[dbUser, dbPass, dbUrl...
Rewrite the snippet below in Groovy so it works the same as the original Java code.
module OptionalParameters { typedef Type<String >.Orderer as ColumnOrderer; typedef Type<String[]>.Orderer as RowOrderer; static String[][] sort(String[][] table, ColumnOrderer? orderer = Null, Int column = 0, ...
def orderedSort(Collection table, column = 0, reverse = false, ordering = {x, y -> x <=> y } as Comparator) { table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])} }
Write the same algorithm in Groovy as shown in this Java implementation.
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; public class SelfReferentialSequence { static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000); public static void main(String[] args) { Seeds res = IntStream.range(0, 1000_000) ...
Number.metaClass.getSelfReferentialSequence = { def number = delegate as String; def sequence = [] while (!sequence.contains(number)) { sequence << number def encoded = new StringBuilder() ((number as List).sort().join('').reverse() =~ /(([0-9])\2*)/).each { matcher, text, digit -> encoded.append...
Transform the following Java implementation into Groovy, maintaining the same output and logic.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
println ''' Time's a strange fellow; more he gives than takes (and he takes all) nor any marvel finds quite disappearance but some keener makes losing, gaining --love! if a world ends '''
Rewrite the snippet below in Groovy so it works the same as the original Java code.
package rosettacode.heredoc; public class MainApp { public static void main(String[] args) { String hereDoc = """ This is a multiline string. It includes all of this text, but on separate lines in the code. """; System.out.println(hereDoc); } }
println ''' Time's a strange fellow; more he gives than takes (and he takes all) nor any marvel finds quite disappearance but some keener makes losing, gaining --love! if a world ends '''
Convert this Java snippet to Groovy and keep its semantics consistent.
class MD5 { private static final int INIT_A = 0x67452301; private static final int INIT_B = (int)0xEFCDAB89L; private static final int INIT_C = (int)0x98BADCFEL; private static final int INIT_D = 0x10325476; private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23,...
class MD5 { private static final int INIT_A = 0x67452301 private static final int INIT_B = (int)0xEFCDAB89L private static final int INIT_C = (int)0x98BADCFEL private static final int INIT_D = 0x10325476 private static final int[] SHIFT_AMTS = [ 7, 12, 17, 22, 5, 9, 14, 20...
Generate a Groovy translation of this Java snippet without changing its computational steps.
module MultiplyExample { static <Value extends Number> Value multiply(Value n1, Value n2) { return n1 * n2; } void run() { (Int i1, Int i2) = (7, 3); Int i3 = multiply(i1, i2); (Double d1, Double d2) = (2.7182818, 3.1415); Double d3 = multiply...
def multiply = { x, y -> x * y }
Write the same algorithm in Groovy as shown in this Java implementation.
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String...
@Grab(group='commons-net', module='commons-net', version='2.0') import org.apache.commons.net.ftp.FTPClient println("About to connect...."); new FTPClient().with { connect "ftp.easynet.fr" enterLocalPassiveMode() login "anonymous", "ftptest@example.com" changeWorkingDirectory "/debian/" def inc...
Port the provided Java code into Groovy while preserving the original functionality.
import java.util.Arrays; public class CycleSort { public static void main(String[] args) { int[] arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1}; System.out.println(Arrays.toString(arr)); int writes = cycleSort(arr); System.out.println(Arrays.toString(arr)); System...
class CycleSort { static void main(String[] args) { int[] arr = [5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1] println(Arrays.toString(arr)) int writes = cycleSort(arr) println(Arrays.toString(arr)) println("writes: " + writes) } static int cycleSort(int[] a) { ...
Maintain the same structure and functionality when rewriting this code in Groovy.
import java.util.Arrays; public class CycleSort { public static void main(String[] args) { int[] arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1}; System.out.println(Arrays.toString(arr)); int writes = cycleSort(arr); System.out.println(Arrays.toString(arr)); System...
class CycleSort { static void main(String[] args) { int[] arr = [5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1] println(Arrays.toString(arr)) int writes = cycleSort(arr) println(Arrays.toString(arr)) println("writes: " + writes) } static int cycleSort(int[] a) { ...
Transform the following Java implementation into Groovy, maintaining the same output and logic.
import java.math.BigInteger; import java.util.List; public class Brazilian { private static final List<Integer> primeList = List.of( 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 16...
import org.codehaus.groovy.GroovyBugError class Brazilian { private static final List<Integer> primeList = new ArrayList<>(Arrays.asList( 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,...
Preserve the algorithm and functionality while converting the code from Java to Groovy.
import java.math.BigInteger; import java.util.List; public class Brazilian { private static final List<Integer> primeList = List.of( 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 16...
import org.codehaus.groovy.GroovyBugError class Brazilian { private static final List<Integer> primeList = new ArrayList<>(Arrays.asList( 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,...
Write the same algorithm in Groovy as shown in this Java implementation.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; public class CreateFile { public static void main(String[] args) throws IOException { String os = System.getProperty("os.name"); if (os.contains("Windows")) {...
import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths class CreateFile { static void main(String[] args) throws IOException { String os = System.getProperty("os.name") if (os.contains("Windows")) { Path path = Paths.get("tape.file") Files.write(path...
Produce a functionally identical Groovy code for the snippet given in Java.
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return...
def Y = { le -> ({ f -> f(f) })({ f -> le { x -> f(f)(x) } }) } def factorial = Y { fac -> { n -> n <= 2 ? n : n * fac(n - 1) } } assert 2432902008176640000 == factorial(20G) def fib = Y { fibStar -> { n -> n <= 1 ? n : fibStar(n - 1) + fibStar(n - 2) } } assert fib(10) == 55
Write a version of this Java function in Groovy with identical behavior.
public class BeadSort { public static void main(String[] args) { BeadSort now=new BeadSort(); int[] arr=new int[(int)(Math.random()*11)+5]; for(int i=0;i<arr.length;i++) arr[i]=(int)(Math.random()*10); System.out.print("Unsorted: "); now.display1D(arr); int[] sort=now.beadSort(arr); System.out.pr...
def beadSort = { list -> final nPoles = list.max() list.collect { print "." ([true] * it) + ([false] * (nPoles - it)) }.transpose().collect { pole -> print "." pole.findAll { ! it } + pole.findAll { it } }.transpose().collect{ beadTally -> beadTally.findAll{ it }....
Write the same algorithm in Groovy as shown in this Java implementation.
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { mem...
class BrainfuckProgram { def program = '', memory = [:] def instructionPointer = 0, dataPointer = 0 def execute() { while (instructionPointer < program.size()) switch(program[instructionPointer++]) { case '>': dataPointer++; break; case '<': dataPointer--; break...
Can you help me rewrite this code in Groovy instead of Java, keeping it the same logically?
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { mem...
class BrainfuckProgram { def program = '', memory = [:] def instructionPointer = 0, dataPointer = 0 def execute() { while (instructionPointer < program.size()) switch(program[instructionPointer++]) { case '>': dataPointer++; break; case '<': dataPointer--; break...
Ensure the translated Groovy code behaves exactly like the original Java snippet.
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
import groovy.transform.TupleConstructor enum Pip { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } enum Suit { DIAMONDS, SPADES, HEARTS, CLUBS } @TupleConstructor class Card { final Pip pip final Suit suit String toString() { "$pip of $suit" } } class Deck { p...
Maintain the same structure and functionality when rewriting this code in Groovy.
import java.util.*; public class CocktailSort { public static void main(String[] args) { Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 }; System.out.println("before: " + Arrays.toString(array)); cocktailSort(array); System.out.println("after: " + Arrays.toString(...
class CocktailSort { static void main(String[] args) { Integer[] array = [ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 ] println("before: " + Arrays.toString(array)) cocktailSort(array) println("after: " + Arrays.toString(array)) } static void cocktailSort(Object[] array) { ...
Write the same algorithm in Groovy as shown in this Java implementation.
import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class PermutationSort { public static void main(String[] args) { int[] a={3,2,1,8,9,4,6}; System.out.println("Unsorted: " + Arrays.toString(a)); a=pSort(a); System.out.println("Sorted: " + Arrays.toString(a)); } public stat...
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 } def makePermutation; makePermutation = { list, i -> def n = list.size() if (n < 2) return list def fact = factorial(n-1) assert i < fact*n def index = i.intdiv(fact) [list[index]] + makePermutation(list[0..<index] + list[...
Convert the following code from Java to Groovy, ensuring the logic remains intact.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
class ScriptedMain { static def meaningOfLife = 42 static main(args) { println "Main: The meaning of life is " + meaningOfLife } }
Port the following code from Java to Groovy with equivalent syntax and logic.
public class ScriptedMain { public static int meaningOfLife() { return 42; } public static void main(String[] args) { System.out.println("Main: The meaning of life is " + meaningOfLife()); } }
class ScriptedMain { static def meaningOfLife = 42 static main(args) { println "Main: The meaning of life is " + meaningOfLife } }
Change the programming language of this snippet from Java to Groovy without modifying what it does.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31...
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } } def date = Date.&parse.curry('yyyy-MM-dd') def month = { it.format('MM') } def days = { year -> (date("${year}-01-01")..<date("${year+1}-01-01")) } def weekDays = { dayOfWeek, year -> days(year).findAll {...
Translate this program into Groovy but keep the logic exactly as in Java.
import java.util.Scanner; public class LastSunday { static final String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; public static int[] findLastSunday(int year) { boolean isLeap = isLeapYear(year); int[] days={31,isLeap?29:28,31...
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } } def date = Date.&parse.curry('yyyy-MM-dd') def month = { it.format('MM') } def days = { year -> (date("${year}-01-01")..<date("${year+1}-01-01")) } def weekDays = { dayOfWeek, year -> days(year).findAll {...
Please provide an equivalent version of this Java code in Groovy.
public class Sparkline { String bars="▁▂▃▄▅▆▇█"; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; ...
def sparkline(List<Number> list) { def (min, max) = [list.min(), list.max()] def div = (max - min) / 7 list.collect { (char)(0x2581 + (it-min) * div) }.join() } def sparkline(String text) { sparkline(text.split(/[ ,]+/).collect { it as Double }) }
Translate the given Java code snippet into Groovy without altering its behavior.
public static void main(String... args){ HashMap<String, Integer> vars = new HashMap<String, Integer>(); vars.put("Variable name", 3); vars.put("Next variable name", 5); Scanner sc = new Scanner(System.in); String str = sc.next(); vars.put(str,...
def varname = 'foo' def value = 42 new GroovyShell(this.binding).evaluate("${varname} = ${value}") assert foo == 42
Write a version of this Java function in Groovy with identical behavior.
import java.util.Arrays; import java.util.Comparator; public class RJSortStability { public static void main(String[] args) { String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", }; String[] cn = cityList.clone(); System.out.println("\nBefore sort:"); for (String ...
def cityList = ['UK London', 'US New York', 'US Birmingham', 'UK Birmingham',].asImmutable() [ 'Sort by city': { city -> city[4..-1] }, 'Sort by country': { city -> city[0..3] }, ].each{ String label, Closure orderBy -> println "\n\nBefore ${label}" cityList.each { println it } println "\nAfter ...
Can you help me rewrite this code in Groovy instead of Java, keeping it the same logically?
public static void main(String[] args) { System.out.println(concat("Rosetta", "Code", ":")); } public static String concat(String a, String b, String c) { return a + c + c + b; } Rosetta::Code
C:\Apps\groovy>groovysh Groovy Shell (1.6.2, JVM: 1.6.0_13) Type 'help' or '\h' for help. --------------------------------------------------------------------------------------------------- groovy:000> f = { a, b, sep -> a + sep + sep + b } ===> groovysh_evaluate$_run_closure1@5e8d7d groovy:000> println f('Rosetta','Co...
Keep all operations the same but rewrite the snippet in Groovy.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class...
def cruncher = { x1, x2, program -> Eval.x(x1, program) - Eval.x(x2, program) }
Ensure the translated Groovy code behaves exactly like the original Java snippet.
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe"; private static class...
def cruncher = { x1, x2, program -> Eval.x(x1, program) - Eval.x(x2, program) }
Generate a Groovy translation of this Java snippet without changing its computational steps.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.Fo...
def years1 = new GroovyShell().evaluate(''' (2008..2121).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" } ''') println years1
Keep all operations the same but rewrite the snippet in Groovy.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.tools.FileObject; import javax.tools.Fo...
def years1 = new GroovyShell().evaluate(''' (2008..2121).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" } ''') println years1
Convert the following code from Java to Groovy, ensuring the logic remains intact.
public class BraceExpansion { public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ cas...
class BraceExpansion { static void main(String[] args) { for (String s : [ "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ c...
Produce a functionally identical Groovy code for the snippet given in Java.
public static Color getColorAt(int x, int y){ return new Robot().getPixelColor(x, y); }
import java.awt.Robot class GetPixelColor { static void main(args) { println getColorAt(args[0] as Integer, args[1] as Integer) } static getColorAt(x, y) { new Robot().getPixelColor(x, y) } }
Generate a Groovy translation of this Java snippet without changing its computational steps.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
class Circles { private static class Point { private final double x, y Point(Double x, Double y) { this.x = x this.y = y } double distanceFrom(Point other) { double dx = x - other.x double dy = y - other.y return Math.sqrt...
Write the same algorithm in Groovy as shown in this Java implementation.
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
class Circles { private static class Point { private final double x, y Point(Double x, Double y) { this.x = x this.y = y } double distanceFrom(Point other) { double dx = x - other.x double dy = y - other.y return Math.sqrt...
Rewrite this program in Groovy while keeping its functionality equivalent to the Java version.
import java.util.List; public class Main { private static class Range { int start; int end; boolean print; public Range(int s, int e, boolean p) { start = s; end = e; print = p; } } public static void main(String[] args) { ...
class Main { private static class Range { int start int end boolean print Range(int s, int e, boolean p) { start = s end = e print = p } } static void main(String[] args) { List<Range> rgs = Arrays.asList( ...
Write the same code in Groovy as shown below in Java.
import java.util.List; public class Main { private static class Range { int start; int end; boolean print; public Range(int s, int e, boolean p) { start = s; end = e; print = p; } } public static void main(String[] args) { ...
class Main { private static class Range { int start int end boolean print Range(int s, int e, boolean p) { start = s end = e print = p } } static void main(String[] args) { List<Range> rgs = Arrays.asList( ...
Translate this program into Groovy but keep the logic exactly as in Java.
package hu.pj.alg.test; import hu.pj.alg.BoundedKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class BoundedKnapsackForTourists { public BoundedKnapsackForTourists() { BoundedKnapsack bok = new BoundedKnapsack(400); bok.add("map", 9, 150, 1); bok...
def totalWeight = { list -> list.collect{ it.item.weight * it.count }.sum() } def totalValue = { list -> list.collect{ it.item.value * it.count }.sum() } def knapsackBounded = { possibleItems -> def n = possibleItems.size() def m = (0..n).collect{ i -> (0..400).collect{ w -> []} } (1..400).each { w -> ...
Convert this Java block to Groovy, preserving its control flow and logic.
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(" ...
import java.lang.reflect.Constructor abstract class Angle implements Comparable<? extends Angle> { double value Angle(double value = 0) { this.value = normalize(value) } abstract Number unitCircle() abstract String unitName() Number normalize(double n) { n % this.unitCircle() } def <B exte...
Port the following code from Java to Groovy with equivalent syntax and logic.
import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class XMLPars...
def inventory = new XmlSlurper().parseText("<inventory...") def firstItem = inventory.section.item[0] inventory.section.item.price.each { println it } def allNamesArray = inventory.section.item.name.collect {it}
Change the following Java code into Groovy without altering its purpose.
import java.awt.Point; import java.util.*; public class ZhangSuen { final static String[] image = { " ", " ################# ############# ", " ################## ################ ", ...
def zhangSuen(text) { def image = text.split('\n').collect { line -> line.collect { it == '#' ? 1 : 0} } def p2, p3, p4, p5, p6, p7, p8, p9 def step1 = { (p2 * p4 * p6 == 0) && (p4 * p6 * p8 == 0) } def step2 = { (p2 * p4 * p8 == 0) && (p2 * p6 * p8 == 0) } def reduce = { step -> def toWhite...
Maintain the same structure and functionality when rewriting this code in Groovy.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
enum Op { ADD('+', 2), SUBTRACT('-', 2), MULTIPLY('*', 1), DIVIDE('/', 1); static { ADD.operation = { a, b -> a + b } SUBTRACT.operation = { a, b -> a - b } MULTIPLY.operation = { a, b -> a * b } DIVIDE.operation = { a, b -> a / b } } final String sy...
Transform the following Java implementation into Groovy, maintaining the same output and logic.
import java.util.Stack; public class ArithmeticEvaluation { public interface Expression { BigRational eval(); } public enum Parentheses {LEFT} public enum BinaryOperator { ADD('+', 1), SUB('-', 1), MUL('*', 2), DIV('/', 2); public final char symbol; ...
enum Op { ADD('+', 2), SUBTRACT('-', 2), MULTIPLY('*', 1), DIVIDE('/', 1); static { ADD.operation = { a, b -> a + b } SUBTRACT.operation = { a, b -> a - b } MULTIPLY.operation = { a, b -> a * b } DIVIDE.operation = { a, b -> a / b } } final String sy...
Generate a Groovy translation of this Java snippet without changing its computational steps.
import static java.util.stream.IntStream.rangeClosed; public class Test { final static int nMax = 12; static char[] superperm; static int pos; static int[] count = new int[nMax]; static int factSum(int n) { return rangeClosed(1, n) .map(m -> rangeClosed(1, m).reduce(1, (a,...
import static java.util.stream.IntStream.rangeClosed class Superpermutation { final static int nMax = 12 static char[] superperm static int pos static int[] count = new int[nMax] static int factSum(int n) { return rangeClosed(1, n) .map({ m -> rangeClosed(1, m).reduce(1, { a, ...
Ensure the translated Groovy code behaves exactly like the original Java snippet.
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan...
def hashJoin(table1, col1, table2, col2) { def hashed = table1.groupBy { s -> s[col1] } def q = [] as Set table2.each { r -> def join = hashed[r[col2]] join.each { s -> q << s.plus(r) } } q }
Transform the following Java implementation into Groovy, maintaining the same output and logic.
package lvijay; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class Church { public static interface ChurchNum extends Function<ChurchNum, ChurchNum> { } public static ChurchNum zero() { return f -> x -> x; } public static ChurchNum next(Chu...
class ChurchNumerals { static void main(args) { def zero = { f -> { a -> a } } def succ = { n -> { f -> { a -> f(n(f)(a)) } } } def add = { n -> { k -> { n(succ)(k) } } } def mult = { f -> { g -> { a -> f(g(a)) } } } def pow = { f -> { g -> g(f) } } def toChurchNum ...
Write the same algorithm in Groovy as shown in this Java implementation.
package lvijay; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class Church { public static interface ChurchNum extends Function<ChurchNum, ChurchNum> { } public static ChurchNum zero() { return f -> x -> x; } public static ChurchNum next(Chu...
class ChurchNumerals { static void main(args) { def zero = { f -> { a -> a } } def succ = { n -> { f -> { a -> f(n(f)(a)) } } } def add = { n -> { k -> { n(succ)(k) } } } def mult = { f -> { g -> { a -> f(g(a)) } } } def pow = { f -> { g -> g(f) } } def toChurchNum ...
Keep all operations the same but rewrite the snippet in Groovy.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Objects; public class Calculate_Pi { private static final MathContext con1024 = new MathContext(1024); private static final BigDecimal bigTwo = new BigDecimal(2); private static final BigDecimal bigFour = new BigDecimal(4); pr...
import java.math.MathContext class CalculatePi { private static final MathContext con1024 = new MathContext(1024) private static final BigDecimal bigTwo = new BigDecimal(2) private static final BigDecimal bigFour = new BigDecimal(4) private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) { ...
Generate an equivalent Groovy version of this Java code.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Objects; public class Calculate_Pi { private static final MathContext con1024 = new MathContext(1024); private static final BigDecimal bigTwo = new BigDecimal(2); private static final BigDecimal bigFour = new BigDecimal(4); pr...
import java.math.MathContext class CalculatePi { private static final MathContext con1024 = new MathContext(1024) private static final BigDecimal bigTwo = new BigDecimal(2) private static final BigDecimal bigFour = new BigDecimal(4) private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) { ...
Change the following Java code into Groovy without altering its purpose.
import javax.swing.JFrame; import javax.swing.SwingUtilities; public class WindowExample { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { createAndShow(); } }; SwingUtilities.invokeLater(runnable); } static void createAndShow() { ...
import javax.swing.* import java.awt.* import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.awt.geom.Rectangle2D class WindowCreation extends JApplet implements Runnable { void paint(Graphics g) { (g as Graphics2D).with { setStroke(new BasicStroke(2.0f)) ...
Produce a language-to-language conversion: from Java to Groovy, same semantics.
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) ...
class CutRectangle { private static int[][] dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]] 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[][]...
Generate a Groovy translation of this Java snippet without changing its computational steps.
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) ...
class CutRectangle { private static int[][] dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]] 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[][]...
Maintain the same structure and functionality when rewriting this code in Groovy.
public class CubanPrimes { private static int MAX = 1_400_000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { preCompute(); cubanPrime(200, true); for ( int i = 1 ; i <= 5 ; i++ ) { int max = (int) Math.pow(10, i); ...
class CubanPrimes { private static int MAX = 1_400_000 private static boolean[] primes = new boolean[MAX] static void main(String[] args) { preCompute() cubanPrime(200, true) for (int i = 1; i <= 5; i++) { int max = (int) Math.pow(10, i) printf("%,d-th cuban ...
Produce a functionally identical Groovy code for the snippet given in Java.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex; ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = ...
import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Scene import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.stage.Stage class ChaosGame extends Application { final randomNumberGenerator = new Random() @O...
Generate an equivalent Groovy version of this Java code.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex; ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = ...
import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Scene import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.stage.Stage class ChaosGame extends Application { final randomNumberGenerator = new Random() @O...
Generate an equivalent Groovy version of this Java code.
import java.util.Locale; public class Test { public static void main(String[] args) { System.out.println(new Vec2(5, 7).add(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).mult(11)); System.out.println(new Vec2(5, 7).div(2...
import groovy.transform.EqualsAndHashCode @EqualsAndHashCode class Vector { private List<Number> elements Vector(List<Number> e ) { if (!e) throw new IllegalArgumentException("A Vector must have at least one element.") if (!e.every { it instanceof Number }) throw new IllegalArgumentException("E...
Translate this program into Groovy but keep the logic exactly as in Java.
import static java.lang.Math.*; import java.util.function.Function; public class ChebyshevCoefficients { static double map(double x, double min_x, double max_x, double min_to, double max_to) { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to; } static void chebyshevCo...
class ChebyshevCoefficients { static double map(double x, double min_x, double max_x, double min_to, double max_to) { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to } static void chebyshevCoef(Closure<Double> func, double min, double max, double[] coef) { final int N = co...
Write a version of this Java function in Groovy with identical behavior.
import static java.lang.Math.*; import java.util.function.Function; public class ChebyshevCoefficients { static double map(double x, double min_x, double max_x, double min_to, double max_to) { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to; } static void chebyshevCo...
class ChebyshevCoefficients { static double map(double x, double min_x, double max_x, double min_to, double max_to) { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to } static void chebyshevCoef(Closure<Double> func, double min, double max, double[] coef) { final int N = co...
Translate this program into Groovy but keep the logic exactly as in Java.
import java.util.ArrayList; import java.util.List; public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003"; private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String canno...
class BWT { private static final String STX = "\u0002" private static final String ETX = "\u0003" private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String cannot contain STX or ETX") } String ss = STX + s...
Convert this Java snippet to Groovy and keep its semantics consistent.
import java.util.ArrayList; import java.util.List; public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003"; private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String canno...
class BWT { private static final String STX = "\u0002" private static final String ETX = "\u0003" private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String cannot contain STX or ETX") } String ss = STX + s...
Rewrite the snippet below in Groovy so it works the same as the original Java code.
import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; public class CardShuffles{ private static final Random rand = new Random(); public static <T> LinkedList<T> riffleShuffle(List<T> list, int flips){ LinkedList<T> newList = new Linke...
class CardShuffles { private static final Random rand = new Random() static <T> LinkedList<T> riffleShuffle(List<T> list, int flips) { LinkedList<T> newList = new LinkedList<T>() newList.addAll(list) for (int n = 0; n < flips; n++) { int cutPoint = newList.siz...
Maintain the same structure and functionality when rewriting this code in Groovy.
import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; public class CardShuffles{ private static final Random rand = new Random(); public static <T> LinkedList<T> riffleShuffle(List<T> list, int flips){ LinkedList<T> newList = new Linke...
class CardShuffles { private static final Random rand = new Random() static <T> LinkedList<T> riffleShuffle(List<T> list, int flips) { LinkedList<T> newList = new LinkedList<T>() newList.addAll(list) for (int n = 0; n < flips; n++) { int cutPoint = newList.siz...
Translate this program into Groovy but keep the logic exactly as in Java.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream; public class FaulhabersTriangle { private static final MathContext MC = new MathContext(256); private static long gcd(long a, long b) { if (b == 0) { return a; } ...
import java.math.MathContext import java.util.stream.LongStream class FaulhabersTriangle { private static final MathContext MC = new MathContext(256) private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) } private static class Frac...
Write a version of this Java function in Groovy with identical behavior.
import java.util.Arrays; import java.util.stream.IntStream; public class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static class Frac implements Comparable<Frac> { private long num; ...
import java.util.stream.IntStream class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) } private static class Frac implements Comparable<Frac> { private long num private long denom pub...
Translate the given Java code snippet into Groovy without altering its behavior.
public class AdditionChains { private static class Pair { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1]; result[0] = n; System.arrayc...
class AdditionChains { private static class Pair { int f, s Pair(int f, int s) { this.f = f this.s = s } } private static int[] prepend(int n, int[] seq) { int[] result = new int[seq.length + 1] result[0] = n System.arraycopy(seq, 0, ...
Maintain the same structure and functionality when rewriting this code in Groovy.
import java.util.*; public class FiniteStateMachine { private enum State { Ready(true, "Deposit", "Quit"), Waiting(true, "Select", "Refund"), Dispensing(true, "Remove"), Refunding(false, "Refunding"), Exiting(false, "Quiting"); State(boolean exp, String... in) { ...
class FiniteStateMachine { private enum State { Ready(true, "Deposit", "Quit"), Waiting(true, "Select", "Refund"), Dispensing(true, "Remove"), Refunding(false, "Refunding"), Exiting(false, "Quiting"); State(boolean exp, String... input) { inputs = Arrays....
Translate this program into Groovy but keep the logic exactly as in Java.
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); Sys...
import java.lang.reflect.Field @SuppressWarnings("unused") class ListProperties { public int examplePublicField = 42 private boolean examplePrivateField = true static void main(String[] args) { ListProperties obj = new ListProperties() Class clazz = obj.class println "All public f...
Rewrite the snippet below in Groovy so it works the same as the original Java code.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58);...
class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" private static final BigInteger BIG0 = BigInteger.ZERO private static final BigInteger BIG58 = BigInteger.valueOf(58) private static String convertToBase58(String hash) { ...
Write the same code in Groovy as shown below in Java.
import java.math.BigInteger; import java.util.List; public class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; private static final BigInteger BIG0 = BigInteger.ZERO; private static final BigInteger BIG58 = BigInteger.valueOf(58);...
class Base58CheckEncoding { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" private static final BigInteger BIG0 = BigInteger.ZERO private static final BigInteger BIG58 = BigInteger.valueOf(58) private static String convertToBase58(String hash) { ...
Produce a functionally identical Groovy code for the snippet given in Java.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class ArithmeticCoding { private static class Triple<A, B, C> { A a; B b; C c; Triple(A a, B b, C c) { this.a = a; this.b = b; this.c = ...
class ArithmeticCoding { private static class Triple<A, B, C> { A a B b C c Triple(A a, B b, C c) { this.a = a this.b = b this.c = c } } private static class Freq extends HashMap<Character, Long> { } private stat...
Port the following code from Java to Groovy with equivalent syntax and logic.
import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Coll...
import java.util.function.Predicate import java.util.regex.Matcher import java.util.regex.Pattern class FindBareTags { private static final Pattern TITLE_PATTERN = Pattern.compile("\"title\": \"([^\"]+)\"") private static final Pattern HEADER_PATTERN = Pattern.compile("==\\{\\{header\\|([^}]+)}}==") privat...
Produce a language-to-language conversion: from Java to Groovy, same semantics.
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import javax.xml.ws.Holder; import org.xml.sax.ErrorHandler; import...
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI import javax.xml.transform.stream.StreamSource import javax.xml.validation.SchemaFactory import org.xml.sax.SAXParseException def factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI) def validate = { schemaURL, docURL -> try { factory.newSche...
Port the provided Java code into Groovy while preserving the original functionality.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin",...
class MetallicRatios { private static List<String> names = new ArrayList<>() static { names.add("Platinum") names.add("Golden") names.add("Silver") names.add("Bronze") names.add("Copper") names.add("Nickel") names.add("Aluminum") names.add("Iron") ...
Change the following Java code into Groovy without altering its purpose.
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin",...
class MetallicRatios { private static List<String> names = new ArrayList<>() static { names.add("Platinum") names.add("Golden") names.add("Silver") names.add("Bronze") names.add("Copper") names.add("Nickel") names.add("Aluminum") names.add("Iron") ...
Convert this VB snippet to Clojure and keep its semantics consistent.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbrevia...
(defn words "Split string into words" [^String str] (.split (.stripLeading str) "\\s+")) (defn join-words "Join words into a single string" ^String [strings] (String/join " " strings)) (defn starts-with-ignore-case "Does string start with prefix (ignoring case)?" ^Boolean [^String string, ^String pre...
Generate an equivalent Clojure version of this VB code.
Option Explicit sub verifydistribution(calledfunction, samples, delta) Dim i, n, maxdiff Dim d : Set d = CreateObject("Scripting.Dictionary") wscript.echo "Running """ & calledfunction & """ " & samples & " times..." for i = 1 to samples Execute "n = " & calledfunction d(n) = d(n) + 1 next n = d.Count max...
(defn verify [rand n & [delta]] (let [rands (frequencies (repeatedly n rand)) avg (/ (reduce + (map val rands)) (count rands)) max-delta (* avg (or delta 1/10)) acceptable? #(<= (- avg max-delta) % (+ avg max-delta))] (for [[num count] (sort rands)] [num count (acceptable? count)])))...
Preserve the algorithm and functionality while converting the code from VB to Clojure.
Public Const HOLDON = False Public Const DIJKSTRASOLUTION = True Public Const X = 10 Public Const GETS = 0 Public Const PUTS = 1 Public Const EATS = 2 Public Const THKS = 5 Public Const FRSTFORK = 0 Public Const SCNDFORK = 1 Public Const SPAGHETI = 0 Public Const UNIVERSE = 1 Public Const MAXCOUNT = 100000 Public...
(defn make-fork [] (ref true)) (defn make-philosopher [name forks food-amt] (ref {:name name :forks forks :eating? false :food food-amt})) (defn start-eating [phil] (dosync (if (every? true? (map ensure (:forks @phil))) (do (doseq [f (:forks @phil)] (alter f not)) (alter phil assoc ...