Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Generate an equivalent AutoHotKey version of this PHP code.
function multiply( $a, $b ) { return $a * $b; }
MsgBox % multiply(10,2) multiply(multiplicand, multiplier) { Return (multiplicand * multiplier) }
Convert the following code from PHP to AutoHotKey, ensuring the logic remains intact.
function sattoloCycle($items) { for ($i = 0; $i < count($items); $i++) { $j = floor((mt_rand() / mt_getrandmax()) * $i); $tmp = $items[$i]; $items[$i] = $items[$j]; $items[$j] = $tmp; } return $items; }
loop 3 { testCases:= [[] ,[10] ,[10, 20] ,[10, 20, 30] ,[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]] for n, items in testCases { Sattolo_cycle(items) res := "[" for m, v in items res .= v ", " r...
Write a version of this PHP function in AutoHotKey with identical behavior.
function sattoloCycle($items) { for ($i = 0; $i < count($items); $i++) { $j = floor((mt_rand() / mt_getrandmax()) * $i); $tmp = $items[$i]; $items[$i] = $items[$j]; $items[$j] = $tmp; } return $items; }
loop 3 { testCases:= [[] ,[10] ,[10, 20] ,[10, 20, 30] ,[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]] for n, items in testCases { Sattolo_cycle(items) res := "[" for m, v in items res .= v ", " r...
Change the programming language of this snippet from PHP to AutoHotKey without modifying what it does.
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) ...
BeadSort(data){ Pole:=[] , TempObj:=[], Result:=[] for, i, v in data { Row := i loop, % v MaxPole := MaxPole>A_Index?MaxPole:A_Index , Pole[A_Index, row] := 1 } for i , obj in Pole { TempVar:=0 , c := A_Index for n, v in obj TempVar += v loop, % TempVar TempObj[c, A_Index] := 1 } loop, % Row ...
Can you help me rewrite this code in AutoHotKey instead of PHP, keeping it the same logically?
$accumulator = 0; echo 'HQ9+: '; $program = trim(fgets(STDIN)); foreach (str_split($program) as $chr) { switch ($chr) { case 'H': case 'h': printHelloWorld(); break; case 'Q': case 'q': printSource($program); break; case '9': ...
testCode := "hq9+HqQ+Qq" MsgBox % RunHQ9Plus(testCode) RunHQ9Plus(input) { Loop, Parse, input If ( A_LoopField = "+" ) acc++ Else If ( A_LoopField = "H" ) output .= "Hello, world!`n" Else If ( A_LoopField = "Q" ) output .= input "`n" Else If ( A_LoopField = "9" ) Loop, 99...
Port the following code from PHP to AutoHotKey with equivalent syntax and logic.
$accumulator = 0; echo 'HQ9+: '; $program = trim(fgets(STDIN)); foreach (str_split($program) as $chr) { switch ($chr) { case 'H': case 'h': printHelloWorld(); break; case 'Q': case 'q': printSource($program); break; case '9': ...
testCode := "hq9+HqQ+Qq" MsgBox % RunHQ9Plus(testCode) RunHQ9Plus(input) { Loop, Parse, input If ( A_LoopField = "+" ) acc++ Else If ( A_LoopField = "H" ) output .= "Hello, world!`n" Else If ( A_LoopField = "Q" ) output .= input "`n" Else If ( A_LoopField = "9" ) Loop, 99...
Ensure the translated AutoHotKey code behaves exactly like the original PHP snippet.
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __c...
suits := ["♠", "♦", "♥", "♣"] values := [2,3,4,5,6,7,8,9,10,"J","Q","K","A"] Gui, font, s14 Gui, add, button, w190 gNewDeck, New Deck Gui, add, button, x+10 wp gShuffle, Shuffle Gui, add, button, x+10 wp gDeal, Deal Gui, add, text, xs w600 , Current Deck: Gui, add, Edit, xs wp r4 vDeck Gui, add, text, xs , Hands: Gui, ...
Keep all operations the same but rewrite the snippet in AutoHotKey.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
DeepCopy(Array, Objs=0) { If !Objs Objs := Object() Obj := Array.Clone()  Objs[&Array] := Obj  For Key, Val in Obj If (IsObject(Val))  Obj[Key] := Objs[&Val]  ? Objs[&Val]  : DeepCopy(Val,Objs)  Return Obj }
Port the provided PHP code into AutoHotKey while preserving the original functionality.
<?php class Foo { public function __clone() { $this->child = clone $this->child; } } $object = new Foo; $object->some_value = 1; $object->child = new stdClass; $object->child->some_value = 1; $deepcopy = clone $object; $deepcopy->some_value++; $deepcopy->child->some_value++; echo "Object contains...
DeepCopy(Array, Objs=0) { If !Objs Objs := Object() Obj := Array.Clone()  Objs[&Array] := Obj  For Key, Val in Obj If (IsObject(Val))  Obj[Key] := Objs[&Val]  ? Objs[&Val]  : DeepCopy(Val,Objs)  Return Obj }
Can you help me rewrite this code in AutoHotKey instead of PHP, keeping it the same logically?
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) ...
MsgBox % PermSort("") MsgBox % PermSort("xxx") MsgBox % PermSort("3,2,1") MsgBox % PermSort("dog,000000,xx,cat,pile,abcde,1,cat") PermSort(var) {   Local i, sorted StringSplit a, var, `,   v0 := a0   Loop %v0% v%A_Index% := A_Index ...
Ensure the translated AutoHotKey code behaves exactly like the original PHP snippet.
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
InputBox, Year, , Enter a year., , 300, 135 Date := Year . "0101" while SubStr(Date, 1, 4) = Year { FormatTime, WD, % Date, WDay if (WD = 1) MM := LTrim(SubStr(Date, 5, 2), "0"), Day%MM% := SubStr(Date, 7, 2) Date += 1, Days } Gui, Font, S10, Courier New Gui, Add, Text, , % "Last Sundays of " Year...
Port the following code from PHP to AutoHotKey with equivalent syntax and logic.
<?php function printLastSundayOfAllMonth($year) { $months = array( 'January', 'February', 'March', 'April', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); foreach ($months as $month) { echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ...
InputBox, Year, , Enter a year., , 300, 135 Date := Year . "0101" while SubStr(Date, 1, 4) = Year { FormatTime, WD, % Date, WDay if (WD = 1) MM := LTrim(SubStr(Date, 5, 2), "0"), Day%MM% := SubStr(Date, 7, 2) Date += 1, Days } Gui, Font, S10, Courier New Gui, Add, Text, , % "Last Sundays of " Year...
Generate an equivalent AutoHotKey version of this PHP code.
<?php class Node { public $val; public $back = NULL; } function lis($n) { $pileTops = array(); foreach ($n as $x) { $low = 0; $high = count($pileTops)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($pileTops[$mid]->val >= $x) $...
Lists := [[3,2,6,4,5,1], [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15]] for k, v in Lists { D := LIS(v) MsgBox, % D[D.I].seq } LIS(L) { D := [] for i, v in L { D[i, "Length"] := 1, D[i, "Seq"] := v, D[i, "Val"] := v Loop, % i - 1 { if(D[A_Index].Val < v && D[A_Index].Length + 1 > D[i].Length) { D[i].Length :...
Convert the following code from PHP to AutoHotKey, ensuring the logic remains intact.
<?php $varname = rtrim(fgets(STDIN)); # type in "foo" on standard input $$varname = 42; echo "$foo\n"; # prints "42" ?>
InputBox, Dynamic, Variable Name %Dynamic% = hello ListVars MsgBox % %dynamic%  
Convert this PHP block to AutoHotKey, preserving its control flow 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". ?>
msgbox % first := evalWithX("x + 4", 5) msgbox % second := evalWithX("x + 4", 6) msgbox % second - first return evalWithX(expression, xvalue) { global script script = ( expression(){ x = %xvalue%   return %expression% } ) renameFunction("expression", "")   gosub load  exp := "expression" return %exp%() ...
Generate a AutoHotKey translation of this PHP snippet without changing its computational steps.
<?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". ?>
msgbox % first := evalWithX("x + 4", 5) msgbox % second := evalWithX("x + 4", 6) msgbox % second - first return evalWithX(expression, xvalue) { global script script = ( expression(){ x = %xvalue%   return %expression% } ) renameFunction("expression", "")   gosub load  exp := "expression" return %exp%() ...
Change the following PHP code into AutoHotKey without altering its purpose.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
msgbox % eval("3 + 4") msgbox % eval("4 + 4") return eval(expression) { global script script = ( expression(){ return %expression% } ) renameFunction("expression", "")   gosub load  exp := "expression" return %exp%() } load: DllCall(A_AhkPath "\addScript","Str",script,"Uchar",0,"Cdecl UInt") return rena...
Write the same code in AutoHotKey as shown below in PHP.
<?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);
msgbox % eval("3 + 4") msgbox % eval("4 + 4") return eval(expression) { global script script = ( expression(){ return %expression% } ) renameFunction("expression", "")   gosub load  exp := "expression" return %exp%() } load: DllCall(A_AhkPath "\addScript","Str",script,"Uchar",0,"Cdecl UInt") return rena...
Convert this PHP block to AutoHotKey, preserving its control flow and logic.
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 = []; ...
BraceExp(string, del:="`n") { Loop, Parse, string if (A_LoopField = "{") break else substring .= A_LoopField substr := SubStr(string, InStr(string, "{")+1, InStr(string, "}")-InStr(string, "{")-1) Loop, Parse, substr, `, toreturn .= substring . A_LoopField . del return toreturn } Msgbox, % BraceExp("en...
Produce a functionally identical AutoHotKey code for the snippet given in PHP.
$img = imagegrabscreen(); $color = imagecolorat($im, 10, 50); imagedestroy($im);
PixelGetColor, color, %X%, %Y%
Convert this PHP block to AutoHotKey, preserving its control flow and logic.
<?php $ldap = ldap_connect($hostname, $port); $success = ldap_bind($ldap, $username, $password);
objConn := CreateObject("ADODB.Connection") objCmd := CreateObject("ADODB.Command") objConn.Provider := "ADsDSOObject" objConn.Open()
Please provide an equivalent version of this PHP code in AutoHotKey.
<?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()); ?>
WS_Initialize() WS_Exec("Set client = CreateObject(""MSSOAP.SoapClient"")") WS_Exec("client.MSSoapInit ""http://example.com/soap/wsdl""") callhello = client.soapFunc("hello") callanother = client.anotherSoapFunc(34234) WS_Eval(result, callhello) WS_Eval(result2, callanother) Msgbox % re...
Ensure the translated AutoHotKey code behaves exactly like the original PHP snippet.
$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();...
string = ( -2 0 -2 5 5 3 -1 -3 5 5 0 2 -4 4 2 ) string2 := string Loop { loop, parse, string, %A_space% { list := 1 = A_index ? A_loopfield : list StringSplit, k, list, %A_space% if ( k%k0% <= A_loopfield ) && ( l != "" ) && ( A_index != 1 ) list := list . " " . A_loopfield if ( k%k0% > A_loopfield ) ...
Convert this PHP snippet to AutoHotKey and keep its semantics consistent.
<?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...
FileRead, inventory, xmlfile.xml RegExMatch(inventory, "<item.*?</item>", item1) MsgBox % item1 pos = 1 While, pos := RegExMatch(inventory, "<price>(.*?)</price>", price, pos + 1) MsgBox % price1 While, pos := RegExMatch(inventory, "<name>.*?</name>", name, pos + 1) names .= name . "`n" MsgBox % names
Convert this PHP block to AutoHotKey, preserving its control flow and logic.
<?php $conf = file_get_contents('update-conf-file.txt'); $conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf); $conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf); $conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf); if (preg_match('/^;?\s*(numberofstrawberries)/mi'...
data = %A_scriptdir%\rosettaconfig.txt outdata = %A_scriptdir%\rosettaconfig.tmp FileDelete, %outdata% NUMBEROFBANANAS := 1024 numberofstrawberries := 560 NEEDSPEELING = "0" FAVOURITEFRUIT := "bananas" SEEDSREMOVED = "1" BOOL0 = "0" BOOL1 = "1" NUMBER1 := 1 number0 := 0 STRINGA := "string here" parameters = bool0|bo...
Transform the following PHP implementation into AutoHotKey, maintaining the same output and logic.
$key2val = ["A"=>"30", "B"=>"31", "C"=>"32", "D"=>"33", "E"=>"5", "F"=>"34", "G"=>"35", "H"=>"0", "I"=>"36", "J"=>"37", "K"=>"38", "L"=>"2", "M"=>"4", "."=>"78", "N"=>"39", "/"=>"79", "O"=>"1", "0"=>"790", "P"=>"70", "1"=>"791", "Q"=>"71", "2"=>"792", "R"=>"8", "3"=>"793", "S"=>"6", "4"=>"794", ...
board := " ( ET AON RIS BCDFGHJKLM PQ/UVWXYZ. )" Text = One night-it was on the twentieth of March, 1888-I was returning StringUpper, Text, Text Text := RegExReplace(text, "[^A-Z0-9]") Num2 := InStr(board, A_Space) -1 Num3 := InStr(board, A_Space, true, Num1+1) -1 Loop Parse, Text { char := A_LoopField ...
Translate this program into AutoHotKey but keep the logic exactly as in PHP.
<?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...
class example { foo() { Msgbox Called example.foo() } __Call(method, params*) { funcRef := Func(funcName := this.__class "." method) if !IsObject(funcRef) { str := "Called undefined method " funcName "() with these parameters:" for k,v in params str .= "`n" v Msgbox ...
Change the programming language of this snippet from Java to Perl without modifying what it does.
class SpecialPrimes { private static boolean isPrime(int n) { if (n < 2) return false; if (n%2 == 0) return n == 2; if (n%3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; d += 2; if (n%d == 0) return false; ...
use strict; use warnings; use feature <state say>; use ntheory 'primes'; my $limit = 1050; sub is_special { state $previous = 2; state $gap = 0; state @primes = @{primes( 2*$limit )}; shift @primes while $primes[0] <= $previous + $gap; $gap = $primes[0] - $previous; $previous = $primes[0...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
public class LynchBell { static String s = ""; public static void main(String args[]) { int i = 98764321; boolean isUnique = true; boolean canBeDivided = true; while (i>0) { s = String.valueOf(i); isUnique = uniqueDigits(i); ...
my $step = 9 * 8 * 7; my $initial = int(9876432 / $step) * $step; for($test = $initial; $test > 0 ; $test -= $step) { next if $test =~ /[05]/; next if $test =~ /(.).*\1/; for (split '', $test) { ...
Generate a Perl translation of this Java snippet without changing its computational steps.
public class LynchBell { static String s = ""; public static void main(String args[]) { int i = 98764321; boolean isUnique = true; boolean canBeDivided = true; while (i>0) { s = String.valueOf(i); isUnique = uniqueDigits(i); ...
my $step = 9 * 8 * 7; my $initial = int(9876432 / $step) * $step; for($test = $initial; $test > 0 ; $test -= $step) { next if $test =~ /[05]/; next if $test =~ /(.).*\1/; for (split '', $test) { ...
Maintain the same structure and functionality when rewriting this code in Perl.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { ...
use strict; use warnings; sub J { my($k,$n) = @_; $k %= $n; my $jacobi = 1; while ($k) { while (0 == $k % 2) { $k = int $k / 2; $jacobi *= -1 if $n%8 == 3 or $n%8 == 5; } ($k, $n) = ($n, $k); $jacobi *= -1 if $n%4 == 3 and $k%4 == 3; $k %...
Translate this program into Perl but keep the logic exactly as in Java.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { ...
use strict; use warnings; sub J { my($k,$n) = @_; $k %= $n; my $jacobi = 1; while ($k) { while (0 == $k % 2) { $k = int $k / 2; $jacobi *= -1 if $n%8 == 3 or $n%8 == 5; } ($k, $n) = ($n, $k); $jacobi *= -1 if $n%4 == 3 and $k%4 == 3; $k %...
Produce a functionally identical Perl code for the snippet given in Java.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j...
use strict; use warnings; use PDL; use PDL::NiceSlice; sub permanent{ my $mat = shift; my $n = shift // $mat->dim(0); return undef if $mat->dim(0) != $mat->dim(1); return $mat(0,0) if $n == 1; my $sum = 0; --$n; my $m = $mat(1:,1:)->copy; for(my $i = 0; $i <= $n; ++$i){ $sum += $mat($i,0) * permanent($m, $n...
Translate the given Java code snippet into Perl without altering its behavior.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j...
use strict; use warnings; use PDL; use PDL::NiceSlice; sub permanent{ my $mat = shift; my $n = shift // $mat->dim(0); return undef if $mat->dim(0) != $mat->dim(1); return $mat(0,0) if $n == 1; my $sum = 0; --$n; my $m = $mat(1:,1:)->copy; for(my $i = 0; $i <= $n; ++$i){ $sum += $mat($i,0) * permanent($m, $n...
Translate this program into Perl but keep the logic exactly as in Java.
private static final Random rng = new Random(); void sattoloCycle(Object[] items) { for (int i = items.length-1; i > 0; i--) { int j = rng.nextInt(i); Object tmp = items[i]; items[i] = items[j]; items[j] = tmp; } }
@a = 0..30; printf "%2d ", $_ for @a; print "\n"; sattolo_cycle(\@a); printf "%2d ", $_ for @a; print "\n"; sub sattolo_cycle { my($array) = @_; for $i (reverse 0 .. -1+@$array) { my $j = int rand $i; @$array[$j, $i] = @$array[$i, $j]; } }
Produce a language-to-language conversion: from Java to Perl, same semantics.
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...
use Net::FTP; my $host = 'speedtest.tele2.net'; my $user = 'anonymous'; my $password = ''; my $f = Net::FTP->new($host) or die "Can't open $host\n"; $f->login($user, $password) or die "Can't login as $user\n"; $f->passive(); $f->cwd('upload'); @files = $f->ls(); printf "Currently %d files in the 'upload'...
Maintain the same structure and functionality when rewriting this code in Perl.
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...
use strict; use warnings; sub cycleSort :prototype(@) { my ($array) = @_; my $writes = 0; my @alreadysorted; for my $start ( 0 .. $ next if $alreadysorted[$start]; my $item = $array->[$start]; my $pos = $start + grep $array->[$_] lt $item, $start + 1 .. $ next if $pos == $start; ++$p...
Produce a language-to-language conversion: from Java to Perl, same semantics.
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...
use strict; use warnings; sub cycleSort :prototype(@) { my ($array) = @_; my $writes = 0; my @alreadysorted; for my $start ( 0 .. $ next if $alreadysorted[$start]; my $item = $array->[$start]; my $pos = $start + grep $array->[$_] lt $item, $start + 1 .. $ next if $pos == $start; ++$p...
Produce a functionally identical Perl code for the snippet given in Java.
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x =...
use strict; use warnings; use Primesieve; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma count_twins(1, 10**$_) for 1..10;
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
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...
use strict; use warnings; use ntheory qw<is_prime>; use constant Inf => 1e10; sub is_Brazilian { my($n) = @_; return 1 if $n > 6 && 0 == $n%2; LOOP: for (my $base = 2; $base < $n - 1; ++$base) { my $digit; my $nn = $n; while (1) { my $x = $nn % $base; $digit...
Maintain the same structure and functionality when rewriting this code in Perl.
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...
use strict; use warnings; use ntheory qw<is_prime>; use constant Inf => 1e10; sub is_Brazilian { my($n) = @_; return 1 if $n > 6 && 0 == $n%2; LOOP: for (my $base = 2; $base < $n - 1; ++$base) { my $digit; my $nn = $n; while (1) { my $x = $nn % $base; $digit...
Maintain the same structure and functionality when rewriting this code in Perl.
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<I...
use bignum; $max = 1000; $remaining += $_ for 1..$max; my @recamans = 0; my $previous = 0; while ($remaining > 0) { $term++; my $this = $previous - $term; $this = $previous + $term unless $this > 0 and !$seen{$this}; push @recamans, $this; $dup = $term if !$dup and defined $seen{$this}; $remaining ...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
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<I...
use bignum; $max = 1000; $remaining += $_ for 1..$max; my @recamans = 0; my $previous = 0; while ($remaining > 0) { $term++; my $this = $previous - $term; $this = $previous + $term unless $this > 0 and !$seen{$this}; push @recamans, $this; $dup = $term if !$dup and defined $seen{$this}; $remaining ...
Produce a language-to-language conversion: from Java to Perl, same semantics.
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...
sub Y { my $f = shift; sub { my $x = shift; $x->($x) }->( sub {my $y = shift; $f->(sub {$y->($y)(@_)})} ) } my $fac = sub {my $f = shift; sub {my $n = shift; $n < 2 ? 1 : $n * $f->($n-1)} }; my $fib = sub {my $f = shift; sub {my $n = shift; $n == 0 ? 0 :...
Maintain the same structure and functionality when rewriting this code in Perl.
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; ...
use strict; use warnings; use feature 'say'; use List::AllUtils <min max>; my @circles = ( [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832...
Convert this Java block to Perl, preserving its control flow and logic.
public class CirclesTotalArea { private static double distSq(double x1, double y1, double x2, double y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) { double r2 = circ[2] * circ[2]; ...
use strict; use warnings; use feature 'say'; use List::AllUtils <min max>; my @circles = ( [ 1.6417233788, 1.6121789534, 0.0848270516], [-1.4944608174, 1.2077959613, 1.1039549836], [ 0.6110294452, -0.6907087527, 0.9089162485], [ 0.3844862411, 0.2923344616, 0.2375743054], [-0.2495892950, -0.3832...
Write the same algorithm in Perl as shown in this Java implementation.
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")...
use strict; use warnings; use ntheory qw/factorial todigits/; my $limit = 1500000; for my $b (9 .. 12) { print "Factorions in base $b:\n"; $_ == factorial($_) and print "$_ " for 0..$b-1; for my $i (1 .. int $limit/$b) { my $sum; my $prod = $i * $b; for (reverse todigits($i, $b))...
Translate this program into Perl but keep the logic exactly as in Java.
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")...
use strict; use warnings; use ntheory qw/factorial todigits/; my $limit = 1500000; for my $b (9 .. 12) { print "Factorions in base $b:\n"; $_ == factorial($_) and print "$_ " for 0..$b-1; for my $i (1 .. int $limit/$b) { my $sum; my $prod = $i * $b; for (reverse todigits($i, $b))...
Generate a Perl translation of this Java snippet without changing its computational steps.
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 (po...
use strict; use warnings; use feature 'say'; use ntheory 'divisor_sum'; my @x; push @x, scalar divisor_sum($_) for 1..100; say "Divisor sums - first 100:\n" . ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
Please provide an equivalent version of this Java code in Perl.
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 (po...
use strict; use warnings; use feature 'say'; use ntheory 'divisor_sum'; my @x; push @x, scalar divisor_sum($_) for 1..100; say "Divisor sums - first 100:\n" . ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
Convert this Java block to Perl, preserving its control flow and logic.
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<Stri...
use strict; use warnings; sub ask { while( 1 ) { print "Compare $a to $b [<,=,>]: "; <STDIN> =~ /[<=>]/ and return +{qw( < -1 = 0 > 1 )}->{$&}; } } my @sorted = sort ask qw( violet red green indigo blue yellow orange ); print "sorted: @sorted\n";
Translate this program into Perl but keep the logic exactly as in Java.
import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class FermatNumbers { public static void main(String[] args) { System.out.println("First 10 Fermat numbers:"); for ( int i = 0 ...
use strict; use warnings; use feature 'say'; use bigint try=>"GMP"; use ntheory qw<factor>; my @Fermats = map { 2**(2**$_) + 1 } 0..9; my $sub = 0; say 'First 10 Fermat numbers:'; printf "F%s = %s\n", $sub++, $_ for @Fermats; $sub = 0; say "\nFactors of first few Fermat numbers:"; for my $f (map { [factor($_)] } @Fe...
Port the provided Java code into Perl while preserving the original functionality.
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...
sub beadsort { my @data = @_; my @columns; my @rows; for my $datum (@data) { for my $column ( 0 .. $datum-1 ) { ++ $rows[ $columns[$column]++ ]; } } return reverse @rows; } beadsort 5, 7, 1, 3, 1, 1, 20;
Write the same code in Perl as shown below in Java.
import java.util.*; import java.util.stream.IntStream; public class CastingOutNines { public static void main(String[] args) { System.out.println(castOut(16, 1, 255)); System.out.println(castOut(10, 1, 99)); System.out.println(castOut(17, 1, 288)); } static List<Integer> castOut(i...
sub co9 { my $n = shift; return $n if $n < 10; my $sum = 0; $sum += $_ for split(//,$n); co9($sum); } sub showadd { my($n,$m) = @_; print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]", " = ", $n+$m," [",co9($n+$m),"]\n"; } sub co9filter { my $base = shift; die unl...
Write the same code in Perl as shown below in Java.
import java.util.*; import java.util.stream.IntStream; public class CastingOutNines { public static void main(String[] args) { System.out.println(castOut(16, 1, 255)); System.out.println(castOut(10, 1, 99)); System.out.println(castOut(17, 1, 288)); } static List<Integer> castOut(i...
sub co9 { my $n = shift; return $n if $n < 10; my $sum = 0; $sum += $_ for split(//,$n); co9($sum); } sub showadd { my($n,$m) = @_; print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]", " = ", $n+$m," [",co9($n+$m),"]\n"; } sub co9filter { my $base = shift; die unl...
Port the provided Java code into Perl while preserving the original functionality.
import java.io.*; import java.text.*; import java.util.*; public class SimpleDatabase { final static String filename = "simdb.csv"; public static void main(String[] args) { if (args.length < 1 || args.length > 3) { printUsage(); return; } switch (args[0].toLow...
use warnings; use strict; use feature qw{ say }; use JSON::PP; use Time::Piece; use constant { NAME => 0, CATEGORY => 1, DATE => 2, DB => 'simple-db', }; my $operation = shift // ""; my %dispatch = ( n => \&add_new, l => \&print_latest, L => \&print_latest_for_categories, ...
Convert the following code from Java to Perl, ensuring the logic remains intact.
package keybord.macro.demo; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; class KeyboardMacroDemo { public static void main( String [] args ) { final JFrame frame = new JFrame(); String directions = "<html><b>Ctrl-S...
use strict; use warnings; use Term::ReadKey; ReadMode 4; sub logger { my($message) = @_; print "$message\n" } while (1) { if (my $c = ReadKey 0) { if ($c eq 'q') { logger "QUIT"; last } elsif ($c =~ /\n|\r/) { logger "CR" } elsif ($c eq "j") { logger "down" } elsif ($c eq "k") {...
Convert this Java block to Perl, preserving its control flow and logic.
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) { +...
use strict; use warnings; use feature 'say'; use ntheory 'divisors'; my @x; push @x, scalar divisors($_) for 1..100; say "Tau function - first 100:\n" . ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
Preserve the algorithm and functionality while converting the code from Java to Perl.
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) { +...
use strict; use warnings; use feature 'say'; use ntheory 'divisors'; my @x; push @x, scalar divisors($_) for 1..100; say "Tau function - first 100:\n" . ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
Translate the given Java code snippet into Perl without altering its behavior.
public class MöbiusFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the möbius function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", möbiusFunction(n)); if ( (n+1) % 20 == 0 ) { ...
use utf8; use strict; use warnings; use feature 'say'; use List::Util 'uniq'; sub prime_factors { my ($n, $d, @factors) = (shift, 1); while ($n > 1 and $d++) { $n /= $d, push @factors, $d until $n % $d; } @factors } sub μ { my @p = prime_factors(shift); @p == uniq(@p) ? 0 == @p%2 ? 1 :...
Change the programming language of this snippet from Java to Perl without modifying what it does.
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...
my %code = split ' ', <<'END'; > $ptr++ < $ptr-- + $memory[$ptr]++ - $memory[$ptr]-- , $memory[$ptr]=ord(getc) . print(chr($memory[$ptr])) [ while($memory[$ptr]){ ] } END my ($ptr, @memory) = 0; eval join ';', map @code{ /./g }, <>;
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
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...
my %code = split ' ', <<'END'; > $ptr++ < $ptr-- + $memory[$ptr]++ - $memory[$ptr]-- , $memory[$ptr]=ord(getc) . print(chr($memory[$ptr])) [ while($memory[$ptr]){ ] } END my ($ptr, @memory) = 0; eval join ';', map @code{ /./g }, <>;
Produce a language-to-language conversion: from Java to Perl, same semantics.
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 ) { ...
use utf8; use strict; use warnings; use feature 'say'; use List::Util 'uniq'; sub prime_factors { my ($n, $d, @factors) = (shift, 1); while ($n > 1 and $d++) { $n /= $d, push @factors, $d until $n % $d; } @factors } sub μ { my @p = prime_factors(shift); @p == uniq(@p) ? 0 == @p%2 ? 1 :...
Ensure the translated Perl code behaves exactly like the original Java snippet.
public class ProductOfDivisors { 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) { ...
use strict; use warnings; my @products = ( 1 ) x 51; for my $n ( 1 .. 50 ) { $n % $_ or $products[$n] *= $_ for 1 .. $n; } printf '' . (('%11d' x 5) . "\n") x 10, @products[1 .. 50];
Port the provided Java code into Perl while preserving the original functionality.
public class ProductOfDivisors { 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) { ...
use strict; use warnings; my @products = ( 1 ) x 51; for my $n ( 1 .. 50 ) { $n % $_ or $products[$n] *= $_ for 1 .. $n; } printf '' . (('%11d' x 5) . "\n") x 10, @products[1 .. 50];
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < m...
use strict; use warnings; use feature 'say'; use utf8; binmode(STDOUT, ':utf8'); use List::AllUtils 'before'; use ntheory qw<is_prime factorial>; sub is_erdos { my($n) = @_; my $k; return unless is_prime($n); while ($n > factorial($k++)) { return if is_prime $n-factorial($k) } 'True' } my(@Erdős,$n); ...
Convert this Java snippet to Perl and keep its semantics consistent.
import java.util.*; public class ErdosPrimes { public static void main(String[] args) { boolean[] sieve = primeSieve(1000000); int maxPrint = 2500; int maxCount = 7875; System.out.printf("Erd\u0151s primes less than %d:\n", maxPrint); for (int count = 0, prime = 1; count < m...
use strict; use warnings; use feature 'say'; use utf8; binmode(STDOUT, ':utf8'); use List::AllUtils 'before'; use ntheory qw<is_prime factorial>; sub is_erdos { my($n) = @_; my $k; return unless is_prime($n); while ($n > factorial($k++)) { return if is_prime $n-factorial($k) } 'True' } my(@Erdős,$n); ...
Translate the given Java code snippet into Perl without altering its behavior.
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
package Playing_Card_Deck; use strict; use warnings; @Playing_Card_Deck::suits = qw [Diamonds Clubs Hearts Spades]; @Playing_Card_Deck::pips = qw [Two Three Four Five Six Seven Eight Nine Ten Jack King Queen Ace]; sub new {my $invocant = shift; my $class = ref($invocant) || $invocant; my @cards; ...
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
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<Intege...
use ntheory qw(euler_phi); sub phi_iter { my($p) = @_; euler_phi($p) + ($p == 2 ? 0 : phi_iter(euler_phi($p))); } my @perfect; for (my $p = 2; @perfect < 20 ; ++$p) { push @perfect, $p if $p == phi_iter($p); } printf "The first twenty perfect totient numbers:\n%s\n", join ' ', @perfect;
Write the same code in Perl as shown below in Java.
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<Intege...
use ntheory qw(euler_phi); sub phi_iter { my($p) = @_; euler_phi($p) + ($p == 2 ? 0 : phi_iter(euler_phi($p))); } my @perfect; for (my $p = 2; @perfect < 20 ; ++$p) { push @perfect, $p if $p == phi_iter($p); } printf "The first twenty perfect totient numbers:\n%s\n", join ' ', @perfect;
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class LahNumbers { public static void main(String[] args) { System.out.println("Show the unsigned Lah numbers up to n = 12:"); for ( int n = 0 ; n <= 12 ; n++ ) { System.out.printf("%5s", n); ...
use strict; use warnings; use feature 'say'; use ntheory qw(factorial); use List::Util qw(max); sub Lah { my($n, $k) = @_; return factorial($n) if $k == 1; return 1 if $k == $n; return 0 if $k > $n; return 0 if $k < 1 or $n < 1; (factorial($n) * factorial($n - 1)) / (factorial($k) * factorial($...
Please provide an equivalent version of this Java code in Perl.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class LahNumbers { public static void main(String[] args) { System.out.println("Show the unsigned Lah numbers up to n = 12:"); for ( int n = 0 ; n <= 12 ; n++ ) { System.out.printf("%5s", n); ...
use strict; use warnings; use feature 'say'; use ntheory qw(factorial); use List::Util qw(max); sub Lah { my($n, $k) = @_; return factorial($n) if $k == 1; return 1 if $k == $n; return 0 if $k > $n; return 0 if $k < 1 or $n < 1; (factorial($n) * factorial($n - 1)) / (factorial($k) * factorial($...
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.util.Arrays; public class TwoSum { public static void main(String[] args) { long sum = 21; int[] arr = {0, 2, 11, 19, 90}; System.out.println(Arrays.toString(twoSum(arr, sum))); } public static int[] twoSum(int[] a, long target) { int i = 0, j = a.length - 1; ...
use strict; use warnings; use feature 'say'; sub two_sum{ my($sum,@numbers) = @_; my $i = 0; my $j = $ my @indices; while ($i < $j) { if ($numbers[$i] + $numbers[$j] == $sum) { push @indices, ($i, $j); $i++; } elsif ($numbers[$i] + $numbers[$j] < $sum) { $i++ } else ...
Port the following code from Java to Perl with equivalent syntax and logic.
import java.util.Arrays; public class TwoSum { public static void main(String[] args) { long sum = 21; int[] arr = {0, 2, 11, 19, 90}; System.out.println(Arrays.toString(twoSum(arr, sum))); } public static int[] twoSum(int[] a, long target) { int i = 0, j = a.length - 1; ...
use strict; use warnings; use feature 'say'; sub two_sum{ my($sum,@numbers) = @_; my $i = 0; my $j = $ my @indices; while ($i < $j) { if ($numbers[$i] + $numbers[$j] == $sum) { push @indices, ($i, $j); $i++; } elsif ($numbers[$i] + $numbers[$j] < $sum) { $i++ } else ...
Change the following Java code into Perl without altering its purpose.
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(...
use strict; use warnings; use feature 'say'; sub cocktail_sort { my @a = @_; my ($min, $max) = (0, $ while (1) { my $swapped_forward = 0; for my $i ($min .. $max) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1 ...
Write a version of this Java function in Perl with identical behavior.
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; ...
use strict; use warnings; use feature 'say'; use ntheory 'is_prime'; use enum qw(False True); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub is_unprimeable { my($n) = @_; return False if is_prime($n); my $chrs = length $n; for my $place (0..$chrs-1) { my $pow = 10**(...
Preserve the algorithm and functionality while converting the code from Java to Perl.
public class Tau { 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; ...
use strict; use warnings; use feature 'say'; use ntheory 'divisors'; my(@x,$n); do { push(@x,$n) unless $n % scalar(divisors(++$n)) } until 100 == @x; say "Tau numbers - first 100:\n" . ((sprintf "@{['%5d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
Change the following Java code into Perl without altering its purpose.
import java.math.BigInteger; public class PrimeSum { private static int digitSum(BigInteger bi) { int sum = 0; while (bi.compareTo(BigInteger.ZERO) > 0) { BigInteger[] dr = bi.divideAndRemainder(BigInteger.TEN); sum += dr[1].intValue(); bi = dr[0]; } ...
use strict; use warnings; use feature 'say'; use List::Util 'sum'; use ntheory 'is_prime'; my($limit, @p25) = 5000; is_prime($_) and 25 == sum(split '', $_) and push @p25, $_ for 1..$limit; say @p25 . " primes < $limit with digital sum 25:\n" . join ' ', @p25;
Change the programming language of this snippet from Java to Perl without modifying what it does.
import java.math.BigInteger; public class PrimeSum { private static int digitSum(BigInteger bi) { int sum = 0; while (bi.compareTo(BigInteger.ZERO) > 0) { BigInteger[] dr = bi.divideAndRemainder(BigInteger.TEN); sum += dr[1].intValue(); bi = dr[0]; } ...
use strict; use warnings; use feature 'say'; use List::Util 'sum'; use ntheory 'is_prime'; my($limit, @p25) = 5000; is_prime($_) and 25 == sum(split '', $_) and push @p25, $_ for 1..$limit; say @p25 . " primes < $limit with digital sum 25:\n" . join ' ', @p25;
Change the following Java code into Perl without altering its purpose.
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...
use strict; use warnings; my @queue = my @primedigits = ( 2, 3, 5, 7 ); my $numbers; while( my $n = shift @queue ) { if( eval $n == 13 ) { $numbers .= $n =~ tr/+//dr . " "; } elsif( eval $n < 13 ) { push @queue, map "$n+$_", @primedigits; } } print $numbers =~ s/.{1,80}\K /\n/gr;
Generate a Perl translation of this Java snippet without changing its computational steps.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class DeepCopy { public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center"...
use strict; use warnings; use Storable; use Data::Dumper; my $src = { foo => 0, bar => [0, 1] }; $src->{baz} = $src; my $dst = Storable::dclone($src); print Dumper($src); print Dumper($dst);
Please provide an equivalent version of this Java code in Perl.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class DeepCopy { public static void main(String[] args) { Person p1 = new Person("Clark", "Kent", new Address("1 World Center"...
use strict; use warnings; use Storable; use Data::Dumper; my $src = { foo => 0, bar => [0, 1] }; $src->{baz} = $src; my $dst = Storable::dclone($src); print Dumper($src); print Dumper($dst);
Preserve the algorithm and functionality while converting the code from Java to Perl.
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0...
use strict; use warnings; use feature 'say'; use List::Util 'min'; use ntheory 'is_prime'; sub rotate { my($i,@a) = @_; join '', @a[$i .. @a-1, 0 .. $i-1] } sub isCircular { my ($n) = @_; return 0 unless is_prime($n); my @circular = split //, $n; return 0 if min(@circular) < $circular[0]; for (1 ....
Translate this program into Perl but keep the logic exactly as in Java.
public class Frobenius { public static void main(String[] args) { final int limit = 1000000; System.out.printf("Frobenius numbers less than %d (asterisk marks primes):\n", limit); PrimeGenerator primeGen = new PrimeGenerator(1000, 100000); int prime1 = primeGen.nextPrime(); f...
use strict; use warnings; use feature 'say'; use ntheory <nth_prime primes>; use List::MoreUtils qw(slide); my(@F,$n); do { ++$n and push @F, nth_prime($n) * nth_prime($n+1) - (nth_prime($n) + nth_prime($n+1)) } until $F[-1] >= 10000; say "$ my $limit = 10_000; say "\n" . join ' ', grep { $_ < $limit } slide { $a *...
Generate an equivalent Perl version of this Java code.
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...
sub psort { my ($x, $d) = @_; unless ($d //= $ $x->[$_] < $x->[$_ - 1] and return for 1 .. $ return 1 } for (0 .. $d) { unshift @$x, splice @$x, $d, 1; next if $x->[$d] < $x->[$d - 1]; return 1 if p...
Convert the following code from Java to Perl, ensuring the logic remains intact.
import java.math.BigInteger; public class IntegerRoots { private static BigInteger iRoot(BigInteger base, int n) { if (base.compareTo(BigInteger.ZERO) < 0 || n <= 0) { throw new IllegalArgumentException(); } int n1 = n - 1; BigInteger n2 = BigInteger.valueOf(n); ...
use bigint; sub integer_root { our($a,$b) = @_; our $a1 = $a - 1; my $c = 1; my $d = f($c); my $e = f($d); ($c, $d, $e) = ($d, $e, f($e)) until $c==$d || $c==$e; return $d < $e ? $d : $e; sub f { ($a1*$_[0]+$b/$_[0]**$a1)/$a } } print integer_root( 3, 8), "\n"; print integer_root( 3, ...
Produce a functionally identical Perl code for the snippet given in Java.
import java.math.BigInteger; public class IntegerRoots { private static BigInteger iRoot(BigInteger base, int n) { if (base.compareTo(BigInteger.ZERO) < 0 || n <= 0) { throw new IllegalArgumentException(); } int n1 = n - 1; BigInteger n2 = BigInteger.valueOf(n); ...
use bigint; sub integer_root { our($a,$b) = @_; our $a1 = $a - 1; my $c = 1; my $d = f($c); my $e = f($d); ($c, $d, $e) = ($d, $e, f($e)) until $c==$d || $c==$e; return $d < $e ? $d : $e; sub f { ($a1*$_[0]+$b/$_[0]**$a1)/$a } } print integer_root( 3, 8), "\n"; print integer_root( 3, ...
Convert this Java snippet to Perl and keep its semantics consistent.
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()); } }
package Life; use strict; use warnings; sub meaning_of_life { return 42; } unless(caller) { print "Main: The meaning of life is " . meaning_of_life() . "\n"; }
Rewrite this program in Perl while keeping its functionality equivalent to the Java version.
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()); } }
package Life; use strict; use warnings; sub meaning_of_life { return 42; } unless(caller) { print "Main: The meaning of life is " . meaning_of_life() . "\n"; }
Please provide an equivalent version of this Java code in Perl.
public class NicePrimes { private static boolean isPrime(long n) { if (n < 2) { return false; } if (n % 2 == 0L) { return n == 2L; } if (n % 3 == 0L) { return n == 3L; } var p = 5L; while (p * p <= n) { ...
use strict; use warnings; use ntheory 'is_prime'; use List::Util qw(sum); sub digital_root { my ($n) = @_; do { $n = sum split '', $n } until 1 == length $n; $n } my($low, $high, $cnt, @nice_primes) = (500,1000); is_prime($_) and is_prime(digital_root($_)) and push @nice_primes, $_ for $low+1 .. $high-1;...
Maintain the same structure and functionality when rewriting this code in Perl.
public class NicePrimes { private static boolean isPrime(long n) { if (n < 2) { return false; } if (n % 2 == 0L) { return n == 2L; } if (n % 3 == 0L) { return n == 3L; } var p = 5L; while (p * p <= n) { ...
use strict; use warnings; use ntheory 'is_prime'; use List::Util qw(sum); sub digital_root { my ($n) = @_; do { $n = sum split '', $n } until 1 == length $n; $n } my($low, $high, $cnt, @nice_primes) = (500,1000); is_prime($_) and is_prime(digital_root($_)) and push @nice_primes, $_ for $low+1 .. $high-1;...
Can you help me rewrite this code in Perl instead of Java, keeping it the same logically?
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...
use strict ; use warnings ; use DateTime ; for my $i( 1..12 ) { my $date = DateTime->last_day_of_month( year => $ARGV[ 0 ] , month => $i ) ; while ( $date->dow != 7 ) { $date = $date->subtract( days => 1 ) ; } my $ymd = $date->ymd ; print "$ymd\n" ; }
Change the following Java code into Perl without altering its purpose.
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...
use strict ; use warnings ; use DateTime ; for my $i( 1..12 ) { my $date = DateTime->last_day_of_month( year => $ARGV[ 0 ] , month => $i ) ; while ( $date->dow != 7 ) { $date = $date->subtract( days => 1 ) ; } my $ymd = $date->ymd ; print "$ymd\n" ; }
Generate an equivalent Perl version of this Java code.
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; public class RandomLatinSquares { private static void printSquare(List<List<Integer>> latin) { for (List<Integer> row : latin) { Iterator<Integer> it = row.itera...
use strict; use warnings; use feature 'say'; use List::Util 'shuffle'; sub random_ls { my($n) = @_; my(@cols,@symbols,@ls_sym); my @ls = [0,]; for my $i (1..$n-1) { @{$ls[$i]} = @{$ls[0]}; splice(@{$ls[$_]}, $_, 0, $i) for 0..$i; } @cols = shuffle 0..$n-1; @ls = ...
Port the following code from Java to Perl with equivalent syntax and logic.
import java.io.*; import java.util.*; public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } c...
use strict; use warnings; use feature 'say'; use List::Util qw(uniqstr any); my(%words,@teacups,%seen); open my $fh, '<', 'ref/wordlist.10000'; while (<$fh>) { chomp(my $w = uc $_); next if length $w < 3; push @{$words{join '', sort split //, $w}}, $w;} for my $these (values %words) { next if @$these...
Write the same algorithm in Perl as shown in this Java implementation.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } }...
use strict; use warnings; use Math::AnyNum qw(sum polymod); sub fairshare { my($b, $n) = @_; sprintf '%3d'x$n, map { sum ( polymod($_, $b, $b )) % $b } 0 .. $n-1; } for (<2 3 5 11>) { printf "%3s:%s\n", $_, fairshare($_, 25); }
Write the same code in Perl as shown below in Java.
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream; public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); } private static boolean isEsthetic(long n, long b) { if (n == 0) { ...
use 5.020; use warnings; use experimental qw(signatures); use ntheory qw(fromdigits todigitstring); sub generate_esthetic ($root, $upto, $callback, $base = 10) { my $v = fromdigits($root, $base); return if ($v > $upto); $callback->($v); my $t = $root->[-1]; __SUB__->([@$root, $t + 1], $upto, $...
Translate the given Java code snippet into Perl without altering its behavior.
package org.rosettacode.java; import java.util.Arrays; import java.util.stream.IntStream; public class HeapsAlgorithm { public static void main(String[] args) { Object[] array = IntStream.range(0, 4) .boxed() .toArray(); HeapsAlgorithm algorithm = new HeapsAlgorithm(); algorithm.recursive(array); Sy...
use strict; use warnings; sub perms :prototype(&@) { my $callback = shift; my @perm = map [$_, -1], @_; $perm[0][1] = 0; my $sign = 1; while( ) { $callback->($sign, map $_->[0], @perm); $sign *= -1; my ($chosen, $index) = (-1, -1); for my $i ( 0 .. $ ($chose...
Transform the following Java implementation into Perl, maintaining the same output and logic.
import java.util.List; import java.util.Random; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class Rpg { private static final Random random = new Random(); public static int genAttribute() { return random.ints(1, 6 + 1) .limit(4) ...
use strict; use List::Util 'sum'; my ($min_sum, $hero_attr_min, $hero_count_min) = <75 15 3>; my @attr_names = <Str Int Wis Dex Con Cha>; sub heroic { scalar grep { $_ >= $hero_attr_min } @_ } sub roll_skip_lowest { my($dice, $sides) = @_; sum( (sort map { 1 + int rand($sides) } 1..$dice)[1..$dice-1] ); } m...
Translate this program into Perl but keep the logic exactly as in Java.
import java.util.Arrays; public class Kolakoski { private static class Crutch { final int len; int[] s; int i; Crutch(int len) { this.len = len; s = new int[len]; i = 0; } void repeat(int count) { for (int j = 0; j < ...
sub kolakoski { my($terms,@seed) = @_; my @k; my $k = $seed[0] == 1 ? 1 : 0; if ($k == 1) { @k = (1, split //, (($seed[1]) x $seed[1])) } else { @k = ($seed[0]) x $seed[0] } do { $k++; push @k, ($seed[$k % @seed]) x $k[$k]; } until $terms <= @k; @k[0..$terms-1] } ...